2
0

upgrade.php 154 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624
  1. <?php
  2. /**
  3. * Simple Machines Forum (SMF)
  4. *
  5. * @package SMF
  6. * @author Simple Machines http://www.simplemachines.org
  7. * @copyright 2013 Simple Machines and individual contributors
  8. * @license http://www.simplemachines.org/about/smf/license.php BSD
  9. *
  10. * @version 2.1 Alpha 1
  11. */
  12. // Version information...
  13. define('SMF_VERSION', '2.1 Alpha 1');
  14. define('SMF_LANG_VERSION', '2.1 Alpha 1');
  15. $GLOBALS['required_php_version'] = '5.1.0';
  16. $GLOBALS['required_mysql_version'] = '4.0.18';
  17. $databases = array(
  18. 'mysqli' => array(
  19. 'name' => 'MySQLi',
  20. 'version' => '4.0.18',
  21. 'version_check' => 'global $db_connection; return min(mysqli_get_server_info($db_connection), mysqli_get_client_info());',
  22. 'utf8_support' => true,
  23. 'utf8_version' => '4.1.0',
  24. 'utf8_version_check' => 'global $db_connection; return mysqli_get_server_info($db_connection);',
  25. 'alter_support' => true,
  26. ),
  27. 'mysql' => array(
  28. 'name' => 'MySQL',
  29. 'version' => '4.0.18',
  30. 'version_check' => 'return min(mysql_get_server_info(), mysql_get_client_info());',
  31. 'utf8_support' => true,
  32. 'utf8_version' => '4.1.0',
  33. 'utf8_version_check' => 'return mysql_get_server_info();',
  34. 'alter_support' => true,
  35. ),
  36. 'postgresql' => array(
  37. 'name' => 'PostgreSQL',
  38. 'version' => '8.0',
  39. 'version_check' => '$version = pg_version(); return $version[\'client\'];',
  40. 'always_has_db' => true,
  41. ),
  42. 'sqlite' => array(
  43. 'name' => 'SQLite',
  44. 'version' => '1',
  45. 'version_check' => 'return 1;',
  46. 'always_has_db' => true,
  47. ),
  48. );
  49. // General options for the script.
  50. $timeLimitThreshold = 3;
  51. $upgrade_path = dirname(__FILE__);
  52. $upgradeurl = $_SERVER['PHP_SELF'];
  53. // Where the SMF images etc are kept.
  54. $smfsite = 'http://www.simplemachines.org/smf';
  55. // Disable the need for admins to login?
  56. $disable_security = false;
  57. // How long, in seconds, must admin be inactive to allow someone else to run?
  58. $upcontext['inactive_timeout'] = 10;
  59. // All the steps in detail.
  60. // Number,Name,Function,Progress Weight.
  61. $upcontext['steps'] = array(
  62. 0 => array(1, 'Login', 'WelcomeLogin', 2),
  63. 1 => array(2, 'Upgrade Options', 'UpgradeOptions', 2),
  64. 2 => array(3, 'Backup', 'BackupDatabase', 10),
  65. 3 => array(4, 'Database Changes', 'DatabaseChanges', 70),
  66. // This is removed as it doesn't really work right at the moment.
  67. //4 => array(5, 'Cleanup Mods', 'CleanupMods', 10),
  68. 4 => array(5, 'Delete Upgrade', 'DeleteUpgrade', 1),
  69. );
  70. // Just to remember which one has files in it.
  71. $upcontext['database_step'] = 3;
  72. @set_time_limit(600);
  73. if (!ini_get('safe_mode'))
  74. {
  75. ini_set('mysql.connect_timeout', -1);
  76. ini_set('default_socket_timeout', 900);
  77. }
  78. // Clean the upgrade path if this is from the client.
  79. if (!empty($_SERVER['argv']) && php_sapi_name() == 'cli' && empty($_SERVER['REMOTE_ADDR']))
  80. for ($i = 1; $i < $_SERVER['argc']; $i++)
  81. {
  82. if (preg_match('~^--path=(.+)$~', $_SERVER['argv'][$i], $match) != 0)
  83. $upgrade_path = substr($match[1], -1) == '/' ? substr($match[1], 0, -1) : $match[1];
  84. }
  85. // Are we from the client?
  86. if (php_sapi_name() == 'cli' && empty($_SERVER['REMOTE_ADDR']))
  87. {
  88. $command_line = true;
  89. $disable_security = 1;
  90. }
  91. else
  92. $command_line = false;
  93. // Load this now just because we can.
  94. require_once($upgrade_path . '/Settings.php');
  95. // Are we logged in?
  96. if (isset($upgradeData))
  97. {
  98. $upcontext['user'] = unserialize(base64_decode($upgradeData));
  99. // Check for sensible values.
  100. if (empty($upcontext['user']['started']) || $upcontext['user']['started'] < time() - 86400)
  101. $upcontext['user']['started'] = time();
  102. if (empty($upcontext['user']['updated']) || $upcontext['user']['updated'] < time() - 86400)
  103. $upcontext['user']['updated'] = 0;
  104. $upcontext['started'] = $upcontext['user']['started'];
  105. $upcontext['updated'] = $upcontext['user']['updated'];
  106. }
  107. // Nothing sensible?
  108. if (empty($upcontext['updated']))
  109. {
  110. $upcontext['started'] = time();
  111. $upcontext['updated'] = 0;
  112. $upcontext['user'] = array(
  113. 'id' => 0,
  114. 'name' => 'Guest',
  115. 'pass' => 0,
  116. 'started' => $upcontext['started'],
  117. 'updated' => $upcontext['updated'],
  118. );
  119. }
  120. // Load up some essential data...
  121. loadEssentialData();
  122. // Are we going to be mimic'ing SSI at this point?
  123. if (isset($_GET['ssi']))
  124. {
  125. require_once($sourcedir . '/Subs.php');
  126. require_once($sourcedir . '/Errors.php');
  127. require_once($sourcedir . '/Logging.php');
  128. require_once($sourcedir . '/Load.php');
  129. require_once($sourcedir . '/Security.php');
  130. require_once($sourcedir . '/Subs-Package.php');
  131. loadUserSettings();
  132. loadPermissions();
  133. }
  134. // All the non-SSI stuff.
  135. if (!function_exists('ip2range'))
  136. require_once($sourcedir . '/Subs.php');
  137. if (!function_exists('un_htmlspecialchars'))
  138. {
  139. function un_htmlspecialchars($string)
  140. {
  141. return strtr($string, array_flip(get_html_translation_table(HTML_SPECIALCHARS, ENT_QUOTES)) + array('&#039;' => '\'', '&nbsp;' => ' '));
  142. }
  143. }
  144. if (!function_exists('text2words'))
  145. {
  146. function text2words($text)
  147. {
  148. global $smcFunc;
  149. // Step 1: Remove entities/things we don't consider words:
  150. $words = preg_replace('~(?:[\x0B\0\xA0\t\r\s\n(){}\\[\\]<>!@$%^*.,:+=`\~\?/\\\\]+|&(?:amp|lt|gt|quot);)+~', ' ', $text);
  151. // Step 2: Entities we left to letters, where applicable, lowercase.
  152. $words = preg_replace('~([^&\d]|^)[#;]~', '$1 ', un_htmlspecialchars(strtolower($words)));
  153. // Step 3: Ready to split apart and index!
  154. $words = explode(' ', $words);
  155. $returned_words = array();
  156. foreach ($words as $word)
  157. {
  158. $word = trim($word, '-_\'');
  159. if ($word != '')
  160. $returned_words[] = substr($word, 0, 20);
  161. }
  162. return array_unique($returned_words);
  163. }
  164. }
  165. if (!function_exists('clean_cache'))
  166. {
  167. // Empty out the cache folder.
  168. function clean_cache($type = '')
  169. {
  170. global $cachedir, $sourcedir;
  171. // No directory = no game.
  172. if (!is_dir($cachedir))
  173. return;
  174. // Remove the files in SMF's own disk cache, if any
  175. $dh = opendir($cachedir);
  176. while ($file = readdir($dh))
  177. {
  178. if ($file != '.' && $file != '..' && $file != 'index.php' && $file != '.htaccess' && (!$type || substr($file, 0, strlen($type)) == $type))
  179. @unlink($cachedir . '/' . $file);
  180. }
  181. closedir($dh);
  182. // Invalidate cache, to be sure!
  183. // ... as long as Load.php can be modified, anyway.
  184. @touch($sourcedir . '/' . 'Load.php');
  185. clearstatcache();
  186. }
  187. }
  188. // MD5 Encryption.
  189. if (!function_exists('md5_hmac'))
  190. {
  191. function md5_hmac($data, $key)
  192. {
  193. if (strlen($key) > 64)
  194. $key = pack('H*', md5($key));
  195. $key = str_pad($key, 64, chr(0x00));
  196. $k_ipad = $key ^ str_repeat(chr(0x36), 64);
  197. $k_opad = $key ^ str_repeat(chr(0x5c), 64);
  198. return md5($k_opad . pack('H*', md5($k_ipad . $data)));
  199. }
  200. }
  201. // http://www.faqs.org/rfcs/rfc959.html
  202. if (!class_exists('ftp_connection'))
  203. {
  204. class ftp_connection
  205. {
  206. var $connection = 'no_connection', $error = false, $last_message, $pasv = array();
  207. // Create a new FTP connection...
  208. function ftp_connection($ftp_server, $ftp_port = 21, $ftp_user = 'anonymous', $ftp_pass = '[email protected]')
  209. {
  210. if ($ftp_server !== null)
  211. $this->connect($ftp_server, $ftp_port, $ftp_user, $ftp_pass);
  212. }
  213. function connect($ftp_server, $ftp_port = 21, $ftp_user = 'anonymous', $ftp_pass = '[email protected]')
  214. {
  215. if (substr($ftp_server, 0, 6) == 'ftp://')
  216. $ftp_server = substr($ftp_server, 6);
  217. elseif (substr($ftp_server, 0, 7) == 'ftps://')
  218. $ftp_server = 'ssl://' . substr($ftp_server, 7);
  219. if (substr($ftp_server, 0, 7) == 'http://')
  220. $ftp_server = substr($ftp_server, 7);
  221. $ftp_server = strtr($ftp_server, array('/' => '', ':' => '', '@' => ''));
  222. // Connect to the FTP server.
  223. $this->connection = @fsockopen($ftp_server, $ftp_port, $err, $err, 5);
  224. if (!$this->connection)
  225. {
  226. $this->error = 'bad_server';
  227. return;
  228. }
  229. // Get the welcome message...
  230. if (!$this->check_response(220))
  231. {
  232. $this->error = 'bad_response';
  233. return;
  234. }
  235. // Send the username, it should ask for a password.
  236. fwrite($this->connection, 'USER ' . $ftp_user . "\r\n");
  237. if (!$this->check_response(331))
  238. {
  239. $this->error = 'bad_username';
  240. return;
  241. }
  242. // Now send the password... and hope it goes okay.
  243. fwrite($this->connection, 'PASS ' . $ftp_pass . "\r\n");
  244. if (!$this->check_response(230))
  245. {
  246. $this->error = 'bad_password';
  247. return;
  248. }
  249. }
  250. function chdir($ftp_path)
  251. {
  252. if (!is_resource($this->connection))
  253. return false;
  254. // No slash on the end, please...
  255. if (substr($ftp_path, -1) == '/' && $ftp_path !== '/')
  256. $ftp_path = substr($ftp_path, 0, -1);
  257. fwrite($this->connection, 'CWD ' . $ftp_path . "\r\n");
  258. if (!$this->check_response(250))
  259. {
  260. $this->error = 'bad_path';
  261. return false;
  262. }
  263. return true;
  264. }
  265. function chmod($ftp_file, $chmod)
  266. {
  267. if (!is_resource($this->connection))
  268. return false;
  269. // Convert the chmod value from octal (0777) to text ("777").
  270. fwrite($this->connection, 'SITE CHMOD ' . decoct($chmod) . ' ' . $ftp_file . "\r\n");
  271. if (!$this->check_response(200))
  272. {
  273. $this->error = 'bad_file';
  274. return false;
  275. }
  276. return true;
  277. }
  278. function unlink($ftp_file)
  279. {
  280. // We are actually connected, right?
  281. if (!is_resource($this->connection))
  282. return false;
  283. // Delete file X.
  284. fwrite($this->connection, 'DELE ' . $ftp_file . "\r\n");
  285. if (!$this->check_response(250))
  286. {
  287. fwrite($this->connection, 'RMD ' . $ftp_file . "\r\n");
  288. // Still no love?
  289. if (!$this->check_response(250))
  290. {
  291. $this->error = 'bad_file';
  292. return false;
  293. }
  294. }
  295. return true;
  296. }
  297. function check_response($desired)
  298. {
  299. // Wait for a response that isn't continued with -, but don't wait too long.
  300. $time = time();
  301. do
  302. $this->last_message = fgets($this->connection, 1024);
  303. while (substr($this->last_message, 3, 1) != ' ' && time() - $time < 5);
  304. // Was the desired response returned?
  305. return is_array($desired) ? in_array(substr($this->last_message, 0, 3), $desired) : substr($this->last_message, 0, 3) == $desired;
  306. }
  307. function passive()
  308. {
  309. // We can't create a passive data connection without a primary one first being there.
  310. if (!is_resource($this->connection))
  311. return false;
  312. // Request a passive connection - this means, we'll talk to you, you don't talk to us.
  313. @fwrite($this->connection, 'PASV' . "\r\n");
  314. $time = time();
  315. do
  316. $response = fgets($this->connection, 1024);
  317. while (substr($response, 3, 1) != ' ' && time() - $time < 5);
  318. // If it's not 227, we weren't given an IP and port, which means it failed.
  319. if (substr($response, 0, 4) != '227 ')
  320. {
  321. $this->error = 'bad_response';
  322. return false;
  323. }
  324. // Snatch the IP and port information, or die horribly trying...
  325. if (preg_match('~\((\d+),\s*(\d+),\s*(\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+))\)~', $response, $match) == 0)
  326. {
  327. $this->error = 'bad_response';
  328. return false;
  329. }
  330. // This is pretty simple - store it for later use ;).
  331. $this->pasv = array('ip' => $match[1] . '.' . $match[2] . '.' . $match[3] . '.' . $match[4], 'port' => $match[5] * 256 + $match[6]);
  332. return true;
  333. }
  334. function create_file($ftp_file)
  335. {
  336. // First, we have to be connected... very important.
  337. if (!is_resource($this->connection))
  338. return false;
  339. // I'd like one passive mode, please!
  340. if (!$this->passive())
  341. return false;
  342. // Seems logical enough, so far...
  343. fwrite($this->connection, 'STOR ' . $ftp_file . "\r\n");
  344. // Okay, now we connect to the data port. If it doesn't work out, it's probably "file already exists", etc.
  345. $fp = @fsockopen($this->pasv['ip'], $this->pasv['port'], $err, $err, 5);
  346. if (!$fp || !$this->check_response(150))
  347. {
  348. $this->error = 'bad_file';
  349. @fclose($fp);
  350. return false;
  351. }
  352. // This may look strange, but we're just closing it to indicate a zero-byte upload.
  353. fclose($fp);
  354. if (!$this->check_response(226))
  355. {
  356. $this->error = 'bad_response';
  357. return false;
  358. }
  359. return true;
  360. }
  361. function list_dir($ftp_path = '', $search = false)
  362. {
  363. // Are we even connected...?
  364. if (!is_resource($this->connection))
  365. return false;
  366. // Passive... non-agressive...
  367. if (!$this->passive())
  368. return false;
  369. // Get the listing!
  370. fwrite($this->connection, 'LIST -1' . ($search ? 'R' : '') . ($ftp_path == '' ? '' : ' ' . $ftp_path) . "\r\n");
  371. // Connect, assuming we've got a connection.
  372. $fp = @fsockopen($this->pasv['ip'], $this->pasv['port'], $err, $err, 5);
  373. if (!$fp || !$this->check_response(array(150, 125)))
  374. {
  375. $this->error = 'bad_response';
  376. @fclose($fp);
  377. return false;
  378. }
  379. // Read in the file listing.
  380. $data = '';
  381. while (!feof($fp))
  382. $data .= fread($fp, 4096);
  383. fclose($fp);
  384. // Everything go okay?
  385. if (!$this->check_response(226))
  386. {
  387. $this->error = 'bad_response';
  388. return false;
  389. }
  390. return $data;
  391. }
  392. function locate($file, $listing = null)
  393. {
  394. if ($listing === null)
  395. $listing = $this->list_dir('', true);
  396. $listing = explode("\n", $listing);
  397. @fwrite($this->connection, 'PWD' . "\r\n");
  398. $time = time();
  399. do
  400. $response = fgets($this->connection, 1024);
  401. while (substr($response, 3, 1) != ' ' && time() - $time < 5);
  402. // Check for 257!
  403. if (preg_match('~^257 "(.+?)" ~', $response, $match) != 0)
  404. $current_dir = strtr($match[1], array('""' => '"'));
  405. else
  406. $current_dir = '';
  407. for ($i = 0, $n = count($listing); $i < $n; $i++)
  408. {
  409. if (trim($listing[$i]) == '' && isset($listing[$i + 1]))
  410. {
  411. $current_dir = substr(trim($listing[++$i]), 0, -1);
  412. $i++;
  413. }
  414. // Okay, this file's name is:
  415. $listing[$i] = $current_dir . '/' . trim(strlen($listing[$i]) > 30 ? strrchr($listing[$i], ' ') : $listing[$i]);
  416. if (substr($file, 0, 1) == '*' && substr($listing[$i], -(strlen($file) - 1)) == substr($file, 1))
  417. return $listing[$i];
  418. if (substr($file, -1) == '*' && substr($listing[$i], 0, strlen($file) - 1) == substr($file, 0, -1))
  419. return $listing[$i];
  420. if (basename($listing[$i]) == $file || $listing[$i] == $file)
  421. return $listing[$i];
  422. }
  423. return false;
  424. }
  425. function create_dir($ftp_dir)
  426. {
  427. // We must be connected to the server to do something.
  428. if (!is_resource($this->connection))
  429. return false;
  430. // Make this new beautiful directory!
  431. fwrite($this->connection, 'MKD ' . $ftp_dir . "\r\n");
  432. if (!$this->check_response(257))
  433. {
  434. $this->error = 'bad_file';
  435. return false;
  436. }
  437. return true;
  438. }
  439. function detect_path($filesystem_path, $lookup_file = null)
  440. {
  441. $username = '';
  442. if (isset($_SERVER['DOCUMENT_ROOT']))
  443. {
  444. if (preg_match('~^/home[2]?/([^/]+?)/public_html~', $_SERVER['DOCUMENT_ROOT'], $match))
  445. {
  446. $username = $match[1];
  447. $path = strtr($_SERVER['DOCUMENT_ROOT'], array('/home/' . $match[1] . '/' => '', '/home2/' . $match[1] . '/' => ''));
  448. if (substr($path, -1) == '/')
  449. $path = substr($path, 0, -1);
  450. if (strlen(dirname($_SERVER['PHP_SELF'])) > 1)
  451. $path .= dirname($_SERVER['PHP_SELF']);
  452. }
  453. elseif (substr($filesystem_path, 0, 9) == '/var/www/')
  454. $path = substr($filesystem_path, 8);
  455. else
  456. $path = strtr(strtr($filesystem_path, array('\\' => '/')), array($_SERVER['DOCUMENT_ROOT'] => ''));
  457. }
  458. else
  459. $path = '';
  460. if (is_resource($this->connection) && $this->list_dir($path) == '')
  461. {
  462. $data = $this->list_dir('', true);
  463. if ($lookup_file === null)
  464. $lookup_file = $_SERVER['PHP_SELF'];
  465. $found_path = dirname($this->locate('*' . basename(dirname($lookup_file)) . '/' . basename($lookup_file), $data));
  466. if ($found_path == false)
  467. $found_path = dirname($this->locate(basename($lookup_file)));
  468. if ($found_path != false)
  469. $path = $found_path;
  470. }
  471. elseif (is_resource($this->connection))
  472. $found_path = true;
  473. return array($username, $path, isset($found_path));
  474. }
  475. function close()
  476. {
  477. // Goodbye!
  478. fwrite($this->connection, 'QUIT' . "\r\n");
  479. fclose($this->connection);
  480. return true;
  481. }
  482. }
  483. }
  484. // Don't do security check if on Yabbse
  485. if (!isset($modSettings['smfVersion']))
  486. $disable_security = true;
  487. // This only exists if we're on SMF ;)
  488. if (isset($modSettings['smfVersion']))
  489. {
  490. $request = $smcFunc['db_query']('', '
  491. SELECT variable, value
  492. FROM {db_prefix}themes
  493. WHERE id_theme = {int:id_theme}
  494. AND variable IN ({string:theme_url}, {string:theme_dir}, {string:images_url})',
  495. array(
  496. 'id_theme' => 1,
  497. 'theme_url' => 'theme_url',
  498. 'theme_dir' => 'theme_dir',
  499. 'images_url' => 'images_url',
  500. 'db_error_skip' => true,
  501. )
  502. );
  503. while ($row = $smcFunc['db_fetch_assoc']($request))
  504. $modSettings[$row['variable']] = $row['value'];
  505. $smcFunc['db_free_result']($request);
  506. }
  507. if (!isset($modSettings['theme_url']))
  508. {
  509. $modSettings['theme_dir'] = $boarddir . '/Themes/default';
  510. $modSettings['theme_url'] = 'Themes/default';
  511. $modSettings['images_url'] = 'Themes/default/images';
  512. }
  513. if (!isset($settings['default_theme_url']))
  514. $settings['default_theme_url'] = $modSettings['theme_url'];
  515. if (!isset($settings['default_theme_dir']))
  516. $settings['default_theme_dir'] = $modSettings['theme_dir'];
  517. $upcontext['is_large_forum'] = (empty($modSettings['smfVersion']) || $modSettings['smfVersion'] <= '1.1 RC1') && !empty($modSettings['totalMessages']) && $modSettings['totalMessages'] > 75000;
  518. // Default title...
  519. $upcontext['page_title'] = isset($modSettings['smfVersion']) ? 'Updating Your SMF Install!' : 'Upgrading from YaBB SE!';
  520. $upcontext['right_to_left'] = isset($txt['lang_rtl']) ? $txt['lang_rtl'] : false;
  521. // Have we got tracking data - if so use it (It will be clean!)
  522. if (isset($_GET['data']))
  523. {
  524. $upcontext['upgrade_status'] = unserialize(base64_decode($_GET['data']));
  525. $upcontext['current_step'] = $upcontext['upgrade_status']['curstep'];
  526. $upcontext['language'] = $upcontext['upgrade_status']['lang'];
  527. $upcontext['rid'] = $upcontext['upgrade_status']['rid'];
  528. $is_debug = $upcontext['upgrade_status']['debug'];
  529. $support_js = $upcontext['upgrade_status']['js'];
  530. // Load the language.
  531. if (file_exists($modSettings['theme_dir'] . '/languages/Install.' . $upcontext['language'] . '.php'))
  532. require_once($modSettings['theme_dir'] . '/languages/Install.' . $upcontext['language'] . '.php');
  533. }
  534. // Set the defaults.
  535. else
  536. {
  537. $upcontext['current_step'] = 0;
  538. $upcontext['rid'] = mt_rand(0, 5000);
  539. $upcontext['upgrade_status'] = array(
  540. 'curstep' => 0,
  541. 'lang' => isset($_GET['lang']) ? $_GET['lang'] : basename($language, '.lng'),
  542. 'rid' => $upcontext['rid'],
  543. 'pass' => 0,
  544. 'debug' => 0,
  545. 'js' => 0,
  546. );
  547. $upcontext['language'] = $upcontext['upgrade_status']['lang'];
  548. }
  549. // If this isn't the first stage see whether they are logging in and resuming.
  550. if ($upcontext['current_step'] != 0 || !empty($upcontext['user']['step']))
  551. checkLogin();
  552. if ($command_line)
  553. cmdStep0();
  554. // Don't error if we're using xml.
  555. if (isset($_GET['xml']))
  556. $upcontext['return_error'] = true;
  557. // Loop through all the steps doing each one as required.
  558. $upcontext['overall_percent'] = 0;
  559. foreach ($upcontext['steps'] as $num => $step)
  560. {
  561. if ($num >= $upcontext['current_step'])
  562. {
  563. // The current weight of this step in terms of overall progress.
  564. $upcontext['step_weight'] = $step[3];
  565. // Make sure we reset the skip button.
  566. $upcontext['skip'] = false;
  567. // We cannot proceed if we're not logged in.
  568. if ($num != 0 && !$disable_security && $upcontext['user']['pass'] != $upcontext['upgrade_status']['pass'])
  569. {
  570. $upcontext['steps'][0][2]();
  571. break;
  572. }
  573. // Call the step and if it returns false that means pause!
  574. if (function_exists($step[2]) && $step[2]() === false)
  575. break;
  576. elseif (function_exists($step[2]))
  577. $upcontext['current_step']++;
  578. }
  579. $upcontext['overall_percent'] += $step[3];
  580. }
  581. upgradeExit();
  582. // Exit the upgrade script.
  583. function upgradeExit($fallThrough = false)
  584. {
  585. global $upcontext, $upgradeurl, $boarddir, $command_line;
  586. // Save where we are...
  587. if (!empty($upcontext['current_step']) && !empty($upcontext['user']['id']))
  588. {
  589. $upcontext['user']['step'] = $upcontext['current_step'];
  590. $upcontext['user']['substep'] = $_GET['substep'];
  591. $upcontext['user']['updated'] = time();
  592. $upgradeData = base64_encode(serialize($upcontext['user']));
  593. copy($boarddir . '/Settings.php', $boarddir . '/Settings_bak.php');
  594. changeSettings(array('upgradeData' => '"' . $upgradeData . '"'));
  595. updateLastError();
  596. }
  597. // Handle the progress of the step, if any.
  598. if (!empty($upcontext['step_progress']) && isset($upcontext['steps'][$upcontext['current_step']]))
  599. {
  600. $upcontext['step_progress'] = round($upcontext['step_progress'], 1);
  601. $upcontext['overall_percent'] += $upcontext['step_progress'] * ($upcontext['steps'][$upcontext['current_step']][3] / 100);
  602. }
  603. $upcontext['overall_percent'] = (int) $upcontext['overall_percent'];
  604. // We usually dump our templates out.
  605. if (!$fallThrough)
  606. {
  607. // This should not happen my dear... HELP ME DEVELOPERS!!
  608. if (!empty($command_line))
  609. {
  610. if (function_exists('debug_print_backtrace'))
  611. debug_print_backtrace();
  612. echo "\n" . 'Error: Unexpected call to use the ' . (isset($upcontext['sub_template']) ? $upcontext['sub_template'] : '') . ' template. Please copy and paste all the text above and visit the SMF support forum to tell the Developers that they\'ve made a boo boo; they\'ll get you up and running again.';
  613. flush();
  614. die();
  615. }
  616. if (!isset($_GET['xml']))
  617. template_upgrade_above();
  618. else
  619. {
  620. header('Content-Type: text/xml; charset=ISO-8859-1');
  621. // Sadly we need to retain the $_GET data thanks to the old upgrade scripts.
  622. $upcontext['get_data'] = array();
  623. foreach ($_GET as $k => $v)
  624. {
  625. if (substr($k, 0, 3) != 'amp' && !in_array($k, array('xml', 'substep', 'lang', 'data', 'step', 'filecount')))
  626. {
  627. $upcontext['get_data'][$k] = $v;
  628. }
  629. }
  630. template_xml_above();
  631. }
  632. // Call the template.
  633. if (isset($upcontext['sub_template']))
  634. {
  635. $upcontext['upgrade_status']['curstep'] = $upcontext['current_step'];
  636. $upcontext['form_url'] = $upgradeurl . '?step=' . $upcontext['current_step'] . '&amp;substep=' . $_GET['substep'] . '&amp;data=' . base64_encode(serialize($upcontext['upgrade_status']));
  637. // Custom stuff to pass back?
  638. if (!empty($upcontext['query_string']))
  639. $upcontext['form_url'] .= $upcontext['query_string'];
  640. call_user_func('template_' . $upcontext['sub_template']);
  641. }
  642. // Was there an error?
  643. if (!empty($upcontext['forced_error_message']))
  644. echo $upcontext['forced_error_message'];
  645. // Show the footer.
  646. if (!isset($_GET['xml']))
  647. template_upgrade_below();
  648. else
  649. template_xml_below();
  650. }
  651. // Bang - gone!
  652. die();
  653. }
  654. // Used to direct the user to another location.
  655. function redirectLocation($location, $addForm = true)
  656. {
  657. global $upgradeurl, $upcontext, $command_line;
  658. // Command line users can't be redirected.
  659. if ($command_line)
  660. upgradeExit(true);
  661. // Are we providing the core info?
  662. if ($addForm)
  663. {
  664. $upcontext['upgrade_status']['curstep'] = $upcontext['current_step'];
  665. $location = $upgradeurl . '?step=' . $upcontext['current_step'] . '&substep=' . $_GET['substep'] . '&data=' . base64_encode(serialize($upcontext['upgrade_status'])) . $location;
  666. }
  667. while (@ob_end_clean());
  668. header('Location: ' . strtr($location, array('&amp;' => '&')));
  669. // Exit - saving status as we go.
  670. upgradeExit(true);
  671. }
  672. // Load all essential data and connect to the DB as this is pre SSI.php
  673. function loadEssentialData()
  674. {
  675. global $db_server, $db_user, $db_passwd, $db_name, $db_connection, $db_prefix, $db_character_set, $db_type;
  676. global $modSettings, $sourcedir, $smcFunc, $upcontext;
  677. // Do the non-SSI stuff...
  678. @set_magic_quotes_runtime(0);
  679. error_reporting(E_ALL);
  680. define('SMF', 1);
  681. // Start the session.
  682. if (@ini_get('session.save_handler') == 'user')
  683. @ini_set('session.save_handler', 'files');
  684. @session_start();
  685. if (empty($smcFunc))
  686. $smcFunc = array();
  687. // Check we don't need some compatibility.
  688. if (@version_compare(PHP_VERSION, '5.1', '<='))
  689. require_once($sourcedir . '/Subs-Compat.php');
  690. // Initialize everything...
  691. initialize_inputs();
  692. // Get the database going!
  693. if (empty($db_type))
  694. $db_type = 'mysql';
  695. if (file_exists($sourcedir . '/Subs-Db-' . $db_type . '.php'))
  696. {
  697. require_once($sourcedir . '/Subs-Db-' . $db_type . '.php');
  698. // Make the connection...
  699. $db_connection = smf_db_initiate($db_server, $db_name, $db_user, $db_passwd, $db_prefix, array('non_fatal' => true));
  700. // Oh dear god!!
  701. if ($db_connection === null)
  702. die('Unable to connect to database - please check username and password are correct in Settings.php');
  703. if (($db_type == 'mysql' || $db_type == 'mysqli') && isset($db_character_set) && preg_match('~^\w+$~', $db_character_set) === 1)
  704. $smcFunc['db_query']('', '
  705. SET NAMES ' . $db_character_set,
  706. array(
  707. 'db_error_skip' => true,
  708. )
  709. );
  710. // Load the modSettings data...
  711. $request = $smcFunc['db_query']('', '
  712. SELECT variable, value
  713. FROM {db_prefix}settings',
  714. array(
  715. 'db_error_skip' => true,
  716. )
  717. );
  718. $modSettings = array();
  719. while ($row = $smcFunc['db_fetch_assoc']($request))
  720. $modSettings[$row['variable']] = $row['value'];
  721. $smcFunc['db_free_result']($request);
  722. }
  723. else
  724. {
  725. return throw_error('Cannot find ' . $sourcedir . '/Subs-Db-' . $db_type . '.php' . '. Please check you have uploaded all source files and have the correct paths set.');
  726. }
  727. // If they don't have the file, they're going to get a warning anyway so we won't need to clean request vars.
  728. if (file_exists($sourcedir . '/QueryString.php'))
  729. {
  730. require_once($sourcedir . '/QueryString.php');
  731. cleanRequest();
  732. }
  733. if (!isset($_GET['substep']))
  734. $_GET['substep'] = 0;
  735. }
  736. function initialize_inputs()
  737. {
  738. global $sourcedir, $start_time, $upcontext, $db_type;
  739. $start_time = time();
  740. umask(0);
  741. // Fun. Low PHP version...
  742. if (!isset($_GET))
  743. {
  744. $GLOBALS['_GET']['step'] = 0;
  745. return;
  746. }
  747. ob_start();
  748. // Better to upgrade cleanly and fall apart than to screw everything up if things take too long.
  749. ignore_user_abort(true);
  750. // This is really quite simple; if ?delete is on the URL, delete the upgrader...
  751. if (isset($_GET['delete']))
  752. {
  753. @unlink(__FILE__);
  754. $type = ($db_type == 'mysqli') ? 'mysql' : $db_type;
  755. // And the extra little files ;).
  756. @unlink(dirname(__FILE__) . '/upgrade_1-0.sql');
  757. @unlink(dirname(__FILE__) . '/upgrade_1-1.sql');
  758. @unlink(dirname(__FILE__) . '/upgrade_2-0_' . $type . '.sql');
  759. @unlink(dirname(__FILE__) . '/upgrade_2-1_' . $type . '.sql');
  760. @unlink(dirname(__FILE__) . '/webinstall.php');
  761. $dh = opendir(dirname(__FILE__));
  762. while ($file = readdir($dh))
  763. {
  764. if (preg_match('~upgrade_\d-\d_([A-Za-z])+\.sql~i', $file, $matches) && isset($matches[1]))
  765. @unlink(dirname(__FILE__) . '/' . $file);
  766. }
  767. closedir($dh);
  768. header('Location: http://' . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : $_SERVER['SERVER_NAME'] . ':' . $_SERVER['SERVER_PORT']) . dirname($_SERVER['PHP_SELF']) . '/Themes/default/images/blank.png');
  769. exit;
  770. }
  771. // Are we calling the backup css file?
  772. if (isset($_GET['infile_css']))
  773. {
  774. header('Content-Type: text/css');
  775. template_css();
  776. exit;
  777. }
  778. // Anybody home?
  779. if (!isset($_GET['xml']))
  780. {
  781. $upcontext['remote_files_available'] = false;
  782. $test = @fsockopen('www.simplemachines.org', 80, $errno, $errstr, 1);
  783. if ($test)
  784. $upcontext['remote_files_available'] = true;
  785. @fclose($test);
  786. }
  787. // Something is causing this to happen, and it's annoying. Stop it.
  788. $temp = 'upgrade_php?step';
  789. while (strlen($temp) > 4)
  790. {
  791. if (isset($_GET[$temp]))
  792. unset($_GET[$temp]);
  793. $temp = substr($temp, 1);
  794. }
  795. // Force a step, defaulting to 0.
  796. $_GET['step'] = (int) @$_GET['step'];
  797. $_GET['substep'] = (int) @$_GET['substep'];
  798. }
  799. // Step 0 - Let's welcome them in and ask them to login!
  800. function WelcomeLogin()
  801. {
  802. global $boarddir, $sourcedir, $db_prefix, $language, $modSettings, $cachedir, $upgradeurl, $upcontext, $disable_security;
  803. global $smcFunc, $db_type, $databases, $txt;
  804. $upcontext['sub_template'] = 'welcome_message';
  805. $type = ($db_type == 'mysqli') ? 'mysql' : $db_type;
  806. // Check for some key files - one template, one language, and a new and an old source file.
  807. $check = @file_exists($modSettings['theme_dir'] . '/index.template.php')
  808. && @file_exists($sourcedir . '/QueryString.php')
  809. && @file_exists($sourcedir . '/Subs-Db-' . $db_type . '.php')
  810. && @file_exists(dirname(__FILE__) . '/upgrade_2-1_' . $type . '.sql');
  811. // Need legacy scripts?
  812. if (!isset($modSettings['smfVersion']) || $modSettings['smfVersion'] < 2.1)
  813. $check &= @file_exists(dirname(__FILE__) . '/upgrade_2-0_' . $type . '.sql');
  814. if (!isset($modSettings['smfVersion']) || $modSettings['smfVersion'] < 2.0)
  815. $check &= @file_exists(dirname(__FILE__) . '/upgrade_1-1.sql');
  816. if (!isset($modSettings['smfVersion']) || $modSettings['smfVersion'] < 1.1)
  817. $check &= @file_exists(dirname(__FILE__) . '/upgrade_1-0.sql');
  818. if (!$check)
  819. // Don't tell them what files exactly because it's a spot check - just like teachers don't tell which problems they are spot checking, that's dumb.
  820. return throw_error('The upgrader was unable to find some crucial files.<br /><br />Please make sure you uploaded all of the files included in the package, including the Themes, Sources, and other directories.');
  821. // Do they meet the install requirements?
  822. if (!php_version_check())
  823. return throw_error('Warning! You do not appear to have a version of PHP installed on your webserver that meets SMF\'s minimum installations requirements.<br /><br />Please ask your host to upgrade.');
  824. if (!db_version_check())
  825. return throw_error('Your ' . $databases[$db_type]['name'] . ' version does not meet the minimum requirements of SMF.<br /><br />Please ask your host to upgrade.');
  826. // Do they have ALTER privileges?
  827. if (!empty($databases[$db_type]['alter_support']) && $smcFunc['db_query']('alter_boards', 'ALTER TABLE {db_prefix}boards ORDER BY id_board', array()) === false)
  828. return throw_error('The ' . $databases[$db_type]['name'] . ' user you have set in Settings.php does not have proper privileges.<br /><br />Please ask your host to give this user the ALTER, CREATE, and DROP privileges.');
  829. // Do a quick version spot check.
  830. $temp = substr(@implode('', @file($boarddir . '/index.php')), 0, 4096);
  831. preg_match('~\*\s@version\s+(.+)[\s]{2}~i', $temp, $match);
  832. if (empty($match[1]) || $match[1] != SMF_VERSION)
  833. return throw_error('The upgrader found some old or outdated files.<br /><br />Please make certain you uploaded the new versions of all the files included in the package.');
  834. // What absolutely needs to be writable?
  835. $writable_files = array(
  836. $boarddir . '/Settings.php',
  837. $boarddir . '/Settings_bak.php',
  838. );
  839. require_once($sourcedir . '/Security.php');
  840. // Check the cache directory.
  841. $cachedir_temp = empty($cachedir) ? $boarddir . '/cache' : $cachedir;
  842. if (!file_exists($cachedir_temp))
  843. @mkdir($cachedir_temp);
  844. if (!file_exists($cachedir_temp))
  845. return throw_error('The cache directory could not be found.<br /><br />Please make sure you have a directory called &quot;cache&quot; in your forum directory before continuing.');
  846. if (!file_exists($modSettings['theme_dir'] . '/languages/index.' . $upcontext['language'] . '.php') && !isset($modSettings['smfVersion']) && !isset($_GET['lang']))
  847. return throw_error('The upgrader was unable to find language files for the language specified in Settings.php.<br />SMF will not work without the primary language files installed.<br /><br />Please either install them, or <a href="' . $upgradeurl . '?step=0;lang=english">use english instead</a>.');
  848. elseif (!isset($_GET['skiplang']))
  849. {
  850. $temp = substr(@implode('', @file($modSettings['theme_dir'] . '/languages/index.' . $upcontext['language'] . '.php')), 0, 4096);
  851. preg_match('~(?://|/\*)\s*Version:\s+(.+?);\s*index(?:[\s]{2}|\*/)~i', $temp, $match);
  852. if (empty($match[1]) || $match[1] != SMF_LANG_VERSION)
  853. return throw_error('The upgrader found some old or outdated language files, for the forum default language, ' . $upcontext['language'] . '.<br /><br />Please make certain you uploaded the new versions of all the files included in the package, even the theme and language files for the default theme.<br />&nbsp;&nbsp;&nbsp;[<a href="' . $upgradeurl . '?skiplang">SKIP</a>] [<a href="' . $upgradeurl . '?lang=english">Try English</a>]');
  854. }
  855. // This needs to exist!
  856. if (!file_exists($modSettings['theme_dir'] . '/languages/Install.' . $upcontext['language'] . '.php'))
  857. return throw_error('The upgrader could not find the &quot;Install&quot; language file for the forum default language, ' . $upcontext['language'] . '.<br /><br />Please make certain you uploaded all the files included in the package, even the theme and language files for the default theme.<br />&nbsp;&nbsp;&nbsp;[<a href="' . $upgradeurl . '?lang=english">Try English</a>]');
  858. else
  859. require_once($modSettings['theme_dir'] . '/languages/Install.' . $upcontext['language'] . '.php');
  860. if (!makeFilesWritable($writable_files))
  861. return false;
  862. // Check agreement.txt. (it may not exist, in which case $boarddir must be writable.)
  863. if (isset($modSettings['agreement']) && (!is_writable($boarddir) || file_exists($boarddir . '/agreement.txt')) && !is_writable($boarddir . '/agreement.txt'))
  864. return throw_error('The upgrader was unable to obtain write access to agreement.txt.<br /><br />If you are using a linux or unix based server, please ensure that the file is chmod\'d to 777, or if it does not exist that the directory this upgrader is in is 777.<br />If your server is running Windows, please ensure that the internet guest account has the proper permissions on it or its folder.');
  865. // Upgrade the agreement.
  866. elseif (isset($modSettings['agreement']))
  867. {
  868. $fp = fopen($boarddir . '/agreement.txt', 'w');
  869. fwrite($fp, $modSettings['agreement']);
  870. fclose($fp);
  871. }
  872. // We're going to check that their board dir setting is right incase they've been moving stuff around.
  873. if (strtr($boarddir, array('/' => '', '\\' => '')) != strtr(dirname(__FILE__), array('/' => '', '\\' => '')))
  874. $upcontext['warning'] = '
  875. It looks as if your board directory settings <em>might</em> be incorrect. Your board directory is currently set to &quot;' . $boarddir . '&quot; but should probably be &quot;' . dirname(__FILE__) . '&quot;. Settings.php currently lists your paths as:<br />
  876. <ul>
  877. <li>Board Directory: ' . $boarddir . '</li>
  878. <li>Source Directory: ' . $boarddir . '</li>
  879. <li>Cache Directory: ' . $cachedir_temp . '</li>
  880. </ul>
  881. If these seem incorrect please open Settings.php in a text editor before proceeding with this upgrade. If they are incorrect due to you moving your forum to a new location please download and execute the <a href="http://download.simplemachines.org/?tools">Repair Settings</a> tool from the Simple Machines website before continuing.';
  882. // Either we're logged in or we're going to present the login.
  883. if (checkLogin())
  884. return true;
  885. $upcontext += createToken('login');
  886. return false;
  887. }
  888. // Step 0.5: Does the login work?
  889. function checkLogin()
  890. {
  891. global $boarddir, $sourcedir, $db_prefix, $language, $modSettings, $cachedir, $upgradeurl, $upcontext, $disable_security;
  892. global $smcFunc, $db_type, $databases, $support_js, $txt;
  893. // Are we trying to login?
  894. if (isset($_POST['contbutt']) && (!empty($_POST['user']) || $disable_security))
  895. {
  896. // If we've disabled security pick a suitable name!
  897. if (empty($_POST['user']))
  898. $_POST['user'] = 'Administrator';
  899. // Before 2.0 these column names were different!
  900. $oldDB = false;
  901. if (empty($db_type) || $db_type == 'mysql' || $db_type == 'mysqli')
  902. {
  903. $request = $smcFunc['db_query']('', '
  904. SHOW COLUMNS
  905. FROM {db_prefix}members
  906. LIKE {string:member_name}',
  907. array(
  908. 'member_name' => 'memberName',
  909. 'db_error_skip' => true,
  910. )
  911. );
  912. if ($smcFunc['db_num_rows']($request) != 0)
  913. $oldDB = true;
  914. $smcFunc['db_free_result']($request);
  915. }
  916. // Get what we believe to be their details.
  917. if (!$disable_security)
  918. {
  919. if ($oldDB)
  920. $request = $smcFunc['db_query']('', '
  921. SELECT id_member, memberName AS member_name, passwd, id_group,
  922. additionalGroups AS additional_groups, lngfile
  923. FROM {db_prefix}members
  924. WHERE memberName = {string:member_name}',
  925. array(
  926. 'member_name' => $_POST['user'],
  927. 'db_error_skip' => true,
  928. )
  929. );
  930. else
  931. $request = $smcFunc['db_query']('', '
  932. SELECT id_member, member_name, passwd, id_group, additional_groups, lngfile
  933. FROM {db_prefix}members
  934. WHERE member_name = {string:member_name}',
  935. array(
  936. 'member_name' => $_POST['user'],
  937. 'db_error_skip' => true,
  938. )
  939. );
  940. if ($smcFunc['db_num_rows']($request) != 0)
  941. {
  942. list ($id_member, $name, $password, $id_group, $addGroups, $user_language) = $smcFunc['db_fetch_row']($request);
  943. $groups = explode(',', $addGroups);
  944. $groups[] = $id_group;
  945. foreach ($groups as $k => $v)
  946. $groups[$k] = (int) $v;
  947. // Figure out the password using SMF's encryption - if what they typed is right.
  948. if (isset($_REQUEST['hash_passwrd']) && strlen($_REQUEST['hash_passwrd']) == 40)
  949. {
  950. // This is needed for validateToken, but isn't always included for some reason...
  951. include_once($sourcedir . '/Security.php');
  952. // Challenge passed.
  953. $tk = validateToken('login');
  954. if ($_REQUEST['hash_passwrd'] == sha1($password . $upcontext['rid'] . $tk))
  955. $sha_passwd = $password;
  956. }
  957. else
  958. $sha_passwd = sha1(strtolower($name) . un_htmlspecialchars($_REQUEST['passwrd']));
  959. }
  960. else
  961. $upcontext['username_incorrect'] = true;
  962. $smcFunc['db_free_result']($request);
  963. }
  964. $upcontext['username'] = $_POST['user'];
  965. // Track whether javascript works!
  966. if (!empty($_POST['js_works']))
  967. {
  968. $upcontext['upgrade_status']['js'] = 1;
  969. $support_js = 1;
  970. }
  971. else
  972. $support_js = 0;
  973. // Note down the version we are coming from.
  974. if (!empty($modSettings['smfVersion']) && empty($upcontext['user']['version']))
  975. $upcontext['user']['version'] = $modSettings['smfVersion'];
  976. // Didn't get anywhere?
  977. if ((empty($sha_passwd) || $password != $sha_passwd) && empty($upcontext['username_incorrect']) && !$disable_security)
  978. {
  979. // MD5?
  980. $md5pass = md5_hmac($_REQUEST['passwrd'], strtolower($_POST['user']));
  981. if ($md5pass != $password)
  982. {
  983. $upcontext['password_failed'] = true;
  984. // Disable the hashing this time.
  985. $upcontext['disable_login_hashing'] = true;
  986. }
  987. }
  988. if ((empty($upcontext['password_failed']) && !empty($name)) || $disable_security)
  989. {
  990. // Set the password.
  991. if (!$disable_security)
  992. {
  993. // Do we actually have permission?
  994. if (!in_array(1, $groups))
  995. {
  996. $request = $smcFunc['db_query']('', '
  997. SELECT permission
  998. FROM {db_prefix}permissions
  999. WHERE id_group IN ({array_int:groups})
  1000. AND permission = {string:admin_forum}',
  1001. array(
  1002. 'groups' => $groups,
  1003. 'admin_forum' => 'admin_forum',
  1004. 'db_error_skip' => true,
  1005. )
  1006. );
  1007. if ($smcFunc['db_num_rows']($request) == 0)
  1008. return throw_error('You need to be an admin to perform an upgrade!');
  1009. $smcFunc['db_free_result']($request);
  1010. }
  1011. $upcontext['user']['id'] = $id_member;
  1012. $upcontext['user']['name'] = $name;
  1013. }
  1014. else
  1015. {
  1016. $upcontext['user']['id'] = 1;
  1017. $upcontext['user']['name'] = 'Administrator';
  1018. }
  1019. $upcontext['user']['pass'] = mt_rand(0,60000);
  1020. // This basically is used to match the GET variables to Settings.php.
  1021. $upcontext['upgrade_status']['pass'] = $upcontext['user']['pass'];
  1022. // Set the language to that of the user?
  1023. if (isset($user_language) && $user_language != $upcontext['language'] && file_exists($modSettings['theme_dir'] . '/languages/index.' . basename($user_language, '.lng') . '.php'))
  1024. {
  1025. $user_language = basename($user_language, '.lng');
  1026. $temp = substr(@implode('', @file($modSettings['theme_dir'] . '/languages/index.' . $user_language . '.php')), 0, 4096);
  1027. preg_match('~(?://|/\*)\s*Version:\s+(.+?);\s*index(?:[\s]{2}|\*/)~i', $temp, $match);
  1028. if (empty($match[1]) || $match[1] != SMF_LANG_VERSION)
  1029. $upcontext['upgrade_options_warning'] = 'The language files for your selected language, ' . $user_language . ', have not been updated to the latest version. Upgrade will continue with the forum default, ' . $upcontext['language'] . '.';
  1030. elseif (!file_exists($modSettings['theme_dir'] . '/languages/Install.' . basename($user_language, '.lng') . '.php'))
  1031. $upcontext['upgrade_options_warning'] = 'The language files for your selected language, ' . $user_language . ', have not been uploaded/updated as the &quot;Install&quot; language file is missing. Upgrade will continue with the forum default, ' . $upcontext['language'] . '.';
  1032. else
  1033. {
  1034. // Set this as the new language.
  1035. $upcontext['language'] = $user_language;
  1036. $upcontext['upgrade_status']['lang'] = $upcontext['language'];
  1037. // Include the file.
  1038. require_once($modSettings['theme_dir'] . '/languages/Install.' . $user_language . '.php');
  1039. }
  1040. }
  1041. // If we're resuming set the step and substep to be correct.
  1042. if (isset($_POST['cont']))
  1043. {
  1044. $upcontext['current_step'] = $upcontext['user']['step'];
  1045. $_GET['substep'] = $upcontext['user']['substep'];
  1046. }
  1047. return true;
  1048. }
  1049. }
  1050. return false;
  1051. }
  1052. // Step 1: Do the maintenance and backup.
  1053. function UpgradeOptions()
  1054. {
  1055. global $db_prefix, $command_line, $modSettings, $is_debug, $smcFunc, $packagesdir;
  1056. global $boarddir, $boardurl, $sourcedir, $maintenance, $mmessage, $cachedir, $upcontext, $db_type;
  1057. $upcontext['sub_template'] = 'upgrade_options';
  1058. $upcontext['page_title'] = 'Upgrade Options';
  1059. // If we've not submitted then we're done.
  1060. if (empty($_POST['upcont']))
  1061. return false;
  1062. // Firstly, if they're enabling SM stat collection just do it.
  1063. if (!empty($_POST['stats']) && substr($boardurl, 0, 16) != 'http://localhost' && empty($modSettings['allow_sm_stats']))
  1064. {
  1065. // Attempt to register the site etc.
  1066. $fp = @fsockopen('www.simplemachines.org', 80, $errno, $errstr);
  1067. if ($fp)
  1068. {
  1069. $out = 'GET /smf/stats/register_stats.php?site=' . base64_encode($boardurl) . ' HTTP/1.1' . "\r\n";
  1070. $out .= 'Host: www.simplemachines.org' . "\r\n";
  1071. $out .= 'Connection: Close' . "\r\n\r\n";
  1072. fwrite($fp, $out);
  1073. $return_data = '';
  1074. while (!feof($fp))
  1075. $return_data .= fgets($fp, 128);
  1076. fclose($fp);
  1077. // Get the unique site ID.
  1078. preg_match('~SITE-ID:\s(\w{10})~', $return_data, $ID);
  1079. if (!empty($ID[1]))
  1080. $smcFunc['db_insert']('replace',
  1081. $db_prefix . 'settings',
  1082. array('variable' => 'string', 'value' => 'string'),
  1083. array('allow_sm_stats', $ID[1]),
  1084. array('variable')
  1085. );
  1086. }
  1087. }
  1088. else
  1089. $smcFunc['db_query']('', '
  1090. DELETE FROM {db_prefix}settings
  1091. WHERE variable = {string:allow_sm_stats}',
  1092. array(
  1093. 'allow_sm_stats' => 'allow_sm_stats',
  1094. 'db_error_skip' => true,
  1095. )
  1096. );
  1097. // Emptying the error log?
  1098. if (!empty($_POST['empty_error']))
  1099. $smcFunc['db_query']('truncate_table', '
  1100. TRUNCATE {db_prefix}log_errors',
  1101. array(
  1102. )
  1103. );
  1104. $changes = array();
  1105. // If we're overriding the language follow it through.
  1106. if (isset($_GET['lang']) && file_exists($modSettings['theme_dir'] . '/languages/index.' . $_GET['lang'] . '.php'))
  1107. $changes['language'] = '\'' . $_GET['lang'] . '\'';
  1108. if (!empty($_POST['maint']))
  1109. {
  1110. $changes['maintenance'] = '2';
  1111. // Remember what it was...
  1112. $upcontext['user']['main'] = $maintenance;
  1113. if (!empty($_POST['maintitle']))
  1114. {
  1115. $changes['mtitle'] = '\'' . addslashes($_POST['maintitle']) . '\'';
  1116. $changes['mmessage'] = '\'' . addslashes($_POST['mainmessage']) . '\'';
  1117. }
  1118. else
  1119. {
  1120. $changes['mtitle'] = '\'Upgrading the forum...\'';
  1121. $changes['mmessage'] = '\'Don\\\'t worry, we will be back shortly with an updated forum. It will only be a minute ;).\'';
  1122. }
  1123. }
  1124. if ($command_line)
  1125. echo ' * Updating Settings.php...';
  1126. // Backup the current one first.
  1127. copy($boarddir . '/Settings.php', $boarddir . '/Settings_bak.php');
  1128. // Fix some old paths.
  1129. if (substr($boarddir, 0, 1) == '.')
  1130. $changes['boarddir'] = '\'' . fixRelativePath($boarddir) . '\'';
  1131. if (substr($sourcedir, 0, 1) == '.')
  1132. $changes['sourcedir'] = '\'' . fixRelativePath($sourcedir) . '\'';
  1133. if (empty($cachedir) || substr($cachedir, 0, 1) == '.')
  1134. $changes['cachedir'] = '\'' . fixRelativePath($boarddir) . '/cache\'';
  1135. // Not had the database type added before?
  1136. if (empty($db_type))
  1137. $changes['db_type'] = 'mysql';
  1138. // For now we offer a option, this may change in future versions when mysql is completely removed.
  1139. if (!empty($_POST['convertMysql']) && $db_type == 'mysql')
  1140. $changes['db_type'] = '\'mysqli\'';
  1141. // Maybe we haven't had this option yet?
  1142. if (empty($packagesdir))
  1143. $changes['packagesdir'] = '\'' . fixRelativePath($boarddir) . '/Packages\'';
  1144. // @todo Maybe change the cookie name if going to 1.1, too?
  1145. // Update Settings.php with the new settings.
  1146. changeSettings($changes);
  1147. if ($command_line)
  1148. echo ' Successful.' . "\n";
  1149. // Are we doing debug?
  1150. if (isset($_POST['debug']))
  1151. {
  1152. $upcontext['upgrade_status']['debug'] = true;
  1153. $is_debug = true;
  1154. }
  1155. // If we're not backing up then jump one.
  1156. if (empty($_POST['backup']))
  1157. $upcontext['current_step']++;
  1158. // If we've got here then let's proceed to the next step!
  1159. return true;
  1160. }
  1161. // Backup the database - why not...
  1162. function BackupDatabase()
  1163. {
  1164. global $upcontext, $db_prefix, $command_line, $is_debug, $support_js, $file_steps, $smcFunc;
  1165. $upcontext['sub_template'] = isset($_GET['xml']) ? 'backup_xml' : 'backup_database';
  1166. $upcontext['page_title'] = 'Backup Database';
  1167. // Done it already - js wise?
  1168. if (!empty($_POST['backup_done']))
  1169. return true;
  1170. // Some useful stuff here.
  1171. db_extend();
  1172. // Get all the table names.
  1173. $filter = str_replace('_', '\_', preg_match('~^`(.+?)`\.(.+?)$~', $db_prefix, $match) != 0 ? $match[2] : $db_prefix) . '%';
  1174. $db = preg_match('~^`(.+?)`\.(.+?)$~', $db_prefix, $match) != 0 ? strtr($match[1], array('`' => '')) : false;
  1175. $tables = $smcFunc['db_list_tables']($db, $filter);
  1176. $table_names = array();
  1177. foreach ($tables as $table)
  1178. if (substr($table, 0, 7) !== 'backup_')
  1179. $table_names[] = $table;
  1180. $upcontext['table_count'] = count($table_names);
  1181. $upcontext['cur_table_num'] = $_GET['substep'];
  1182. $upcontext['cur_table_name'] = str_replace($db_prefix, '', isset($table_names[$_GET['substep']]) ? $table_names[$_GET['substep']] : $table_names[0]);
  1183. $upcontext['step_progress'] = (int) (($upcontext['cur_table_num'] / $upcontext['table_count']) * 100);
  1184. // For non-java auto submit...
  1185. $file_steps = $upcontext['table_count'];
  1186. // What ones have we already done?
  1187. foreach ($table_names as $id => $table)
  1188. if ($id < $_GET['substep'])
  1189. $upcontext['previous_tables'][] = $table;
  1190. if ($command_line)
  1191. echo 'Backing Up Tables.';
  1192. // If we don't support javascript we backup here.
  1193. if (!$support_js || isset($_GET['xml']))
  1194. {
  1195. // Backup each table!
  1196. for ($substep = $_GET['substep'], $n = count($table_names); $substep < $n; $substep++)
  1197. {
  1198. $upcontext['cur_table_name'] = str_replace($db_prefix, '', (isset($table_names[$substep + 1]) ? $table_names[$substep + 1] : $table_names[$substep]));
  1199. $upcontext['cur_table_num'] = $substep + 1;
  1200. $upcontext['step_progress'] = (int) (($upcontext['cur_table_num'] / $upcontext['table_count']) * 100);
  1201. // Do we need to pause?
  1202. nextSubstep($substep);
  1203. backupTable($table_names[$substep]);
  1204. // If this is XML to keep it nice for the user do one table at a time anyway!
  1205. if (isset($_GET['xml']))
  1206. return upgradeExit();
  1207. }
  1208. if ($is_debug && $command_line)
  1209. {
  1210. echo "\n" . ' Successful.\'' . "\n";
  1211. flush();
  1212. }
  1213. $upcontext['step_progress'] = 100;
  1214. $_GET['substep'] = 0;
  1215. // Make sure we move on!
  1216. return true;
  1217. }
  1218. // Either way next place to post will be database changes!
  1219. $_GET['substep'] = 0;
  1220. return false;
  1221. }
  1222. // Backup one table...
  1223. function backupTable($table)
  1224. {
  1225. global $is_debug, $command_line, $db_prefix, $smcFunc;
  1226. if ($is_debug && $command_line)
  1227. {
  1228. echo "\n" . ' +++ Backing up \"' . str_replace($db_prefix, '', $table) . '"...';
  1229. flush();
  1230. }
  1231. $smcFunc['db_backup_table']($table, 'backup_' . $table);
  1232. if ($is_debug && $command_line)
  1233. echo ' done.';
  1234. }
  1235. // Step 2: Everything.
  1236. function DatabaseChanges()
  1237. {
  1238. global $db_prefix, $modSettings, $command_line, $smcFunc;
  1239. global $language, $boardurl, $sourcedir, $boarddir, $upcontext, $support_js, $db_type;
  1240. // Have we just completed this?
  1241. if (!empty($_POST['database_done']))
  1242. return true;
  1243. $upcontext['sub_template'] = isset($_GET['xml']) ? 'database_xml' : 'database_changes';
  1244. $upcontext['page_title'] = 'Database Changes';
  1245. $type = ($db_type == 'mysqli') ? 'mysql' : $db_type;
  1246. // All possible files.
  1247. // Name, <version, insert_on_complete
  1248. $files = array(
  1249. array('upgrade_1-0.sql', '1.1', '1.1 RC0'),
  1250. array('upgrade_1-1.sql', '2.0', '2.0 a'),
  1251. array('upgrade_2-0_' . $type . '.sql', '2.1', '2.1 dev0'),
  1252. array('upgrade_2-1_' . $type . '.sql', '3.0', SMF_VERSION),
  1253. );
  1254. // How many files are there in total?
  1255. if (isset($_GET['filecount']))
  1256. $upcontext['file_count'] = (int) $_GET['filecount'];
  1257. else
  1258. {
  1259. $upcontext['file_count'] = 0;
  1260. foreach ($files as $file)
  1261. {
  1262. if (!isset($modSettings['smfVersion']) || $modSettings['smfVersion'] < $file[1])
  1263. $upcontext['file_count']++;
  1264. }
  1265. }
  1266. // Do each file!
  1267. $did_not_do = count($files) - $upcontext['file_count'];
  1268. $upcontext['step_progress'] = 0;
  1269. $upcontext['cur_file_num'] = 0;
  1270. foreach ($files as $file)
  1271. {
  1272. if ($did_not_do)
  1273. $did_not_do--;
  1274. else
  1275. {
  1276. $upcontext['cur_file_num']++;
  1277. $upcontext['cur_file_name'] = $file[0];
  1278. // Do we actually need to do this still?
  1279. if (!isset($modSettings['smfVersion']) || $modSettings['smfVersion'] < $file[1])
  1280. {
  1281. $nextFile = parse_sql(dirname(__FILE__) . '/' . $file[0]);
  1282. if ($nextFile)
  1283. {
  1284. // Only update the version of this if complete.
  1285. $smcFunc['db_insert']('replace',
  1286. $db_prefix . 'settings',
  1287. array('variable' => 'string', 'value' => 'string'),
  1288. array('smfVersion', $file[2]),
  1289. array('variable')
  1290. );
  1291. $modSettings['smfVersion'] = $file[2];
  1292. }
  1293. // If this is XML we only do this stuff once.
  1294. if (isset($_GET['xml']))
  1295. {
  1296. // Flag to move on to the next.
  1297. $upcontext['completed_step'] = true;
  1298. // Did we complete the whole file?
  1299. if ($nextFile)
  1300. $upcontext['current_debug_item_num'] = -1;
  1301. return upgradeExit();
  1302. }
  1303. elseif ($support_js)
  1304. break;
  1305. }
  1306. // Set the progress bar to be right as if we had - even if we hadn't...
  1307. $upcontext['step_progress'] = ($upcontext['cur_file_num'] / $upcontext['file_count']) * 100;
  1308. }
  1309. }
  1310. $_GET['substep'] = 0;
  1311. // So the template knows we're done.
  1312. if (!$support_js)
  1313. {
  1314. $upcontext['changes_complete'] = true;
  1315. // If this is the command line we can't do any more.
  1316. if ($command_line)
  1317. return DeleteUpgrade();
  1318. return true;
  1319. }
  1320. return false;
  1321. }
  1322. // Clean up any mods installed...
  1323. function CleanupMods()
  1324. {
  1325. global $db_prefix, $modSettings, $upcontext, $boarddir, $sourcedir, $packagesdir, $settings, $smcFunc, $command_line;
  1326. // Sorry. Not supported for command line users.
  1327. if ($command_line)
  1328. return true;
  1329. // Skipping first?
  1330. if (!empty($_POST['skip']))
  1331. {
  1332. unset($_POST['skip']);
  1333. return true;
  1334. }
  1335. // If we get here withOUT SSI we need to redirect to ensure we get it!
  1336. if (!isset($_GET['ssi']) || !function_exists('mktree'))
  1337. redirectLocation('&ssi=1');
  1338. $upcontext['sub_template'] = 'clean_mods';
  1339. $upcontext['page_title'] = 'Cleanup Modifications';
  1340. // This can be skipped.
  1341. $upcontext['skip'] = true;
  1342. // If we're on the second redirect continue...
  1343. if (isset($_POST['cleandone2']))
  1344. return true;
  1345. // Do we already know about some writable files?
  1346. if (isset($_POST['writable_files']))
  1347. {
  1348. $writable_files = unserialize(base64_decode($_POST['writable_files']));
  1349. if (!makeFilesWritable($writable_files))
  1350. {
  1351. // What have we left?
  1352. $upcontext['writable_files'] = $writable_files;
  1353. return false;
  1354. }
  1355. }
  1356. // Make sure we have some sort of packages directory.
  1357. if (!isset($packagesdir))
  1358. $packagesdir = $boarddir . '/Packages';
  1359. // Load all theme paths....
  1360. $request = $smcFunc['db_query']('', '
  1361. SELECT id_theme, variable, value
  1362. FROM {db_prefix}themes
  1363. WHERE id_member = {int:id_member}
  1364. AND variable IN ({string:theme_dir}, {string:images_url})',
  1365. array(
  1366. 'id_member' => 0,
  1367. 'theme_dir' => 'theme_dir',
  1368. 'images_url' => 'images_url',
  1369. 'db_error_skip' => true,
  1370. )
  1371. );
  1372. $theme_paths = array();
  1373. while ($row = $smcFunc['db_fetch_assoc']($request))
  1374. {
  1375. if ($row['id_theme'] == 1)
  1376. $settings['default_' . $row['variable']] = $row['value'];
  1377. elseif ($row['variable'] == 'theme_dir')
  1378. $theme_paths[$row['id_theme']][$row['variable']] = $row['value'];
  1379. }
  1380. $smcFunc['db_free_result']($request);
  1381. // Are there are mods installed that may need uninstalling?
  1382. $request = $smcFunc['db_query']('', '
  1383. SELECT id_install, filename, name, themes_installed, version
  1384. FROM {db_prefix}log_packages
  1385. WHERE install_state = {int:installed}
  1386. ORDER BY time_installed DESC',
  1387. array(
  1388. 'installed' => 1,
  1389. 'db_error_skip' => true,
  1390. )
  1391. );
  1392. $upcontext['packages'] = array();
  1393. while ($row = $smcFunc['db_fetch_assoc']($request))
  1394. {
  1395. // Work out the status.
  1396. if (!file_exists($packagesdir . '/' . $row['filename']))
  1397. {
  1398. $status = 'Missing';
  1399. $status_color = 'red';
  1400. $result = 'Removed';
  1401. }
  1402. else
  1403. {
  1404. $status = 'Installed';
  1405. $status_color = 'green';
  1406. $result = 'No Action Needed';
  1407. }
  1408. $upcontext['packages'][$row['id_install']] = array(
  1409. 'id' => $row['id_install'],
  1410. 'themes' => explode(',', $row['themes_installed']),
  1411. 'name' => $row['name'],
  1412. 'filename' => $row['filename'],
  1413. 'missing_file' => file_exists($packagesdir . '/' . $row['filename']) ? 0 : 1,
  1414. 'files' => array(),
  1415. 'file_count' => 0,
  1416. 'status' => $status,
  1417. 'result' => $result,
  1418. 'color' => $status_color,
  1419. 'version' => $row['version'],
  1420. 'needs_removing' => false,
  1421. );
  1422. }
  1423. $smcFunc['db_free_result']($request);
  1424. // Don't carry on if there are none.
  1425. if (empty($upcontext['packages']))
  1426. return true;
  1427. // Setup some basics.
  1428. if (!empty($upcontext['user']['version']))
  1429. $_SESSION['version_emulate'] = $upcontext['user']['version'];
  1430. // Before we get started, don't report notice errors.
  1431. $oldErrorReporting = error_reporting(E_ALL ^ E_NOTICE);
  1432. if (!mktree($packagesdir . '/temp', 0755))
  1433. {
  1434. deltree($packagesdir . '/temp', false);
  1435. if (!mktree($packagesdir . '/temp', 0777))
  1436. {
  1437. deltree($packagesdir . '/temp', false);
  1438. // @todo Error here - plus chmod!
  1439. }
  1440. }
  1441. // Anything which reinstalled should not have its entry removed.
  1442. $reinstall_worked = array();
  1443. // We're gonna be doing some removin'
  1444. $test = isset($_POST['cleandone']) ? false : true;
  1445. foreach ($upcontext['packages'] as $id => $package)
  1446. {
  1447. // Can't do anything about this....
  1448. if ($package['missing_file'])
  1449. continue;
  1450. // Not testing *and* this wasn't checked?
  1451. if (!$test && (!isset($_POST['remove']) || !isset($_POST['remove'][$id])))
  1452. continue;
  1453. // What are the themes this was installed into?
  1454. $cur_theme_paths = array();
  1455. foreach ($theme_paths as $tid => $data)
  1456. if ($tid != 1 && in_array($tid, $package['themes']))
  1457. $cur_theme_paths[$tid] = $data;
  1458. // Get the modifications data if applicable.
  1459. $filename = $package['filename'];
  1460. $packageInfo = getPackageInfo($filename);
  1461. if (!is_array($packageInfo))
  1462. continue;
  1463. $info = parsePackageInfo($packageInfo['xml'], $test, 'uninstall');
  1464. // Also get the reinstall details...
  1465. if (isset($_POST['remove']))
  1466. $infoInstall = parsePackageInfo($packageInfo['xml'], true);
  1467. if (is_file($packagesdir . '/' . $filename))
  1468. read_tgz_file($packagesdir . '/' . $filename, $packagesdir . '/temp');
  1469. else
  1470. copytree($packagesdir . '/' . $filename, $packagesdir . '/temp');
  1471. // Work out how we uninstall...
  1472. $files = array();
  1473. foreach ($info as $change)
  1474. {
  1475. // Work out two things:
  1476. // 1) Whether it's installed at the moment - and if so whether its fully installed, and:
  1477. // 2) Whether it could be installed on the new version.
  1478. if ($change['type'] == 'modification')
  1479. {
  1480. $contents = @file_get_contents($packagesdir . '/temp/' . $upcontext['base_path'] . $change['filename']);
  1481. if ($change['boardmod'])
  1482. $results = parseBoardMod($contents, $test, $change['reverse'], $cur_theme_paths);
  1483. else
  1484. $results = parseModification($contents, $test, $change['reverse'], $cur_theme_paths);
  1485. foreach ($results as $action)
  1486. {
  1487. // Something we can remove? Probably means it existed!
  1488. if (($action['type'] == 'replace' || $action['type'] == 'append' || (!empty($action['filename']) && $action['type'] == 'failure')) && !in_array($action['filename'], $files))
  1489. $files[] = $action['filename'];
  1490. if ($action['type'] == 'failure')
  1491. {
  1492. $upcontext['packages'][$id]['needs_removing'] = true;
  1493. $upcontext['packages'][$id]['status'] = 'Reinstall Required';
  1494. $upcontext['packages'][$id]['color'] = '#FD6435';
  1495. }
  1496. }
  1497. }
  1498. }
  1499. // Store this info for the template as appropriate.
  1500. $upcontext['packages'][$id]['files'] = $files;
  1501. $upcontext['packages'][$id]['file_count'] = count($files);
  1502. // If we've done something save the changes!
  1503. if (!$test)
  1504. package_flush_cache();
  1505. // Are we attempting to reinstall this thing?
  1506. if (isset($_POST['remove']) && !$test && isset($infoInstall))
  1507. {
  1508. // Need to extract again I'm afraid.
  1509. if (is_file($packagesdir . '/' . $filename))
  1510. read_tgz_file($packagesdir . '/' . $filename, $packagesdir . '/temp');
  1511. else
  1512. copytree($packagesdir . '/' . $filename, $packagesdir . '/temp');
  1513. $errors = false;
  1514. $upcontext['packages'][$id]['result'] = 'Removed';
  1515. foreach ($infoInstall as $change)
  1516. {
  1517. if ($change['type'] == 'modification')
  1518. {
  1519. $contents = @file_get_contents($packagesdir . '/temp/' . $upcontext['base_path'] . $change['filename']);
  1520. if ($change['boardmod'])
  1521. $results = parseBoardMod($contents, true, $change['reverse'], $cur_theme_paths);
  1522. else
  1523. $results = parseModification($contents, true, $change['reverse'], $cur_theme_paths);
  1524. // Are there any errors?
  1525. foreach ($results as $action)
  1526. if ($action['type'] == 'failure')
  1527. $errors = true;
  1528. }
  1529. }
  1530. if (!$errors)
  1531. {
  1532. $reinstall_worked[] = $id;
  1533. $upcontext['packages'][$id]['result'] = 'Reinstalled';
  1534. $upcontext['packages'][$id]['color'] = 'green';
  1535. foreach ($infoInstall as $change)
  1536. {
  1537. if ($change['type'] == 'modification')
  1538. {
  1539. $contents = @file_get_contents($packagesdir . '/temp/' . $upcontext['base_path'] . $change['filename']);
  1540. if ($change['boardmod'])
  1541. $results = parseBoardMod($contents, false, $change['reverse'], $cur_theme_paths);
  1542. else
  1543. $results = parseModification($contents, false, $change['reverse'], $cur_theme_paths);
  1544. }
  1545. }
  1546. // Save the changes.
  1547. package_flush_cache();
  1548. }
  1549. }
  1550. }
  1551. // Put errors back on a sec.
  1552. error_reporting($oldErrorReporting);
  1553. // Check everything is writable.
  1554. if ($test && !empty($upcontext['packages']))
  1555. {
  1556. $writable_files = array();
  1557. foreach ($upcontext['packages'] as $package)
  1558. {
  1559. if (!empty($package['files']))
  1560. foreach ($package['files'] as $file)
  1561. $writable_files[] = $file;
  1562. }
  1563. if (!empty($writable_files))
  1564. {
  1565. $writable_files = array_unique($writable_files);
  1566. $upcontext['writable_files'] = $writable_files;
  1567. if (!makeFilesWritable($writable_files))
  1568. return false;
  1569. }
  1570. }
  1571. if (file_exists($packagesdir . '/temp'))
  1572. deltree($packagesdir . '/temp');
  1573. // Removing/Reinstalling any packages?
  1574. if (isset($_POST['remove']))
  1575. {
  1576. $deletes = array();
  1577. foreach ($_POST['remove'] as $id => $dummy)
  1578. {
  1579. if (!in_array((int) $id, $reinstall_worked))
  1580. $deletes[] = (int) $id;
  1581. }
  1582. if (!empty($deletes))
  1583. upgrade_query( '
  1584. UPDATE ' . $db_prefix . 'log_packages
  1585. SET install_state = 0
  1586. WHERE id_install IN (' . implode(',', $deletes) . ')');
  1587. // Ensure we don't lose our changes!
  1588. package_put_contents($packagesdir . '/installed.list', time());
  1589. $upcontext['sub_template'] = 'cleanup_done';
  1590. return false;
  1591. }
  1592. else
  1593. {
  1594. $allgood = true;
  1595. // Is there actually anything that needs our attention?
  1596. foreach ($upcontext['packages'] as $package)
  1597. if ($package['color'] != 'green')
  1598. $allgood = false;
  1599. if ($allgood)
  1600. return true;
  1601. }
  1602. $_GET['substep'] = 0;
  1603. return isset($_POST['cleandone']) ? true : false;
  1604. }
  1605. // Delete the damn thing!
  1606. function DeleteUpgrade()
  1607. {
  1608. global $command_line, $language, $upcontext, $boarddir, $sourcedir, $forum_version, $user_info, $maintenance, $smcFunc, $db_type;
  1609. // Now it's nice to have some of the basic SMF source files.
  1610. if (!isset($_GET['ssi']) && !$command_line)
  1611. redirectLocation('&ssi=1');
  1612. $upcontext['sub_template'] = 'upgrade_complete';
  1613. $upcontext['page_title'] = 'Upgrade Complete';
  1614. $endl = $command_line ? "\n" : '<br />' . "\n";
  1615. $changes = array(
  1616. 'language' => '\'' . (substr($language, -4) == '.lng' ? substr($language, 0, -4) : $language) . '\'',
  1617. 'db_error_send' => '1',
  1618. 'upgradeData' => '#remove#',
  1619. );
  1620. // Are we in maintenance mode?
  1621. if (isset($upcontext['user']['main']))
  1622. {
  1623. if ($command_line)
  1624. echo ' * ';
  1625. $upcontext['removed_maintenance'] = true;
  1626. $changes['maintenance'] = $upcontext['user']['main'];
  1627. }
  1628. // Otherwise if somehow we are in 2 let's go to 1.
  1629. elseif (!empty($maintenance) && $maintenance == 2)
  1630. $changes['maintenance'] = 1;
  1631. // Wipe this out...
  1632. $upcontext['user'] = array();
  1633. // Make a backup of Settings.php first as otherwise earlier changes are lost.
  1634. copy($boarddir . '/Settings.php', $boarddir . '/Settings_bak.php');
  1635. changeSettings($changes);
  1636. // Clean any old cache files away.
  1637. clean_cache();
  1638. // Can we delete the file?
  1639. $upcontext['can_delete_script'] = is_writable(dirname(__FILE__)) || is_writable(__FILE__);
  1640. // Now is the perfect time to fetch the SM files.
  1641. if ($command_line)
  1642. cli_scheduled_fetchSMfiles();
  1643. else
  1644. {
  1645. require_once($sourcedir . '/ScheduledTasks.php');
  1646. $forum_version = SMF_VERSION; // The variable is usually defined in index.php so lets just use the constant to do it for us.
  1647. scheduled_fetchSMfiles(); // Now go get those files!
  1648. }
  1649. // Log what we've done.
  1650. if (empty($user_info['id']))
  1651. $user_info['id'] = !empty($upcontext['user']['id']) ? $upcontext['user']['id'] : 0;
  1652. // Log the action manually, so CLI still works.
  1653. $smcFunc['db_insert']('',
  1654. '{db_prefix}log_actions',
  1655. array(
  1656. 'log_time' => 'int', 'id_log' => 'int', 'id_member' => 'int', 'ip' => 'string-16', 'action' => 'string',
  1657. 'id_board' => 'int', 'id_topic' => 'int', 'id_msg' => 'int', 'extra' => 'string-65534',
  1658. ),
  1659. array(
  1660. time(), 3, $user_info['id'], $command_line ? '127.0.0.1' : $user_info['ip'], 'upgrade',
  1661. 0, 0, 0, serialize(array('version' => $forum_version, 'member' => $user_info['id'])),
  1662. ),
  1663. array('id_action')
  1664. );
  1665. $user_info['id'] = 0;
  1666. // Save the current database version.
  1667. $server_version = $smcFunc['db_server_info']();
  1668. if (($db_type == 'mysql' || $db_type == 'mysqli') && in_array(substr($server_version, 0, 6), array('5.0.50', '5.0.51')))
  1669. updateSettings(array('db_mysql_group_by_fix' => '1'));
  1670. if ($command_line)
  1671. {
  1672. echo $endl;
  1673. echo 'Upgrade Complete!', $endl;
  1674. echo 'Please delete this file as soon as possible for security reasons.', $endl;
  1675. exit;
  1676. }
  1677. // Make sure it says we're done.
  1678. $upcontext['overall_percent'] = 100;
  1679. if (isset($upcontext['step_progress']))
  1680. unset($upcontext['step_progress']);
  1681. $_GET['substep'] = 0;
  1682. return false;
  1683. }
  1684. // Just like the built in one, but setup for CLI to not use themes.
  1685. function cli_scheduled_fetchSMfiles()
  1686. {
  1687. global $sourcedir, $txt, $language, $settings, $forum_version, $modSettings, $smcFunc;
  1688. if (empty($modSettings['time_format']))
  1689. $modSettings['time_format'] = '%B %d, %Y, %I:%M:%S %p';
  1690. // What files do we want to get
  1691. $request = $smcFunc['db_query']('', '
  1692. SELECT id_file, filename, path, parameters
  1693. FROM {db_prefix}admin_info_files',
  1694. array(
  1695. )
  1696. );
  1697. $js_files = array();
  1698. while ($row = $smcFunc['db_fetch_assoc']($request))
  1699. {
  1700. $js_files[$row['id_file']] = array(
  1701. 'filename' => $row['filename'],
  1702. 'path' => $row['path'],
  1703. 'parameters' => sprintf($row['parameters'], $language, urlencode($modSettings['time_format']), urlencode($forum_version)),
  1704. );
  1705. }
  1706. $smcFunc['db_free_result']($request);
  1707. // We're gonna need fetch_web_data() to pull this off.
  1708. require_once($sourcedir . '/Subs-Package.php');
  1709. foreach ($js_files as $ID_FILE => $file)
  1710. {
  1711. // Create the url
  1712. $server = empty($file['path']) || substr($file['path'], 0, 7) != 'http://' ? 'http://www.simplemachines.org' : '';
  1713. $url = $server . (!empty($file['path']) ? $file['path'] : $file['path']) . $file['filename'] . (!empty($file['parameters']) ? '?' . $file['parameters'] : '');
  1714. // Get the file
  1715. $file_data = fetch_web_data($url);
  1716. // If we got an error - give up - the site might be down.
  1717. if ($file_data === false)
  1718. return throw_error(sprintf('Could not retrieve the file %1$s.', $url));
  1719. // Save the file to the database.
  1720. $smcFunc['db_query']('substring', '
  1721. UPDATE {db_prefix}admin_info_files
  1722. SET data = SUBSTRING({string:file_data}, 1, 65534)
  1723. WHERE id_file = {int:id_file}',
  1724. array(
  1725. 'id_file' => $ID_FILE,
  1726. 'file_data' => $file_data,
  1727. )
  1728. );
  1729. }
  1730. return true;
  1731. }
  1732. function convertSettingsToTheme()
  1733. {
  1734. global $db_prefix, $modSettings, $smcFunc;
  1735. $values = array(
  1736. 'show_latest_member' => @$GLOBALS['showlatestmember'],
  1737. 'show_bbc' => isset($GLOBALS['showyabbcbutt']) ? $GLOBALS['showyabbcbutt'] : @$GLOBALS['showbbcbutt'],
  1738. 'show_modify' => @$GLOBALS['showmodify'],
  1739. 'show_user_images' => @$GLOBALS['showuserpic'],
  1740. 'show_blurb' => @$GLOBALS['showusertext'],
  1741. 'show_gender' => @$GLOBALS['showgenderimage'],
  1742. 'show_newsfader' => @$GLOBALS['shownewsfader'],
  1743. 'display_recent_bar' => @$GLOBALS['Show_RecentBar'],
  1744. 'show_member_bar' => @$GLOBALS['Show_MemberBar'],
  1745. 'linktree_link' => @$GLOBALS['curposlinks'],
  1746. 'show_profile_buttons' => @$GLOBALS['profilebutton'],
  1747. 'show_mark_read' => @$GLOBALS['showmarkread'],
  1748. 'show_board_desc' => @$GLOBALS['ShowBDescrip'],
  1749. 'newsfader_time' => @$GLOBALS['fadertime'],
  1750. 'use_image_buttons' => empty($GLOBALS['MenuType']) ? 1 : 0,
  1751. 'enable_news' => @$GLOBALS['enable_news'],
  1752. 'return_to_post' => @$modSettings['returnToPost'],
  1753. );
  1754. $themeData = array();
  1755. foreach ($values as $variable => $value)
  1756. {
  1757. if (!isset($value) || $value === null)
  1758. $value = 0;
  1759. $themeData[] = array(0, 1, $variable, $value);
  1760. }
  1761. if (!empty($themeData))
  1762. {
  1763. $smcFunc['db_insert']('ignore',
  1764. $db_prefix . 'themes',
  1765. array('id_member' => 'int', 'id_theme' => 'int', 'variable' => 'string', 'value' => 'string'),
  1766. $themeData,
  1767. array('id_member', 'id_theme', 'variable')
  1768. );
  1769. }
  1770. }
  1771. // This function only works with MySQL but that's fine as it is only used for v1.0.
  1772. function convertSettingstoOptions()
  1773. {
  1774. global $db_prefix, $modSettings, $smcFunc;
  1775. // Format: new_setting -> old_setting_name.
  1776. $values = array(
  1777. 'calendar_start_day' => 'cal_startmonday',
  1778. 'view_newest_first' => 'viewNewestFirst',
  1779. 'view_newest_pm_first' => 'viewNewestFirst',
  1780. );
  1781. foreach ($values as $variable => $value)
  1782. {
  1783. if (empty($modSettings[$value[0]]))
  1784. continue;
  1785. $smcFunc['db_query']('', '
  1786. INSERT IGNORE INTO {db_prefix}themes
  1787. (id_member, id_theme, variable, value)
  1788. SELECT id_member, 1, {string:variable}, {string:value}
  1789. FROM {db_prefix}members',
  1790. array(
  1791. 'variable' => $variable,
  1792. 'value' => $modSettings[$value[0]],
  1793. 'db_error_skip' => true,
  1794. )
  1795. );
  1796. $smcFunc['db_query']('', '
  1797. INSERT IGNORE INTO {db_prefix}themes
  1798. (id_member, id_theme, variable, value)
  1799. VALUES (-1, 1, {string:variable}, {string:value})',
  1800. array(
  1801. 'variable' => $variable,
  1802. 'value' => $modSettings[$value[0]],
  1803. 'db_error_skip' => true,
  1804. )
  1805. );
  1806. }
  1807. }
  1808. function changeSettings($config_vars)
  1809. {
  1810. global $boarddir;
  1811. $settingsArray = file($boarddir . '/Settings_bak.php');
  1812. if (count($settingsArray) == 1)
  1813. $settingsArray = preg_split('~[\r\n]~', $settingsArray[0]);
  1814. for ($i = 0, $n = count($settingsArray); $i < $n; $i++)
  1815. {
  1816. // Don't trim or bother with it if it's not a variable.
  1817. if (substr($settingsArray[$i], 0, 1) == '$')
  1818. {
  1819. $settingsArray[$i] = trim($settingsArray[$i]) . "\n";
  1820. foreach ($config_vars as $var => $val)
  1821. {
  1822. if (isset($settingsArray[$i]) && strncasecmp($settingsArray[$i], '$' . $var, 1 + strlen($var)) == 0)
  1823. {
  1824. if ($val == '#remove#')
  1825. unset($settingsArray[$i]);
  1826. else
  1827. {
  1828. $comment = strstr(substr($settingsArray[$i], strpos($settingsArray[$i], ';')), '#');
  1829. $settingsArray[$i] = '$' . $var . ' = ' . $val . ';' . ($comment != '' ? "\t\t" . $comment : "\n");
  1830. }
  1831. unset($config_vars[$var]);
  1832. }
  1833. }
  1834. }
  1835. if (isset($settingsArray[$i]))
  1836. {
  1837. if (trim(substr($settingsArray[$i], 0, 2)) == '?' . '>')
  1838. $end = $i;
  1839. }
  1840. }
  1841. // Assume end-of-file if the end wasn't found.
  1842. if (empty($end) || $end < 10)
  1843. $end = count($settingsArray);
  1844. if (!empty($config_vars))
  1845. {
  1846. $settingsArray[$end++] = '';
  1847. foreach ($config_vars as $var => $val)
  1848. {
  1849. if ($val != '#remove#')
  1850. $settingsArray[$end++] = '$' . $var . ' = ' . $val . ';' . "\n";
  1851. }
  1852. }
  1853. // This should be the last line and even last bytes of the file.
  1854. $settingsArray[$end] = '?' . '>';
  1855. // Blank out the file - done to fix a oddity with some servers.
  1856. $fp = fopen($boarddir . '/Settings.php', 'w');
  1857. fclose($fp);
  1858. $fp = fopen($boarddir . '/Settings.php', 'r+');
  1859. for ($i = 0; $i < $end; $i++)
  1860. {
  1861. if (isset($settingsArray[$i]))
  1862. fwrite($fp, strtr($settingsArray[$i], "\r", ''));
  1863. }
  1864. fwrite($fp, rtrim($settingsArray[$i]));
  1865. fclose($fp);
  1866. }
  1867. function updateLastError()
  1868. {
  1869. // clear out the db_last_error file
  1870. file_put_contents(dirname(__FILE__) . '/db_last_error.php', '<' . '?' . "php\n" . '$db_last_error = 0;' . "\n" . '?' . '>');
  1871. }
  1872. function php_version_check()
  1873. {
  1874. $minver = explode('.', $GLOBALS['required_php_version']);
  1875. $curver = explode('.', PHP_VERSION);
  1876. return !(($curver[0] <= $minver[0]) && ($curver[1] <= $minver[1]) && ($curver[1] <= $minver[1]) && ($curver[2][0] < $minver[2][0]));
  1877. }
  1878. function db_version_check()
  1879. {
  1880. global $db_type, $databases;
  1881. $curver = eval($databases[$db_type]['version_check']);
  1882. $curver = preg_replace('~\-.+?$~', '', $curver);
  1883. return version_compare($databases[$db_type]['version'], $curver, '<=');
  1884. }
  1885. function getMemberGroups()
  1886. {
  1887. global $db_prefix, $smcFunc;
  1888. static $member_groups = array();
  1889. if (!empty($member_groups))
  1890. return $member_groups;
  1891. $request = $smcFunc['db_query']('', '
  1892. SELECT group_name, id_group
  1893. FROM {db_prefix}membergroups
  1894. WHERE id_group = {int:admin_group} OR id_group > {int:old_group}',
  1895. array(
  1896. 'admin_group' => 1,
  1897. 'old_group' => 7,
  1898. 'db_error_skip' => true,
  1899. )
  1900. );
  1901. if ($request === false)
  1902. {
  1903. $request = $smcFunc['db_query']('', '
  1904. SELECT membergroup, id_group
  1905. FROM {db_prefix}membergroups
  1906. WHERE id_group = {int:admin_group} OR id_group > {int:old_group}',
  1907. array(
  1908. 'admin_group' => 1,
  1909. 'old_group' => 7,
  1910. 'db_error_skip' => true,
  1911. )
  1912. );
  1913. }
  1914. while ($row = $smcFunc['db_fetch_row']($request))
  1915. $member_groups[trim($row[0])] = $row[1];
  1916. $smcFunc['db_free_result']($request);
  1917. return $member_groups;
  1918. }
  1919. function fixRelativePath($path)
  1920. {
  1921. global $install_path;
  1922. // Fix the . at the start, clear any duplicate slashes, and fix any trailing slash...
  1923. return addslashes(preg_replace(array('~^\.([/\\\]|$)~', '~[/]+~', '~[\\\]+~', '~[/\\\]$~'), array($install_path . '$1', '/', '\\', ''), $path));
  1924. }
  1925. function parse_sql($filename)
  1926. {
  1927. global $db_prefix, $db_collation, $boarddir, $boardurl, $command_line, $file_steps, $step_progress, $custom_warning;
  1928. global $upcontext, $support_js, $is_debug, $smcFunc, $db_connection, $databases, $db_type, $db_character_set;
  1929. /*
  1930. Failure allowed on:
  1931. - INSERT INTO but not INSERT IGNORE INTO.
  1932. - UPDATE IGNORE but not UPDATE.
  1933. - ALTER TABLE and ALTER IGNORE TABLE.
  1934. - DROP TABLE.
  1935. Yes, I realize that this is a bit confusing... maybe it should be done differently?
  1936. If a comment...
  1937. - begins with --- it is to be output, with a break only in debug mode. (and say successful\n\n if there was one before.)
  1938. - begins with ---# it is a debugging statement, no break - only shown at all in debug.
  1939. - is only ---#, it is "done." and then a break - only shown in debug.
  1940. - begins with ---{ it is a code block terminating at ---}.
  1941. Every block of between "--- ..."s is a step. Every "---#" section represents a substep.
  1942. Replaces the following variables:
  1943. - {$boarddir}
  1944. - {$boardurl}
  1945. - {$db_prefix}
  1946. - {$db_collation}
  1947. */
  1948. // May want to use extended functionality.
  1949. db_extend();
  1950. db_extend('packages');
  1951. // Our custom error handler - does nothing but does stop public errors from XML!
  1952. if (!function_exists('sql_error_handler'))
  1953. {
  1954. function sql_error_handler($errno, $errstr, $errfile, $errline)
  1955. {
  1956. global $support_js;
  1957. if ($support_js)
  1958. return true;
  1959. else
  1960. echo 'Error: ' . $errstr . ' File: ' . $errfile . ' Line: ' . $errline;
  1961. }
  1962. }
  1963. // Make our own error handler.
  1964. set_error_handler('sql_error_handler');
  1965. // If we're on MySQL supporting collations then let's find out what the members table uses and put it in a global var - to allow upgrade script to match collations!
  1966. if (!empty($databases[$db_type]['utf8_support']) && version_compare($databases[$db_type]['utf8_version'], eval($databases[$db_type]['utf8_version_check']), '>'))
  1967. {
  1968. $request = $smcFunc['db_query']('', '
  1969. SHOW TABLE STATUS
  1970. LIKE {string:table_name}',
  1971. array(
  1972. 'table_name' => "{$db_prefix}members",
  1973. 'db_error_skip' => true,
  1974. )
  1975. );
  1976. if ($smcFunc['db_num_rows']($request) === 0)
  1977. die('Unable to find members table!');
  1978. $table_status = $smcFunc['db_fetch_assoc']($request);
  1979. $smcFunc['db_free_result']($request);
  1980. if (!empty($table_status['Collation']))
  1981. {
  1982. $request = $smcFunc['db_query']('', '
  1983. SHOW COLLATION
  1984. LIKE {string:collation}',
  1985. array(
  1986. 'collation' => $table_status['Collation'],
  1987. 'db_error_skip' => true,
  1988. )
  1989. );
  1990. // Got something?
  1991. if ($smcFunc['db_num_rows']($request) !== 0)
  1992. $collation_info = $smcFunc['db_fetch_assoc']($request);
  1993. $smcFunc['db_free_result']($request);
  1994. // Excellent!
  1995. if (!empty($collation_info['Collation']) && !empty($collation_info['Charset']))
  1996. $db_collation = ' CHARACTER SET ' . $collation_info['Charset'] . ' COLLATE ' . $collation_info['Collation'];
  1997. }
  1998. }
  1999. if (empty($db_collation))
  2000. $db_collation = '';
  2001. $endl = $command_line ? "\n" : '<br />' . "\n";
  2002. $lines = file($filename);
  2003. $current_type = 'sql';
  2004. $current_data = '';
  2005. $substep = 0;
  2006. $last_step = '';
  2007. // Make sure all newly created tables will have the proper characters set.
  2008. if (isset($db_character_set) && $db_character_set === 'utf8')
  2009. $lines = str_replace(') ENGINE=MyISAM;', ') ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;', $lines);
  2010. // Count the total number of steps within this file - for progress.
  2011. $file_steps = substr_count(implode('', $lines), '---#');
  2012. $upcontext['total_items'] = substr_count(implode('', $lines), '--- ');
  2013. $upcontext['debug_items'] = $file_steps;
  2014. $upcontext['current_item_num'] = 0;
  2015. $upcontext['current_item_name'] = '';
  2016. $upcontext['current_debug_item_num'] = 0;
  2017. $upcontext['current_debug_item_name'] = '';
  2018. // This array keeps a record of what we've done in case java is dead...
  2019. $upcontext['actioned_items'] = array();
  2020. $done_something = false;
  2021. foreach ($lines as $line_number => $line)
  2022. {
  2023. $do_current = $substep >= $_GET['substep'];
  2024. // Get rid of any comments in the beginning of the line...
  2025. if (substr(trim($line), 0, 2) === '/*')
  2026. $line = preg_replace('~/\*.+?\*/~', '', $line);
  2027. // Always flush. Flush, flush, flush. Flush, flush, flush, flush! FLUSH!
  2028. if ($is_debug && !$support_js && $command_line)
  2029. flush();
  2030. if (trim($line) === '')
  2031. continue;
  2032. if (trim(substr($line, 0, 3)) === '---')
  2033. {
  2034. $type = substr($line, 3, 1);
  2035. // An error??
  2036. if (trim($current_data) != '' && $type !== '}')
  2037. {
  2038. $upcontext['error_message'] = 'Error in upgrade script - line ' . $line_number . '!' . $endl;
  2039. if ($command_line)
  2040. echo $upcontext['error_message'];
  2041. }
  2042. if ($type == ' ')
  2043. {
  2044. if (!$support_js && $do_current && $_GET['substep'] != 0 && $command_line)
  2045. {
  2046. echo ' Successful.', $endl;
  2047. flush();
  2048. }
  2049. $last_step = htmlspecialchars(rtrim(substr($line, 4)));
  2050. $upcontext['current_item_num']++;
  2051. $upcontext['current_item_name'] = $last_step;
  2052. if ($do_current)
  2053. {
  2054. $upcontext['actioned_items'][] = $last_step;
  2055. if ($command_line)
  2056. echo ' * ';
  2057. }
  2058. }
  2059. elseif ($type == '#')
  2060. {
  2061. $upcontext['step_progress'] += (100 / $upcontext['file_count']) / $file_steps;
  2062. $upcontext['current_debug_item_num']++;
  2063. if (trim($line) != '---#')
  2064. $upcontext['current_debug_item_name'] = htmlspecialchars(rtrim(substr($line, 4)));
  2065. // Have we already done something?
  2066. if (isset($_GET['xml']) && $done_something)
  2067. {
  2068. restore_error_handler();
  2069. return $upcontext['current_debug_item_num'] >= $upcontext['debug_items'] ? true : false;
  2070. }
  2071. if ($do_current)
  2072. {
  2073. if (trim($line) == '---#' && $command_line)
  2074. echo ' done.', $endl;
  2075. elseif ($command_line)
  2076. echo ' +++ ', rtrim(substr($line, 4));
  2077. elseif (trim($line) != '---#')
  2078. {
  2079. if ($is_debug)
  2080. $upcontext['actioned_items'][] = htmlspecialchars(rtrim(substr($line, 4)));
  2081. }
  2082. }
  2083. if ($substep < $_GET['substep'] && $substep + 1 >= $_GET['substep'])
  2084. {
  2085. if ($command_line)
  2086. echo ' * ';
  2087. else
  2088. $upcontext['actioned_items'][] = $last_step;
  2089. }
  2090. // Small step - only if we're actually doing stuff.
  2091. if ($do_current)
  2092. nextSubstep(++$substep);
  2093. else
  2094. $substep++;
  2095. }
  2096. elseif ($type == '{')
  2097. $current_type = 'code';
  2098. elseif ($type == '}')
  2099. {
  2100. $current_type = 'sql';
  2101. if (!$do_current)
  2102. {
  2103. $current_data = '';
  2104. continue;
  2105. }
  2106. if (eval('global $db_prefix, $modSettings, $smcFunc; ' . $current_data) === false)
  2107. {
  2108. $upcontext['error_message'] = 'Error in upgrade script ' . basename($filename) . ' on line ' . $line_number . '!' . $endl;
  2109. if ($command_line)
  2110. echo $upcontext['error_message'];
  2111. }
  2112. // Done with code!
  2113. $current_data = '';
  2114. $done_something = true;
  2115. }
  2116. continue;
  2117. }
  2118. $current_data .= $line;
  2119. if (substr(rtrim($current_data), -1) === ';' && $current_type === 'sql')
  2120. {
  2121. if ((!$support_js || isset($_GET['xml'])))
  2122. {
  2123. if (!$do_current)
  2124. {
  2125. $current_data = '';
  2126. continue;
  2127. }
  2128. $current_data = strtr(substr(rtrim($current_data), 0, -1), array('{$db_prefix}' => $db_prefix, '{$boarddir}' => $boarddir, '{$sboarddir}' => addslashes($boarddir), '{$boardurl}' => $boardurl, '{$db_collation}' => $db_collation));
  2129. upgrade_query($current_data);
  2130. // @todo This will be how it kinda does it once mysql all stripped out - needed for postgre (etc).
  2131. /*
  2132. $result = $smcFunc['db_query']('', $current_data, false, false);
  2133. // Went wrong?
  2134. if (!$result)
  2135. {
  2136. // Bit of a bodge - do we want the error?
  2137. if (!empty($upcontext['return_error']))
  2138. {
  2139. $upcontext['error_message'] = $smcFunc['db_error']($db_connection);
  2140. return false;
  2141. }
  2142. }*/
  2143. $done_something = true;
  2144. }
  2145. $current_data = '';
  2146. }
  2147. // If this is xml based and we're just getting the item name then that's grand.
  2148. elseif ($support_js && !isset($_GET['xml']) && $upcontext['current_debug_item_name'] != '' && $do_current)
  2149. {
  2150. restore_error_handler();
  2151. return false;
  2152. }
  2153. // Clean up by cleaning any step info.
  2154. $step_progress = array();
  2155. $custom_warning = '';
  2156. }
  2157. // Put back the error handler.
  2158. restore_error_handler();
  2159. if ($command_line)
  2160. {
  2161. echo ' Successful.' . "\n";
  2162. flush();
  2163. }
  2164. $_GET['substep'] = 0;
  2165. return true;
  2166. }
  2167. function upgrade_query($string, $unbuffered = false)
  2168. {
  2169. global $db_connection, $db_server, $db_user, $db_passwd, $db_type, $command_line, $upcontext, $upgradeurl, $modSettings;
  2170. global $db_name, $db_unbuffered, $smcFunc;
  2171. // Get the query result - working around some SMF specific security - just this once!
  2172. $modSettings['disableQueryCheck'] = true;
  2173. $db_unbuffered = $unbuffered;
  2174. $result = $smcFunc['db_query']('', $string, array('security_override' => true, 'db_error_skip' => true));
  2175. $db_unbuffered = false;
  2176. // Failure?!
  2177. if ($result !== false)
  2178. return $result;
  2179. $db_error_message = $smcFunc['db_error']($db_connection);
  2180. // If MySQL we do something more clever.
  2181. if ($db_type == 'mysql' || $db_type == 'mysqli')
  2182. {
  2183. $mysql_errno = ($db_type == 'mysqli') ? mysqli_errno($db_connection) : mysql_errno($db_connection);
  2184. $error_query = in_array(substr(trim($string), 0, 11), array('INSERT INTO', 'UPDATE IGNO', 'ALTER TABLE', 'DROP TABLE ', 'ALTER IGNOR'));
  2185. // Error numbers:
  2186. // 1016: Can't open file '....MYI'
  2187. // 1050: Table already exists.
  2188. // 1054: Unknown column name.
  2189. // 1060: Duplicate column name.
  2190. // 1061: Duplicate key name.
  2191. // 1062: Duplicate entry for unique key.
  2192. // 1068: Multiple primary keys.
  2193. // 1072: Key column '%s' doesn't exist in table.
  2194. // 1091: Can't drop key, doesn't exist.
  2195. // 1146: Table doesn't exist.
  2196. // 2013: Lost connection to server during query.
  2197. if ($mysql_errno == 1016)
  2198. {
  2199. if (preg_match('~\'([^\.\']+)~', $db_error_message, $match) != 0 && !empty($match[1]))
  2200. {
  2201. if ($db_type == 'mysql')
  2202. {
  2203. mysql_query('REPAIR TABLE `' . $match[1] . '`');
  2204. $result = mysql_query($string);
  2205. }
  2206. else
  2207. {
  2208. mysqli_query($db_connection, 'REPAIR TABLE `' . $match[1] . '`');
  2209. $result = mysqli_query($db_connection, $string);
  2210. }
  2211. if ($result !== false)
  2212. return $result;
  2213. }
  2214. }
  2215. elseif ($mysql_errno == 2013)
  2216. {
  2217. $db_connection = mysql_connect($db_server, $db_user, $db_passwd);
  2218. if ($db_type == 'mysql')
  2219. {
  2220. mysql_select_db($db_name, $db_connection);
  2221. if ($db_connection)
  2222. {
  2223. $result = mysql_query($string);
  2224. if ($result !== false)
  2225. return $result;
  2226. }
  2227. }
  2228. else
  2229. {
  2230. mysqli_select_db($db_connection, $db_name);
  2231. if ($db_connection)
  2232. {
  2233. $result = mysqli_query($db_connection, $string);
  2234. if ($result !== false)
  2235. return $result;
  2236. }
  2237. }
  2238. }
  2239. // Duplicate column name... should be okay ;).
  2240. elseif (in_array($mysql_errno, array(1060, 1061, 1068, 1091)))
  2241. return false;
  2242. // Duplicate insert... make sure it's the proper type of query ;).
  2243. elseif (in_array($mysql_errno, array(1054, 1062, 1146)) && $error_query)
  2244. return false;
  2245. // Creating an index on a non-existent column.
  2246. elseif ($mysql_errno == 1072)
  2247. return false;
  2248. elseif ($mysql_errno == 1050 && substr(trim($string), 0, 12) == 'RENAME TABLE')
  2249. return false;
  2250. }
  2251. // If a table already exists don't go potty.
  2252. else
  2253. {
  2254. if (in_array(substr(trim($string), 0, 8), array('CREATE T', 'CREATE S', 'DROP TABL', 'ALTER TA', 'CREATE I')))
  2255. {
  2256. if (strpos($db_error_message, 'exist') !== false)
  2257. return true;
  2258. // SQLite
  2259. if (strpos($db_error_message, 'missing') !== false)
  2260. return true;
  2261. }
  2262. elseif (strpos(trim($string), 'INSERT ') !== false)
  2263. {
  2264. if (strpos($db_error_message, 'duplicate') !== false)
  2265. return true;
  2266. }
  2267. }
  2268. // Get the query string so we pass everything.
  2269. $query_string = '';
  2270. foreach ($_GET as $k => $v)
  2271. $query_string .= ';' . $k . '=' . $v;
  2272. if (strlen($query_string) != 0)
  2273. $query_string = '?' . substr($query_string, 1);
  2274. if ($command_line)
  2275. {
  2276. echo 'Unsuccessful! Database error message:', "\n", $db_error_message, "\n";
  2277. die;
  2278. }
  2279. // Bit of a bodge - do we want the error?
  2280. if (!empty($upcontext['return_error']))
  2281. {
  2282. $upcontext['error_message'] = $db_error_message;
  2283. return false;
  2284. }
  2285. // Otherwise we have to display this somewhere appropriate if possible.
  2286. $upcontext['forced_error_message'] = '
  2287. <strong>Unsuccessful!</strong><br />
  2288. <div style="margin: 2ex;">
  2289. This query:
  2290. <blockquote><tt>' . nl2br(htmlspecialchars(trim($string))) . ';</tt></blockquote>
  2291. Caused the error:
  2292. <blockquote>' . nl2br(htmlspecialchars($db_error_message)) . '</blockquote>
  2293. </div>
  2294. <form action="' . $upgradeurl . $query_string . '" method="post">
  2295. <input type="submit" value="Try again" class="button_submit" />
  2296. </form>
  2297. </div>';
  2298. upgradeExit();
  2299. }
  2300. function smf_mysql_fetch_assoc($rs)
  2301. {
  2302. global $db_type;
  2303. return ($db_type == 'mysql') ? mysql_fetch_assoc($rs) : mysqli_fetch_assoc($rs);
  2304. }
  2305. function smf_mysql_fetch_row($rs)
  2306. {
  2307. global $db_type;
  2308. return ($db_type == 'mysql') ? mysql_fetch_row($rs) : mysqli_fetch_row($rs);
  2309. }
  2310. function smf_mysql_free_result($rs)
  2311. {
  2312. global $db_type;
  2313. return ($db_type == 'mysql') ? mysql_free_result($rs) : mysqli_free_result($rs);
  2314. }
  2315. function smf_mysql_insert_id($rs)
  2316. {
  2317. global $db_type;
  2318. return ($db_type == 'mysql') ? mysql_insert_id($rs) : mysqli_insert_id($rs);
  2319. }
  2320. function smf_mysql_num_rows($rs)
  2321. {
  2322. global $db_type;
  2323. return ($db_type == 'mysql') ? mysql_num_rows($rs) : mysqli_num_rows($rs);
  2324. }
  2325. function smf_mysql_real_escape_string($string)
  2326. {
  2327. global $db_type, $db_connection;
  2328. return ($db_type == 'mysql') ? mysql_real_escape_string($string, $db_connection) : mysqli_real_escape_string($db_connection, $string);
  2329. }
  2330. // This performs a table alter, but does it unbuffered so the script can time out professionally.
  2331. function protected_alter($change, $substep, $is_test = false)
  2332. {
  2333. global $db_prefix, $smcFunc;
  2334. db_extend('packages');
  2335. // Firstly, check whether the current index/column exists.
  2336. $found = false;
  2337. if ($change['type'] === 'column')
  2338. {
  2339. $columns = $smcFunc['db_list_columns']('{db_prefix}' . $change['table'], true);
  2340. foreach ($columns as $column)
  2341. {
  2342. // Found it?
  2343. if ($column['name'] === $change['name'])
  2344. {
  2345. $found |= 1;
  2346. // Do some checks on the data if we have it set.
  2347. if (isset($change['col_type']))
  2348. $found &= $change['col_type'] === $column['type'];
  2349. if (isset($change['null_allowed']))
  2350. $found &= $column['null'] == $change['null_allowed'];
  2351. if (isset($change['default']))
  2352. $found &= $change['default'] === $column['default'];
  2353. }
  2354. }
  2355. }
  2356. elseif ($change['type'] === 'index')
  2357. {
  2358. $request = upgrade_query( '
  2359. SHOW INDEX
  2360. FROM ' . $db_prefix . $change['table']);
  2361. if ($request !== false)
  2362. {
  2363. $cur_index = array();
  2364. while ($row = $smcFunc['db_fetch_assoc']($request))
  2365. if ($row['Key_name'] === $change['name'])
  2366. $cur_index[(int) $row['Seq_in_index']] = $row['Column_name'];
  2367. ksort($cur_index, SORT_NUMERIC);
  2368. $found = array_values($cur_index) === $change['target_columns'];
  2369. $smcFunc['db_free_result']($request);
  2370. }
  2371. }
  2372. // If we're trying to add and it's added, we're done.
  2373. if ($found && in_array($change['method'], array('add', 'change')))
  2374. return true;
  2375. // Otherwise if we're removing and it wasn't found we're also done.
  2376. elseif (!$found && in_array($change['method'], array('remove', 'change_remove')))
  2377. return true;
  2378. // Otherwise is it just a test?
  2379. elseif ($is_test)
  2380. return false;
  2381. // Not found it yet? Bummer! How about we see if we're currently doing it?
  2382. $running = false;
  2383. $found = false;
  2384. while (1 == 1)
  2385. {
  2386. $request = upgrade_query('
  2387. SHOW FULL PROCESSLIST');
  2388. while ($row = $smcFunc['db_fetch_assoc']($request))
  2389. {
  2390. if (strpos($row['Info'], 'ALTER TABLE ' . $db_prefix . $change['table']) !== false && strpos($row['Info'], $change['text']) !== false)
  2391. $found = true;
  2392. }
  2393. // Can't find it? Then we need to run it fools!
  2394. if (!$found && !$running)
  2395. {
  2396. $smcFunc['db_free_result']($request);
  2397. $success = upgrade_query('
  2398. ALTER TABLE ' . $db_prefix . $change['table'] . '
  2399. ' . $change['text'], true) !== false;
  2400. if (!$success)
  2401. return false;
  2402. // Return
  2403. $running = true;
  2404. }
  2405. // What if we've not found it, but we'd ran it already? Must of completed.
  2406. elseif (!$found)
  2407. {
  2408. $smcFunc['db_free_result']($request);
  2409. return true;
  2410. }
  2411. // Pause execution for a sec or three.
  2412. sleep(3);
  2413. // Can never be too well protected.
  2414. nextSubstep($substep);
  2415. }
  2416. // Protect it.
  2417. nextSubstep($substep);
  2418. }
  2419. // Alter a text column definition preserving its character set.
  2420. function textfield_alter($change, $substep)
  2421. {
  2422. global $db_prefix, $databases, $db_type, $smcFunc;
  2423. // Versions of MySQL < 4.1 wouldn't benefit from character set detection.
  2424. if (empty($databases[$db_type]['utf8_support']) || version_compare($databases[$db_type]['utf8_version'], eval($databases[$db_type]['utf8_version_check']), '>'))
  2425. {
  2426. $column_fix = true;
  2427. $null_fix = !$change['null_allowed'];
  2428. }
  2429. else
  2430. {
  2431. $request = $smcFunc['db_query']('', '
  2432. SHOW FULL COLUMNS
  2433. FROM {db_prefix}' . $change['table'] . '
  2434. LIKE {string:column}',
  2435. array(
  2436. 'column' => $change['column'],
  2437. 'db_error_skip' => true,
  2438. )
  2439. );
  2440. if ($smcFunc['db_num_rows']($request) === 0)
  2441. die('Unable to find column ' . $change['column'] . ' inside table ' . $db_prefix . $change['table']);
  2442. $table_row = $smcFunc['db_fetch_assoc']($request);
  2443. $smcFunc['db_free_result']($request);
  2444. // If something of the current column definition is different, fix it.
  2445. $column_fix = $table_row['Type'] !== $change['type'] || (strtolower($table_row['Null']) === 'yes') !== $change['null_allowed'] || ($table_row['Default'] === null) !== !isset($change['default']) || (isset($change['default']) && $change['default'] !== $table_row['Default']);
  2446. // Columns that previously allowed null, need to be converted first.
  2447. $null_fix = strtolower($table_row['Null']) === 'yes' && !$change['null_allowed'];
  2448. // Get the character set that goes with the collation of the column.
  2449. if ($column_fix && !empty($table_row['Collation']))
  2450. {
  2451. $request = $smcFunc['db_query']('', '
  2452. SHOW COLLATION
  2453. LIKE {string:collation}',
  2454. array(
  2455. 'collation' => $table_row['Collation'],
  2456. 'db_error_skip' => true,
  2457. )
  2458. );
  2459. // No results? Just forget it all together.
  2460. if ($smcFunc['db_num_rows']($request) === 0)
  2461. unset($table_row['Collation']);
  2462. else
  2463. $collation_info = $smcFunc['db_fetch_assoc']($request);
  2464. $smcFunc['db_free_result']($request);
  2465. }
  2466. }
  2467. if ($column_fix)
  2468. {
  2469. // Make sure there are no NULL's left.
  2470. if ($null_fix)
  2471. $smcFunc['db_query']('', '
  2472. UPDATE {db_prefix}' . $change['table'] . '
  2473. SET ' . $change['column'] . ' = {string:default}
  2474. WHERE ' . $change['column'] . ' IS NULL',
  2475. array(
  2476. 'default' => isset($change['default']) ? $change['default'] : '',
  2477. 'db_error_skip' => true,
  2478. )
  2479. );
  2480. // Do the actual alteration.
  2481. $smcFunc['db_query']('', '
  2482. ALTER TABLE {db_prefix}' . $change['table'] . '
  2483. CHANGE COLUMN ' . $change['column'] . ' ' . $change['column'] . ' ' . $change['type'] . (isset($collation_info['Charset']) ? ' CHARACTER SET ' . $collation_info['Charset'] . ' COLLATE ' . $collation_info['Collation'] : '') . ($change['null_allowed'] ? '' : ' NOT NULL') . (isset($change['default']) ? ' default {string:default}' : ''),
  2484. array(
  2485. 'default' => isset($change['default']) ? $change['default'] : '',
  2486. 'db_error_skip' => true,
  2487. )
  2488. );
  2489. }
  2490. nextSubstep($substep);
  2491. }
  2492. // Check if we need to alter this query.
  2493. function checkChange(&$change)
  2494. {
  2495. global $smcFunc, $db_type, $databases;
  2496. static $database_version, $where_field_support;
  2497. // Attempt to find a database_version.
  2498. if (empty($database_version))
  2499. {
  2500. $database_version = $databases[$db_type]['version_check'];
  2501. $where_field_support = ($db_type == 'mysql' || $db_type == 'mysqli') && version_compare('5.0', $database_version, '<=');
  2502. }
  2503. // Not a column we need to check on?
  2504. if (!in_array($change['name'], array('memberGroups', 'passwordSalt')))
  2505. return;
  2506. // Break it up you (six|seven).
  2507. $temp = explode(' ', str_replace('NOT NULL', 'NOT_NULL', $change['text']));
  2508. // Can we support a shortcut method?
  2509. if ($where_field_support)
  2510. {
  2511. // Get the details about this change.
  2512. $request = $smcFunc['db_query']('', '
  2513. SHOW FIELDS
  2514. FROM {db_prefix}{raw:table}
  2515. WHERE Field = {string:old_name} OR Field = {string:new_name}',
  2516. array(
  2517. 'table' => $change['table'],
  2518. 'old_name' => $temp[1],
  2519. 'new_name' => $temp[2],
  2520. ));
  2521. if ($smcFunc['db_num_rows'] != 1)
  2522. return;
  2523. list (, $current_type) = $smcFunc['db_fetch_assoc']($request);
  2524. $smcFunc['db_free_result']($request);
  2525. }
  2526. else
  2527. {
  2528. // Do this the old fashion, sure method way.
  2529. $request = $smcFunc['db_query']('', '
  2530. SHOW FIELDS
  2531. FROM {db_prefix}{raw:table}',
  2532. array(
  2533. 'table' => $change['table'],
  2534. ));
  2535. // Mayday!
  2536. if ($smcFunc['db_num_rows'] == 0)
  2537. return;
  2538. // Oh where, oh where has my little field gone. Oh where can it be...
  2539. while ($row = $smcFunc['db_query']($request))
  2540. if ($row['Field'] == $temp[1] || $row['Field'] == $temp[2])
  2541. {
  2542. $current_type = $row['Type'];
  2543. break;
  2544. }
  2545. }
  2546. // If this doesn't match, the column may of been altered for a reason.
  2547. if (trim($current_type) != trim($temp[3]))
  2548. $temp[3] = $current_type;
  2549. // Piece this back together.
  2550. $change['text'] = str_replace('NOT_NULL', 'NOT NULL', implode(' ', $temp));
  2551. }
  2552. // The next substep.
  2553. function nextSubstep($substep)
  2554. {
  2555. global $start_time, $timeLimitThreshold, $command_line, $file_steps, $modSettings, $custom_warning;
  2556. global $step_progress, $is_debug, $upcontext;
  2557. if ($_GET['substep'] < $substep)
  2558. $_GET['substep'] = $substep;
  2559. if ($command_line)
  2560. {
  2561. if (time() - $start_time > 1 && empty($is_debug))
  2562. {
  2563. echo '.';
  2564. $start_time = time();
  2565. }
  2566. return;
  2567. }
  2568. @set_time_limit(300);
  2569. if (function_exists('apache_reset_timeout'))
  2570. @apache_reset_timeout();
  2571. if (time() - $start_time <= $timeLimitThreshold)
  2572. return;
  2573. // Do we have some custom step progress stuff?
  2574. if (!empty($step_progress))
  2575. {
  2576. $upcontext['substep_progress'] = 0;
  2577. $upcontext['substep_progress_name'] = $step_progress['name'];
  2578. if ($step_progress['current'] > $step_progress['total'])
  2579. $upcontext['substep_progress'] = 99.9;
  2580. else
  2581. $upcontext['substep_progress'] = ($step_progress['current'] / $step_progress['total']) * 100;
  2582. // Make it nicely rounded.
  2583. $upcontext['substep_progress'] = round($upcontext['substep_progress'], 1);
  2584. }
  2585. // If this is XML we just exit right away!
  2586. if (isset($_GET['xml']))
  2587. return upgradeExit();
  2588. // We're going to pause after this!
  2589. $upcontext['pause'] = true;
  2590. $upcontext['query_string'] = '';
  2591. foreach ($_GET as $k => $v)
  2592. {
  2593. if ($k != 'data' && $k != 'substep' && $k != 'step')
  2594. $upcontext['query_string'] .= ';' . $k . '=' . $v;
  2595. }
  2596. // Custom warning?
  2597. if (!empty($custom_warning))
  2598. $upcontext['custom_warning'] = $custom_warning;
  2599. upgradeExit();
  2600. }
  2601. function cmdStep0()
  2602. {
  2603. global $boarddir, $sourcedir, $db_prefix, $language, $modSettings, $start_time, $cachedir, $databases, $db_type, $smcFunc, $upcontext;
  2604. global $language, $is_debug, $txt;
  2605. $start_time = time();
  2606. ob_end_clean();
  2607. ob_implicit_flush(true);
  2608. @set_time_limit(600);
  2609. if (!isset($_SERVER['argv']))
  2610. $_SERVER['argv'] = array();
  2611. $_GET['maint'] = 1;
  2612. foreach ($_SERVER['argv'] as $i => $arg)
  2613. {
  2614. if (preg_match('~^--language=(.+)$~', $arg, $match) != 0)
  2615. $_GET['lang'] = $match[1];
  2616. elseif (preg_match('~^--path=(.+)$~', $arg) != 0)
  2617. continue;
  2618. elseif ($arg == '--no-maintenance')
  2619. $_GET['maint'] = 0;
  2620. elseif ($arg == '--debug')
  2621. $is_debug = true;
  2622. elseif ($arg == '--backup')
  2623. $_POST['backup'] = 1;
  2624. elseif ($arg == '--template' && (file_exists($boarddir . '/template.php') || file_exists($boarddir . '/template.html') && !file_exists($modSettings['theme_dir'] . '/converted')))
  2625. $_GET['conv'] = 1;
  2626. elseif ($i != 0)
  2627. {
  2628. echo 'SMF Command-line Upgrader
  2629. Usage: /path/to/php -f ' . basename(__FILE__) . ' -- [OPTION]...
  2630. --language=LANG Reset the forum\'s language to LANG.
  2631. --no-maintenance Don\'t put the forum into maintenance mode.
  2632. --debug Output debugging information.
  2633. --backup Create backups of tables with "backup_" prefix.';
  2634. echo "\n";
  2635. exit;
  2636. }
  2637. }
  2638. if (!php_version_check())
  2639. print_error('Error: PHP ' . PHP_VERSION . ' does not match version requirements.', true);
  2640. if (!db_version_check())
  2641. print_error('Error: ' . $databases[$db_type]['name'] . ' ' . $databases[$db_type]['version'] . ' does not match minimum requirements.', true);
  2642. if (!empty($databases[$db_type]['alter_support']) && $smcFunc['db_query']('alter_boards', 'ALTER TABLE {db_prefix}boards ORDER BY id_board', array()) === false)
  2643. print_error('Error: The ' . $databases[$db_type]['name'] . ' account in Settings.php does not have sufficient privileges.', true);
  2644. $check = @file_exists($modSettings['theme_dir'] . '/index.template.php')
  2645. && @file_exists($sourcedir . '/QueryString.php')
  2646. && @file_exists($sourcedir . '/ManageBoards.php');
  2647. if (!$check && !isset($modSettings['smfVersion']))
  2648. print_error('Error: Some files are missing or out-of-date.', true);
  2649. // Do a quick version spot check.
  2650. $temp = substr(@implode('', @file($boarddir . '/index.php')), 0, 4096);
  2651. preg_match('~\*\s@version\s+(.+)[\s]{2}~i', $temp, $match);
  2652. if (empty($match[1]) || $match[1] != SMF_VERSION)
  2653. print_error('Error: Some files have not yet been updated properly.');
  2654. // Make sure Settings.php is writable.
  2655. if (!is_writable($boarddir . '/Settings.php'))
  2656. @chmod($boarddir . '/Settings.php', 0777);
  2657. if (!is_writable($boarddir . '/Settings.php'))
  2658. print_error('Error: Unable to obtain write access to "Settings.php".', true);
  2659. // Make sure Settings.php is writable.
  2660. if (!is_writable($boarddir . '/Settings_bak.php'))
  2661. @chmod($boarddir . '/Settings_bak.php', 0777);
  2662. if (!is_writable($boarddir . '/Settings_bak.php'))
  2663. print_error('Error: Unable to obtain write access to "Settings_bak.php".');
  2664. if (isset($modSettings['agreement']) && (!is_writable($boarddir) || file_exists($boarddir . '/agreement.txt')) && !is_writable($boarddir . '/agreement.txt'))
  2665. print_error('Error: Unable to obtain write access to "agreement.txt".');
  2666. elseif (isset($modSettings['agreement']))
  2667. {
  2668. $fp = fopen($boarddir . '/agreement.txt', 'w');
  2669. fwrite($fp, $modSettings['agreement']);
  2670. fclose($fp);
  2671. }
  2672. // Make sure Themes is writable.
  2673. if (!is_writable($modSettings['theme_dir']))
  2674. @chmod($modSettings['theme_dir'], 0777);
  2675. if (!is_writable($modSettings['theme_dir']) && !isset($modSettings['smfVersion']))
  2676. print_error('Error: Unable to obtain write access to "Themes".');
  2677. // Make sure cache directory exists and is writable!
  2678. $cachedir_temp = empty($cachedir) ? $boarddir . '/cache' : $cachedir;
  2679. if (!file_exists($cachedir_temp))
  2680. @mkdir($cachedir_temp);
  2681. if (!is_writable($cachedir_temp))
  2682. @chmod($cachedir_temp, 0777);
  2683. if (!is_writable($cachedir_temp))
  2684. print_error('Error: Unable to obtain write access to "cache".', true);
  2685. if (!file_exists($modSettings['theme_dir'] . '/languages/index.' . $upcontext['language'] . '.php') && !isset($modSettings['smfVersion']) && !isset($_GET['lang']))
  2686. print_error('Error: Unable to find language files!', true);
  2687. else
  2688. {
  2689. $temp = substr(@implode('', @file($modSettings['theme_dir'] . '/languages/index.' . $upcontext['language'] . '.php')), 0, 4096);
  2690. preg_match('~(?://|/\*)\s*Version:\s+(.+?);\s*index(?:[\s]{2}|\*/)~i', $temp, $match);
  2691. if (empty($match[1]) || $match[1] != SMF_LANG_VERSION)
  2692. print_error('Error: Language files out of date.', true);
  2693. if (!file_exists($modSettings['theme_dir'] . '/languages/Install.' . $upcontext['language'] . '.php'))
  2694. print_error('Error: Install language is missing for selected language.', true);
  2695. // Otherwise include it!
  2696. require_once($modSettings['theme_dir'] . '/languages/Install.' . $upcontext['language'] . '.php');
  2697. }
  2698. // Make sure we skip the HTML for login.
  2699. $_POST['upcont'] = true;
  2700. $upcontext['current_step'] = 1;
  2701. }
  2702. function print_error($message, $fatal = false)
  2703. {
  2704. static $fp = null;
  2705. if ($fp === null)
  2706. $fp = fopen('php://stderr', 'wb');
  2707. fwrite($fp, $message . "\n");
  2708. if ($fatal)
  2709. exit;
  2710. }
  2711. function throw_error($message)
  2712. {
  2713. global $upcontext;
  2714. $upcontext['error_msg'] = $message;
  2715. $upcontext['sub_template'] = 'error_message';
  2716. return false;
  2717. }
  2718. // Check files are writable - make them writable if necessary...
  2719. function makeFilesWritable(&$files)
  2720. {
  2721. global $upcontext, $boarddir;
  2722. if (empty($files))
  2723. return true;
  2724. $failure = false;
  2725. // On linux, it's easy - just use is_writable!
  2726. if (substr(__FILE__, 1, 2) != ':\\')
  2727. {
  2728. foreach ($files as $k => $file)
  2729. {
  2730. if (!is_writable($file))
  2731. {
  2732. @chmod($file, 0755);
  2733. // Well, 755 hopefully worked... if not, try 777.
  2734. if (!is_writable($file) && !@chmod($file, 0777))
  2735. $failure = true;
  2736. // Otherwise remove it as it's good!
  2737. else
  2738. unset($files[$k]);
  2739. }
  2740. else
  2741. unset($files[$k]);
  2742. }
  2743. }
  2744. // Windows is trickier. Let's try opening for r+...
  2745. else
  2746. {
  2747. foreach ($files as $k => $file)
  2748. {
  2749. // Folders can't be opened for write... but the index.php in them can ;).
  2750. if (is_dir($file))
  2751. $file .= '/index.php';
  2752. // Funny enough, chmod actually does do something on windows - it removes the read only attribute.
  2753. @chmod($file, 0777);
  2754. $fp = @fopen($file, 'r+');
  2755. // Hmm, okay, try just for write in that case...
  2756. if (!$fp)
  2757. $fp = @fopen($file, 'w');
  2758. if (!$fp)
  2759. $failure = true;
  2760. else
  2761. unset($files[$k]);
  2762. @fclose($fp);
  2763. }
  2764. }
  2765. if (empty($files))
  2766. return true;
  2767. if (!isset($_SERVER))
  2768. return !$failure;
  2769. // What still needs to be done?
  2770. $upcontext['chmod']['files'] = $files;
  2771. // If it's windows it's a mess...
  2772. if ($failure && substr(__FILE__, 1, 2) == ':\\')
  2773. {
  2774. $upcontext['chmod']['ftp_error'] = 'total_mess';
  2775. return false;
  2776. }
  2777. // We're going to have to use... FTP!
  2778. elseif ($failure)
  2779. {
  2780. // Load any session data we might have...
  2781. if (!isset($_POST['ftp_username']) && isset($_SESSION['installer_temp_ftp']))
  2782. {
  2783. $upcontext['chmod']['server'] = $_SESSION['installer_temp_ftp']['server'];
  2784. $upcontext['chmod']['port'] = $_SESSION['installer_temp_ftp']['port'];
  2785. $upcontext['chmod']['username'] = $_SESSION['installer_temp_ftp']['username'];
  2786. $upcontext['chmod']['password'] = $_SESSION['installer_temp_ftp']['password'];
  2787. $upcontext['chmod']['path'] = $_SESSION['installer_temp_ftp']['path'];
  2788. }
  2789. // Or have we submitted?
  2790. elseif (isset($_POST['ftp_username']))
  2791. {
  2792. $upcontext['chmod']['server'] = $_POST['ftp_server'];
  2793. $upcontext['chmod']['port'] = $_POST['ftp_port'];
  2794. $upcontext['chmod']['username'] = $_POST['ftp_username'];
  2795. $upcontext['chmod']['password'] = $_POST['ftp_password'];
  2796. $upcontext['chmod']['path'] = $_POST['ftp_path'];
  2797. }
  2798. if (isset($upcontext['chmod']['username']))
  2799. {
  2800. $ftp = new ftp_connection($upcontext['chmod']['server'], $upcontext['chmod']['port'], $upcontext['chmod']['username'], $upcontext['chmod']['password']);
  2801. if ($ftp->error === false)
  2802. {
  2803. // Try it without /home/abc just in case they messed up.
  2804. if (!$ftp->chdir($upcontext['chmod']['path']))
  2805. {
  2806. $upcontext['chmod']['ftp_error'] = $ftp->last_message;
  2807. $ftp->chdir(preg_replace('~^/home[2]?/[^/]+?~', '', $upcontext['chmod']['path']));
  2808. }
  2809. }
  2810. }
  2811. if (!isset($ftp) || $ftp->error !== false)
  2812. {
  2813. if (!isset($ftp))
  2814. $ftp = new ftp_connection(null);
  2815. // Save the error so we can mess with listing...
  2816. elseif ($ftp->error !== false && !isset($upcontext['chmod']['ftp_error']))
  2817. $upcontext['chmod']['ftp_error'] = $ftp->last_message === null ? '' : $ftp->last_message;
  2818. list ($username, $detect_path, $found_path) = $ftp->detect_path(dirname(__FILE__));
  2819. if ($found_path || !isset($upcontext['chmod']['path']))
  2820. $upcontext['chmod']['path'] = $detect_path;
  2821. if (!isset($upcontext['chmod']['username']))
  2822. $upcontext['chmod']['username'] = $username;
  2823. return false;
  2824. }
  2825. else
  2826. {
  2827. // We want to do a relative path for FTP.
  2828. if (!in_array($upcontext['chmod']['path'], array('', '/')))
  2829. {
  2830. $ftp_root = strtr($boarddir, array($upcontext['chmod']['path'] => ''));
  2831. if (substr($ftp_root, -1) == '/' && ($upcontext['chmod']['path'] == '' || $upcontext['chmod']['path'][0] === '/'))
  2832. $ftp_root = substr($ftp_root, 0, -1);
  2833. }
  2834. else
  2835. $ftp_root = $boarddir;
  2836. // Save the info for next time!
  2837. $_SESSION['installer_temp_ftp'] = array(
  2838. 'server' => $upcontext['chmod']['server'],
  2839. 'port' => $upcontext['chmod']['port'],
  2840. 'username' => $upcontext['chmod']['username'],
  2841. 'password' => $upcontext['chmod']['password'],
  2842. 'path' => $upcontext['chmod']['path'],
  2843. 'root' => $ftp_root,
  2844. );
  2845. foreach ($files as $k => $file)
  2846. {
  2847. if (!is_writable($file))
  2848. $ftp->chmod($file, 0755);
  2849. if (!is_writable($file))
  2850. $ftp->chmod($file, 0777);
  2851. // Assuming that didn't work calculate the path without the boarddir.
  2852. if (!is_writable($file))
  2853. {
  2854. if (strpos($file, $boarddir) === 0)
  2855. {
  2856. $ftp_file = strtr($file, array($_SESSION['installer_temp_ftp']['root'] => ''));
  2857. $ftp->chmod($ftp_file, 0755);
  2858. if (!is_writable($file))
  2859. $ftp->chmod($ftp_file, 0777);
  2860. // Sometimes an extra slash can help...
  2861. $ftp_file = '/' . $ftp_file;
  2862. if (!is_writable($file))
  2863. $ftp->chmod($ftp_file, 0755);
  2864. if (!is_writable($file))
  2865. $ftp->chmod($ftp_file, 0777);
  2866. }
  2867. }
  2868. if (is_writable($file))
  2869. unset($files[$k]);
  2870. }
  2871. $ftp->close();
  2872. }
  2873. }
  2874. // What remains?
  2875. $upcontext['chmod']['files'] = $files;
  2876. if (empty($files))
  2877. return true;
  2878. return false;
  2879. }
  2880. /******************************************************************************
  2881. ******************* Templates are below this point ****************************
  2882. ******************************************************************************/
  2883. // This is what is displayed if there's any chmod to be done. If not it returns nothing...
  2884. function template_chmod()
  2885. {
  2886. global $upcontext, $upgradeurl, $settings;
  2887. // Don't call me twice!
  2888. if (!empty($upcontext['chmod_called']))
  2889. return;
  2890. $upcontext['chmod_called'] = true;
  2891. // Nothing?
  2892. if (empty($upcontext['chmod']['files']) && empty($upcontext['chmod']['ftp_error']))
  2893. return;
  2894. // @todo Temporary!
  2895. $txt['error_ftp_no_connect'] = 'Unable to connect to FTP server with this combination of details.';
  2896. $txt['ftp_login'] = 'Your FTP connection information';
  2897. $txt['ftp_login_info'] = 'This web installer needs your FTP information in order to automate the installation for you. Please note that none of this information is saved in your installation, it is just used to setup SMF.';
  2898. $txt['ftp_server'] = 'Server';
  2899. $txt['ftp_server_info'] = 'The address (often localhost) and port for your FTP server.';
  2900. $txt['ftp_port'] = 'Port';
  2901. $txt['ftp_username'] = 'Username';
  2902. $txt['ftp_username_info'] = 'The username to login with. <em>This will not be saved anywhere.</em>';
  2903. $txt['ftp_password'] = 'Password';
  2904. $txt['ftp_password_info'] = 'The password to login with. <em>This will not be saved anywhere.</em>';
  2905. $txt['ftp_path'] = 'Install Path';
  2906. $txt['ftp_path_info'] = 'This is the <em>relative</em> path you use in your FTP client <a href="' . $_SERVER['PHP_SELF'] . '?ftphelp" onclick="window.open(this.href, \'\', \'width=450,height=250\');return false;" target="_blank">(more help)</a>.';
  2907. $txt['ftp_path_found_info'] = 'The path in the box above was automatically detected.';
  2908. $txt['ftp_path_help'] = 'Your FTP path is the path you see when you log in to your FTP client. It commonly starts with &quot;<tt>www</tt>&quot;, &quot;<tt>public_html</tt>&quot;, or &quot;<tt>httpdocs</tt>&quot; - but it should include the directory SMF is in too, such as &quot;/public_html/forum&quot;. It is different from your URL and full path.<br /><br />Files in this path may be overwritten, so make sure it\'s correct.';
  2909. $txt['ftp_path_help_close'] = 'Close';
  2910. $txt['ftp_connect'] = 'Connect';
  2911. // Was it a problem with Windows?
  2912. if (!empty($upcontext['chmod']['ftp_error']) && $upcontext['chmod']['ftp_error'] == 'total_mess')
  2913. {
  2914. echo '
  2915. <div class="error_message">
  2916. <div style="color: red;">The following files need to be writable to continue the upgrade. Please ensure the Windows permissions are correctly set to allow this:</div>
  2917. <ul style="margin: 2.5ex; font-family: monospace;">
  2918. <li>' . implode('</li>
  2919. <li>', $upcontext['chmod']['files']). '</li>
  2920. </ul>
  2921. </div>';
  2922. return false;
  2923. }
  2924. echo '
  2925. <div class="panel">
  2926. <h2>Your FTP connection information</h2>
  2927. <h3>The upgrader can fix any issues with file permissions to make upgrading as simple as possible. Simply enter your connection information below or alternatively click <a href="#" onclick="warning_popup();">here</a> for a list of files which need to be changed.</h3>
  2928. <script type="text/javascript"><!-- // --><![CDATA[
  2929. function warning_popup()
  2930. {
  2931. popup = window.open(\'\',\'popup\',\'height=150,width=400,scrollbars=yes\');
  2932. var content = popup.document;
  2933. content.write(\'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n\');
  2934. content.write(\'<html xmlns="http://www.w3.org/1999/xhtml"', $upcontext['right_to_left'] ? ' dir="rtl"' : '', '>\n\t<head>\n\t\t<meta name="robots" content="noindex" />\n\t\t\');
  2935. content.write(\'<title>Warning</title>\n\t\t<link rel="stylesheet" type="text/css" href="', $settings['default_theme_url'], '/css/index.css" />\n\t</head>\n\t<body id="popup">\n\t\t\');
  2936. content.write(\'<div class="windowbg description">\n\t\t\t<h4>The following files needs to be made writable to continue:</h4>\n\t\t\t\');
  2937. content.write(\'<p>', implode('<br />\n\t\t\t', $upcontext['chmod']['files']), '</p>\n\t\t\t\');
  2938. content.write(\'<a href="javascript:self.close();">close</a>\n\t\t</div>\n\t</body>\n</html>\');
  2939. content.close();
  2940. }
  2941. // ]]></script>';
  2942. if (!empty($upcontext['chmod']['ftp_error']))
  2943. echo '
  2944. <div class="error_message">
  2945. <div style="color: red;">
  2946. The following error was encountered when trying to connect:<br />
  2947. <br />
  2948. <code>', $upcontext['chmod']['ftp_error'], '</code>
  2949. </div>
  2950. </div>
  2951. <br />';
  2952. if (empty($upcontext['chmod_in_form']))
  2953. echo '
  2954. <form action="', $upcontext['form_url'], '" method="post">';
  2955. echo '
  2956. <table width="520" cellspacing="0" cellpadding="0" border="0" align="center" style="margin-bottom: 1ex;">
  2957. <tr>
  2958. <td width="26%" valign="top" class="textbox"><label for="ftp_server">', $txt['ftp_server'], ':</label></td>
  2959. <td>
  2960. <div style="float: right; margin-right: 1px;"><label for="ftp_port" class="textbox"><strong>', $txt['ftp_port'], ':&nbsp;</strong></label> <input type="text" size="3" name="ftp_port" id="ftp_port" value="', isset($upcontext['chmod']['port']) ? $upcontext['chmod']['port'] : '21', '" class="input_text" /></div>
  2961. <input type="text" size="30" name="ftp_server" id="ftp_server" value="', isset($upcontext['chmod']['server']) ? $upcontext['chmod']['server'] : 'localhost', '" style="width: 70%;" class="input_text" />
  2962. <div style="font-size: smaller; margin-bottom: 2ex;">', $txt['ftp_server_info'], '</div>
  2963. </td>
  2964. </tr><tr>
  2965. <td width="26%" valign="top" class="textbox"><label for="ftp_username">', $txt['ftp_username'], ':</label></td>
  2966. <td>
  2967. <input type="text" size="50" name="ftp_username" id="ftp_username" value="', isset($upcontext['chmod']['username']) ? $upcontext['chmod']['username'] : '', '" style="width: 99%;" class="input_text" />
  2968. <div style="font-size: smaller; margin-bottom: 2ex;">', $txt['ftp_username_info'], '</div>
  2969. </td>
  2970. </tr><tr>
  2971. <td width="26%" valign="top" class="textbox"><label for="ftp_password">', $txt['ftp_password'], ':</label></td>
  2972. <td>
  2973. <input type="password" size="50" name="ftp_password" id="ftp_password" style="width: 99%;" class="input_password" />
  2974. <div style="font-size: smaller; margin-bottom: 3ex;">', $txt['ftp_password_info'], '</div>
  2975. </td>
  2976. </tr><tr>
  2977. <td width="26%" valign="top" class="textbox"><label for="ftp_path">', $txt['ftp_path'], ':</label></td>
  2978. <td style="padding-bottom: 1ex;">
  2979. <input type="text" size="50" name="ftp_path" id="ftp_path" value="', isset($upcontext['chmod']['path']) ? $upcontext['chmod']['path'] : '', '" style="width: 99%;" class="input_text" />
  2980. <div style="font-size: smaller; margin-bottom: 2ex;">', !empty($upcontext['chmod']['path']) ? $txt['ftp_path_found_info'] : $txt['ftp_path_info'], '</div>
  2981. </td>
  2982. </tr>
  2983. </table>
  2984. <div class="righttext" style="margin: 1ex;"><input type="submit" value="', $txt['ftp_connect'], '" class="button_submit" /></div>
  2985. </div>';
  2986. if (empty($upcontext['chmod_in_form']))
  2987. echo '
  2988. </form>';
  2989. }
  2990. function template_upgrade_above()
  2991. {
  2992. global $modSettings, $txt, $smfsite, $settings, $upcontext, $upgradeurl;
  2993. echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2994. <html xmlns="http://www.w3.org/1999/xhtml"', $upcontext['right_to_left'] ? ' dir="rtl"' : '', '>
  2995. <head>
  2996. <meta http-equiv="Content-Type" content="text/html; charset=', isset($txt['lang_character_set']) ? $txt['lang_character_set'] : 'ISO-8859-1', '" />
  2997. <meta name="robots" content="noindex" />
  2998. <title>', $txt['upgrade_upgrade_utility'], '</title>
  2999. <link rel="stylesheet" type="text/css" href="', $settings['default_theme_url'], '/css/index.css?alp21" />
  3000. <link rel="stylesheet" type="text/css" href="', $settings['default_theme_url'], '/css/install.css?alp21" />
  3001. <script type="text/javascript" src="', $settings['default_theme_url'], '/scripts/script.js"></script>
  3002. <script type="text/javascript"><!-- // --><![CDATA[
  3003. var smf_scripturl = \'', $upgradeurl, '\';
  3004. var smf_charset = \'', (empty($modSettings['global_character_set']) ? (empty($txt['lang_character_set']) ? 'ISO-8859-1' : $txt['lang_character_set']) : $modSettings['global_character_set']), '\';
  3005. var startPercent = ', $upcontext['overall_percent'], ';
  3006. // This function dynamically updates the step progress bar - and overall one as required.
  3007. function updateStepProgress(current, max, overall_weight)
  3008. {
  3009. // What out the actual percent.
  3010. var width = parseInt((current / max) * 100);
  3011. if (document.getElementById(\'step_progress\'))
  3012. {
  3013. document.getElementById(\'step_progress\').style.width = width + "%";
  3014. setInnerHTML(document.getElementById(\'step_text\'), width + "%");
  3015. }
  3016. if (overall_weight && document.getElementById(\'overall_progress\'))
  3017. {
  3018. overall_width = parseInt(startPercent + width * (overall_weight / 100));
  3019. document.getElementById(\'overall_progress\').style.width = overall_width + "%";
  3020. setInnerHTML(document.getElementById(\'overall_text\'), overall_width + "%");
  3021. }
  3022. }
  3023. // ]]></script>
  3024. </head>
  3025. <body>
  3026. <div id="header"><div class="frame">
  3027. <h1 class="forumtitle">', $txt['upgrade_upgrade_utility'], '</h1>
  3028. <img id="smflogo" src="', $settings['default_theme_url'], '/images/smflogo.png" alt="Simple Machines Forum" title="Simple Machines Forum" />
  3029. </div></div>
  3030. <div id="wrapper">
  3031. <div id="upper_section">
  3032. <div id="main_content_section">
  3033. <div id="main_steps">
  3034. <h2>', $txt['upgrade_progress'], '</h2>
  3035. <ul>';
  3036. foreach ($upcontext['steps'] as $num => $step)
  3037. echo '
  3038. <li class="', $num < $upcontext['current_step'] ? 'stepdone' : ($num == $upcontext['current_step'] ? 'stepcurrent' : 'stepwaiting'), '">', $txt['upgrade_step'], ' ', $step[0], ': ', $step[1], '</li>';
  3039. echo '
  3040. </ul>
  3041. </div>
  3042. <div id="progress">
  3043. <div id="overall_text_upgrade">', $upcontext['overall_percent'], '%</div>
  3044. <div id="overall_progress_upgrade" style="width: ', $upcontext['overall_percent'], '%;">&nbsp;</div>
  3045. <div class="over_progress">', $txt['upgrade_overall_progress'], '</div>
  3046. </div>';
  3047. if (isset($upcontext['step_progress']))
  3048. echo '
  3049. <br />
  3050. <br />
  3051. <div id="progress">
  3052. <div id="step_text_upgrade">', $upcontext['step_progress'], '%</div>
  3053. <div id="step_progress_upgrade" style="width: ', $upcontext['step_progress'], '%;background-color: #ffd000;">&nbsp;</div>
  3054. <div class="over_progress">', $txt['upgrade_step_progress'], '</div>
  3055. </div>';
  3056. echo '
  3057. <div id="substep_bar_div" class="smalltext" style="display: ', isset($upcontext['substep_progress']) ? '' : 'none', ';">', isset($upcontext['substep_progress_name']) ? trim(strtr($upcontext['substep_progress_name'], array('.' => ''))) : '', ':</div>
  3058. <div id="substep_bar_div2" style="font-size: 8pt; height: 12pt; border: 1px solid black; background-color: white; width: 50%; margin: 5px auto; display: ', isset($upcontext['substep_progress']) ? '' : 'none', ';">
  3059. <div id="substep_text" style="color: #000; position: absolute; margin-left: -5em;">', isset($upcontext['substep_progress']) ? $upcontext['substep_progress'] : '', '%</div>
  3060. <div id="substep_progress" style="width: ', isset($upcontext['substep_progress']) ? $upcontext['substep_progress'] : 0, '%; height: 12pt; z-index: 1; background-color: #eebaf4;">&nbsp;</div>
  3061. </div>';
  3062. // How long have we been running this?
  3063. $elapsed = time() - $upcontext['started'];
  3064. $mins = (int) ($elapsed / 60);
  3065. $seconds = $elapsed - $mins * 60;
  3066. echo '
  3067. <br /> <br /> <br /> <br />
  3068. <div class="smalltext" style="padding: 5px; text-align: center;"><br />', $txt['upgrade_time_elapsed'], ':
  3069. <span id="mins_elapsed">', $mins, '</span> ', $txt['upgrade_time_mins'], ', <span id="secs_elapsed">', $seconds, '</span> ', $txt['upgrade_time_secs'], '.
  3070. </div>';
  3071. echo '
  3072. </div>
  3073. </div>
  3074. <div id="content_section">
  3075. <div id="main_screen" class="clear">
  3076. <h2>', $upcontext['page_title'], '</h2>
  3077. <div class="panel">
  3078. <div style="max-height: 360px; overflow: auto;">';
  3079. }
  3080. function template_upgrade_below()
  3081. {
  3082. global $upcontext, $txt;
  3083. if (!empty($upcontext['pause']))
  3084. echo '
  3085. <em>', $txt['upgrade_incomplete'], '.</em><br />
  3086. <h2 style="margin-top: 2ex;">', $txt['upgrade_not_quite_done'], '</h2>
  3087. <h3>
  3088. ', $txt['upgrade_paused_overload'], '
  3089. </h3>';
  3090. if (!empty($upcontext['custom_warning']))
  3091. echo '
  3092. <div style="margin: 2ex; padding: 2ex; border: 2px dashed #cc3344; color: black; background-color: #ffe4e9;">
  3093. <div style="float: left; width: 2ex; font-size: 2em; color: red;">!!</div>
  3094. <strong style="text-decoration: underline;">', $txt['upgrade_note'], '</strong><br />
  3095. <div style="padding-left: 6ex;">', $upcontext['custom_warning'], '</div>
  3096. </div>';
  3097. echo '
  3098. <div class="righttext" style="margin: 1ex;">';
  3099. if (!empty($upcontext['continue']))
  3100. echo '
  3101. <input type="submit" id="contbutt" name="contbutt" value="', $txt['upgrade_continue'], '"', $upcontext['continue'] == 2 ? ' disabled="disabled"' : '', ' class="button_submit" />';
  3102. if (!empty($upcontext['skip']))
  3103. echo '
  3104. <input type="submit" id="skip" name="skip" value="', $txt['upgrade_skip'], '" onclick="dontSubmit = true; document.getElementById(\'contbutt\').disabled = \'disabled\'; return true;" class="button_submit" />';
  3105. echo '
  3106. </div>
  3107. </form>
  3108. </div>
  3109. </div>
  3110. </div>
  3111. </div>
  3112. </div>
  3113. <div id="footer_section"><div class="frame" style="height: 40px;">
  3114. <ul class="reset">
  3115. <li class="copyright"><a href="http://www.simplemachines.org/" title="Simple Machines Forum" target="_blank" class="new_win">SMF &copy;2013, Simple Machines</a></li>
  3116. </ul>
  3117. </div></div>
  3118. </body>
  3119. </html>';
  3120. // Are we on a pause?
  3121. if (!empty($upcontext['pause']))
  3122. {
  3123. echo '
  3124. <script type="text/javascript"><!-- // --><![CDATA[
  3125. window.onload = doAutoSubmit;
  3126. var countdown = 3;
  3127. var dontSubmit = false;
  3128. function doAutoSubmit()
  3129. {
  3130. if (countdown == 0 && !dontSubmit)
  3131. document.upform.submit();
  3132. else if (countdown == -1)
  3133. return;
  3134. document.getElementById(\'contbutt\').value = "', $txt['upgrade_continue'], ' (" + countdown + ")";
  3135. countdown--;
  3136. setTimeout("doAutoSubmit();", 1000);
  3137. }
  3138. // ]]></script>';
  3139. }
  3140. }
  3141. function template_xml_above()
  3142. {
  3143. global $upcontext;
  3144. echo '<', '?xml version="1.0" encoding="ISO-8859-1"?', '>
  3145. <smf>';
  3146. if (!empty($upcontext['get_data']))
  3147. foreach ($upcontext['get_data'] as $k => $v)
  3148. echo '
  3149. <get key="', $k, '">', $v, '</get>';
  3150. }
  3151. function template_xml_below()
  3152. {
  3153. global $upcontext;
  3154. echo '
  3155. </smf>';
  3156. }
  3157. function template_error_message()
  3158. {
  3159. global $upcontext;
  3160. echo '
  3161. <div class="error_message">
  3162. <div style="color: red;">
  3163. ', $upcontext['error_msg'], '
  3164. </div>
  3165. <br />
  3166. <a href="', $_SERVER['PHP_SELF'], '">Click here to try again.</a>
  3167. </div>';
  3168. }
  3169. function template_welcome_message()
  3170. {
  3171. global $upcontext, $modSettings, $upgradeurl, $disable_security, $settings, $txt;
  3172. echo '
  3173. <script type="text/javascript" src="http://www.simplemachines.org/smf/current-version.js?version=' . SMF_VERSION . '"></script>
  3174. <script type="text/javascript" src="', $settings['default_theme_url'], '/scripts/sha1.js"></script>
  3175. <h3>', sprintf($txt['upgrade_ready_proceed'], SMF_VERSION), '</h3>
  3176. <form action="', $upcontext['form_url'], '" method="post" name="upform" id="upform" ', empty($upcontext['disable_login_hashing']) ? ' onsubmit="hashLoginPassword(this, \'' . $upcontext['rid'] . '\', \'' . (!empty($upcontext['login_token']) ? $upcontext['login_token'] : '') . '\');"' : '', '>
  3177. <input type="hidden" name="', $upcontext['login_token_var'], '" value="', $upcontext['login_token'], '" />
  3178. <div id="version_warning" style="margin: 2ex; padding: 2ex; border: 2px dashed #a92174; color: black; background-color: #fbbbe2; display: none;">
  3179. <div style="float: left; width: 2ex; font-size: 2em; color: red;">!!</div>
  3180. <strong style="text-decoration: underline;">', $txt['upgrade_warning'], '</strong><br />
  3181. <div style="padding-left: 6ex;">
  3182. ', sprintf($txt['upgrade_warning_out_of_date'], SMF_VERSION), '
  3183. </div>
  3184. </div>';
  3185. $upcontext['chmod_in_form'] = true;
  3186. template_chmod();
  3187. // For large, pre 1.1 RC2 forums give them a warning about the possible impact of this upgrade!
  3188. if ($upcontext['is_large_forum'])
  3189. echo '
  3190. <div style="margin: 2ex; padding: 2ex; border: 2px dashed #cc3344; color: black; background-color: #ffe4e9;">
  3191. <div style="float: left; width: 2ex; font-size: 2em; color: red;">!!</div>
  3192. <strong style="text-decoration: underline;">', $txt['upgrade_warning'], '</strong><br />
  3193. <div style="padding-left: 6ex;">
  3194. ', $txt['upgrade_warning_lots_data'], '
  3195. </div>
  3196. </div>';
  3197. // A warning message?
  3198. if (!empty($upcontext['warning']))
  3199. echo '
  3200. <div style="margin: 2ex; padding: 2ex; border: 2px dashed #cc3344; color: black; background-color: #ffe4e9;">
  3201. <div style="float: left; width: 2ex; font-size: 2em; color: red;">!!</div>
  3202. <strong style="text-decoration: underline;">', $txt['upgrade_warning'], '</strong><br />
  3203. <div style="padding-left: 6ex;">
  3204. ', $upcontext['warning'], '
  3205. </div>
  3206. </div>';
  3207. // Paths are incorrect?
  3208. echo '
  3209. <div style="margin: 2ex; padding: 2ex; border: 2px dashed #804840; color: black; background-color: #fe5a44; ', (file_exists($settings['default_theme_dir'] . '/scripts/script.js') ? 'display: none;' : ''), '" id="js_script_missing_error">
  3210. <div style="float: left; width: 2ex; font-size: 2em; color: black;">!!</div>
  3211. <strong style="text-decoration: underline;">', $txt['upgrade_critical_error'], '</strong><br />
  3212. <div style="padding-left: 6ex;">
  3213. ', $txt['upgrade_error_script_js'], '
  3214. </div>
  3215. </div>';
  3216. // Is there someone already doing this?
  3217. if (!empty($upcontext['user']['id']) && (time() - $upcontext['started'] < 72600 || time() - $upcontext['updated'] < 3600))
  3218. {
  3219. $ago = time() - $upcontext['started'];
  3220. if ($ago < 60)
  3221. $ago = $ago . ' seconds';
  3222. elseif ($ago < 3600)
  3223. $ago = (int) ($ago / 60) . ' minutes';
  3224. else
  3225. $ago = (int) ($ago / 3600) . ' hours';
  3226. $active = time() - $upcontext['updated'];
  3227. if ($active < 60)
  3228. $updated = $active . ' seconds';
  3229. elseif ($active < 3600)
  3230. $updated = (int) ($active / 60) . ' minutes';
  3231. else
  3232. $updated = (int) ($active / 3600) . ' hours';
  3233. echo '
  3234. <div style="margin: 2ex; padding: 2ex; border: 2px dashed #cc3344; color: black; background-color: #ffe4e9;">
  3235. <div style="float: left; width: 2ex; font-size: 2em; color: red;">!!</div>
  3236. <strong style="text-decoration: underline;">', $txt['upgrade_warning'], '</strong><br />
  3237. <div style="padding-left: 6ex;">
  3238. &quot;', $upcontext['user']['name'], '&quot; has been running the upgrade script for the last ', $ago, ' - and was last active ', $updated, ' ago.';
  3239. if ($active < 600)
  3240. echo '
  3241. We recommend that you do not run this script unless you are sure that ', $upcontext['user']['name'], ' has completed their upgrade.';
  3242. if ($active > $upcontext['inactive_timeout'])
  3243. echo '
  3244. <br /><br />You can choose to either run the upgrade again from the beginning - or alternatively continue from the last step reached during the last upgrade.';
  3245. else
  3246. echo '
  3247. <br /><br />This upgrade script cannot be run until ', $upcontext['user']['name'], ' has been inactive for at least ', ($upcontext['inactive_timeout'] > 120 ? round($upcontext['inactive_timeout'] / 60, 1) . ' minutes!' : $upcontext['inactive_timeout'] . ' seconds!');
  3248. echo '
  3249. </div>
  3250. </div>';
  3251. }
  3252. echo '
  3253. <strong>Admin Login: ', $disable_security ? '(DISABLED)' : '', '</strong>
  3254. <h3>For security purposes please login with your admin account to proceed with the upgrade.</h3>
  3255. <table>
  3256. <tr valign="top">
  3257. <td><strong ', $disable_security ? 'style="color: gray;"' : '', '>Username:</strong></td>
  3258. <td>
  3259. <input type="text" name="user" value="', !empty($upcontext['username']) ? $upcontext['username'] : '', '" ', $disable_security ? 'disabled="disabled"' : '', ' class="input_text" />';
  3260. if (!empty($upcontext['username_incorrect']))
  3261. echo '
  3262. <div class="smalltext" style="color: red;">Username Incorrect</div>';
  3263. echo '
  3264. </td>
  3265. </tr>
  3266. <tr valign="top">
  3267. <td><strong ', $disable_security ? 'style="color: gray;"' : '', '>Password:</strong></td>
  3268. <td>
  3269. <input type="password" name="passwrd" value=""', $disable_security ? ' disabled="disabled"' : '', ' class="input_password" />
  3270. <input type="hidden" name="hash_passwrd" value="" />';
  3271. if (!empty($upcontext['password_failed']))
  3272. echo '
  3273. <div class="smalltext" style="color: red;">Password Incorrect</div>';
  3274. echo '
  3275. </td>
  3276. </tr>';
  3277. // Can they continue?
  3278. if (!empty($upcontext['user']['id']) && time() - $upcontext['user']['updated'] >= $upcontext['inactive_timeout'] && $upcontext['user']['step'] > 1)
  3279. {
  3280. echo '
  3281. <tr>
  3282. <td colspan="2">
  3283. <label for="cont"><input type="checkbox" id="cont" name="cont" checked="checked" class="input_check" />Continue from step reached during last execution of upgrade script.</label>
  3284. </td>
  3285. </tr>';
  3286. }
  3287. echo '
  3288. </table><br />
  3289. <span class="smalltext">
  3290. <strong>Note:</strong> If necessary the above security check can be bypassed for users who may administrate a server but not have admin rights on the forum. In order to bypass the above check simply open &quot;upgrade.php&quot; in a text editor and replace &quot;$disable_security = false;&quot; with &quot;$disable_security = true;&quot; and refresh this page.
  3291. </span>
  3292. <input type="hidden" name="login_attempt" id="login_attempt" value="1" />
  3293. <input type="hidden" name="js_works" id="js_works" value="0" />';
  3294. // Say we want the continue button!
  3295. $upcontext['continue'] = !empty($upcontext['user']['id']) && time() - $upcontext['user']['updated'] < $upcontext['inactive_timeout'] ? 2 : 1;
  3296. // This defines whether javascript is going to work elsewhere :D
  3297. echo '
  3298. <script type="text/javascript"><!-- // --><![CDATA[
  3299. if (\'XMLHttpRequest\' in window && document.getElementById(\'js_works\'))
  3300. document.getElementById(\'js_works\').value = 1;
  3301. // Latest version?
  3302. function smfCurrentVersion()
  3303. {
  3304. var smfVer, yourVer;
  3305. if (!(\'smfVersion\' in window))
  3306. return;
  3307. window.smfVersion = window.smfVersion.replace(/SMF\s?/g, \'\');
  3308. smfVer = document.getElementById(\'smfVersion\');
  3309. yourVer = document.getElementById(\'yourVersion\');
  3310. setInnerHTML(smfVer, window.smfVersion);
  3311. var currentVersion = getInnerHTML(yourVer);
  3312. if (currentVersion < window.smfVersion)
  3313. document.getElementById(\'version_warning\').style.display = \'\';
  3314. }
  3315. addLoadEvent(smfCurrentVersion);
  3316. // This checks that the script file even exists!
  3317. if (typeof(smfSelectText) == \'undefined\')
  3318. document.getElementById(\'js_script_missing_error\').style.display = \'\';
  3319. // ]]></script>';
  3320. }
  3321. function template_upgrade_options()
  3322. {
  3323. global $upcontext, $modSettings, $upgradeurl, $disable_security, $settings, $boarddir, $db_prefix, $mmessage, $mtitle, $db_type;
  3324. echo '
  3325. <h3>Before the upgrade gets underway please review the options below - and hit continue when you\'re ready to begin.</h3>
  3326. <form action="', $upcontext['form_url'], '" method="post" name="upform" id="upform">';
  3327. // Warning message?
  3328. if (!empty($upcontext['upgrade_options_warning']))
  3329. echo '
  3330. <div style="margin: 1ex; padding: 1ex; border: 1px dashed #cc3344; color: black; background-color: #ffe4e9;">
  3331. <div style="float: left; width: 2ex; font-size: 2em; color: red;">!!</div>
  3332. <strong style="text-decoration: underline;">Warning!</strong><br />
  3333. <div style="padding-left: 4ex;">
  3334. ', $upcontext['upgrade_options_warning'], '
  3335. </div>
  3336. </div>';
  3337. echo '
  3338. <table cellpadding="1" cellspacing="0">
  3339. <tr valign="top">
  3340. <td width="2%">
  3341. <input type="checkbox" name="backup" id="backup" value="1"', $db_type != 'mysql' && $db_type != 'mysqli' && $db_type != 'postgresql' ? ' disabled="disabled"' : '', ' class="input_check" />
  3342. </td>
  3343. <td width="100%">
  3344. <label for="backup">Backup tables in your database with the prefix &quot;backup_' . $db_prefix . '&quot;.</label>', isset($modSettings['smfVersion']) ? '' : ' (recommended!)', '
  3345. </td>
  3346. </tr>
  3347. <tr valign="top">
  3348. <td width="2%">
  3349. <input type="checkbox" name="maint" id="maint" value="1" checked="checked" class="input_check" />
  3350. </td>
  3351. <td width="100%">
  3352. <label for="maint">Put the forum into maintenance mode during upgrade.</label> <span class="smalltext">(<a href="#" onclick="document.getElementById(\'mainmess\').style.display = document.getElementById(\'mainmess\').style.display == \'\' ? \'none\' : \'\'">Customize</a>)</span>
  3353. <div id="mainmess" style="display: none;">
  3354. <strong class="smalltext">Maintenance Title: </strong><br />
  3355. <input type="text" name="maintitle" size="30" value="', htmlspecialchars($mtitle), '" class="input_text" /><br />
  3356. <strong class="smalltext">Maintenance Message: </strong><br />
  3357. <textarea name="mainmessage" rows="3" cols="50">', htmlspecialchars($mmessage), '</textarea>
  3358. </div>
  3359. </td>
  3360. </tr>';
  3361. // Offer mysql users to switch to mysqli
  3362. if ($db_type == 'mysql' && function_exists('mysqli_query'))
  3363. echo '
  3364. <tr valign="top">
  3365. <td width="2%">
  3366. <input type="checkbox" name="convertMysql" id="convertMysql" value="1" checked="checked" class="input_check" />
  3367. </td>
  3368. <td width="100%">
  3369. <label for="convertMysql">Use MySQLi functionality (MySQL compatible).</span>
  3370. <strong class="smalltext"><a href="http://wiki.simplemachines.org/smf/Upgrading-MySQLi-Functionality" target="_blank">More information about MySQLi</a></strong><br />
  3371. </td>
  3372. </tr>';
  3373. echo '
  3374. <tr valign="top">
  3375. <td width="2%">
  3376. <input type="checkbox" name="debug" id="debug" value="1" class="input_check" />
  3377. </td>
  3378. <td width="100%">
  3379. <label for="debug">Output extra debugging information</label>
  3380. </td>
  3381. </tr>
  3382. <tr valign="top">
  3383. <td width="2%">
  3384. <input type="checkbox" name="empty_error" id="empty_error" value="1" class="input_check" />
  3385. </td>
  3386. <td width="100%">
  3387. <label for="empty_error">Empty error log before upgrading</label>
  3388. </td>
  3389. </tr>
  3390. <tr valign="top">
  3391. <td width="2%">
  3392. <input type="checkbox" name="stat" id="stat" value="1"', empty($modSettings['allow_sm_stats']) ? '' : ' checked="checked"', ' class="input_check" />
  3393. </td>
  3394. <td width="100%">
  3395. <label for="stat">
  3396. Allow Simple Machines to Collect Basic Stats Monthly.<br />
  3397. <span class="smalltext">If enabled, this will allow Simple Machines to visit your site once a month to collect basic statistics. This will help us make decisions as to which configurations to optimise the software for. For more information please visit our <a href="http://www.simplemachines.org/about/stats.php" target="_blank">info page</a>.</span>
  3398. </label>
  3399. </td>
  3400. </tr>
  3401. </table>
  3402. <input type="hidden" name="upcont" value="1" />';
  3403. // We need a normal continue button here!
  3404. $upcontext['continue'] = 1;
  3405. }
  3406. // Template for the database backup tool/
  3407. function template_backup_database()
  3408. {
  3409. global $upcontext, $modSettings, $upgradeurl, $disable_security, $settings, $support_js, $is_debug;
  3410. echo '
  3411. <h3>Please wait while a backup is created. For large forums this may take some time!</h3>';
  3412. echo '
  3413. <form action="', $upcontext['form_url'], '" name="upform" id="upform" method="post">
  3414. <input type="hidden" name="backup_done" id="backup_done" value="0" />
  3415. <strong>Completed <span id="tab_done">', $upcontext['cur_table_num'], '</span> out of ', $upcontext['table_count'], ' tables.</strong>
  3416. <span id="debuginfo"></span>';
  3417. // Dont any tables so far?
  3418. if (!empty($upcontext['previous_tables']))
  3419. foreach ($upcontext['previous_tables'] as $table)
  3420. echo '
  3421. <br />Completed Table: &quot;', $table, '&quot;.';
  3422. echo '
  3423. <h3 id="current_tab_div">Current Table: &quot;<span id="current_table">', $upcontext['cur_table_name'], '</span>&quot;</h3>
  3424. <br /><span id="commess" style="font-weight: bold; display: ', $upcontext['cur_table_num'] == $upcontext['table_count'] ? 'inline' : 'none', ';">Backup Complete! Click Continue to Proceed.</span>';
  3425. // Continue please!
  3426. $upcontext['continue'] = $support_js ? 2 : 1;
  3427. // If javascript allows we want to do this using XML.
  3428. if ($support_js)
  3429. {
  3430. echo '
  3431. <script type="text/javascript"><!-- // --><![CDATA[
  3432. var lastTable = ', $upcontext['cur_table_num'], ';
  3433. function getNextTables()
  3434. {
  3435. getXMLDocument(\'', $upcontext['form_url'], '&xml&substep=\' + lastTable, onBackupUpdate);
  3436. }
  3437. // Got an update!
  3438. function onBackupUpdate(oXMLDoc)
  3439. {
  3440. var sCurrentTableName = "";
  3441. var iTableNum = 0;
  3442. var sCompletedTableName = getInnerHTML(document.getElementById(\'current_table\'));
  3443. for (var i = 0; i < oXMLDoc.getElementsByTagName("table")[0].childNodes.length; i++)
  3444. sCurrentTableName += oXMLDoc.getElementsByTagName("table")[0].childNodes[i].nodeValue;
  3445. iTableNum = oXMLDoc.getElementsByTagName("table")[0].getAttribute("num");
  3446. // Update the page.
  3447. setInnerHTML(document.getElementById(\'tab_done\'), iTableNum);
  3448. setInnerHTML(document.getElementById(\'current_table\'), sCurrentTableName);
  3449. lastTable = iTableNum;
  3450. updateStepProgress(iTableNum, ', $upcontext['table_count'], ', ', $upcontext['step_weight'] * ((100 - $upcontext['step_progress']) / 100), ');';
  3451. // If debug flood the screen.
  3452. if ($is_debug)
  3453. echo '
  3454. setOuterHTML(document.getElementById(\'debuginfo\'), \'<br />Completed Table: &quot;\' + sCompletedTableName + \'&quot;.<span id="debuginfo"><\' + \'/span>\');';
  3455. echo '
  3456. // Get the next update...
  3457. if (iTableNum == ', $upcontext['table_count'], ')
  3458. {
  3459. document.getElementById(\'commess\').style.display = "";
  3460. document.getElementById(\'current_tab_div\').style.display = "none";
  3461. document.getElementById(\'contbutt\').disabled = 0;
  3462. document.getElementById(\'backup_done\').value = 1;
  3463. }
  3464. else
  3465. getNextTables();
  3466. }
  3467. getNextTables();
  3468. // ]]></script>';
  3469. }
  3470. }
  3471. function template_backup_xml()
  3472. {
  3473. global $upcontext, $settings, $options, $txt;
  3474. echo '
  3475. <table num="', $upcontext['cur_table_num'], '">', $upcontext['cur_table_name'], '</table>';
  3476. }
  3477. // Here is the actual "make the changes" template!
  3478. function template_database_changes()
  3479. {
  3480. global $upcontext, $modSettings, $upgradeurl, $disable_security, $settings, $support_js, $is_debug, $timeLimitThreshold;
  3481. echo '
  3482. <h3>Executing database changes</h3>
  3483. <h4 style="font-style: italic;">Please be patient - this may take some time on large forums. The time elapsed increments from the server to show progress is being made!</h4>';
  3484. echo '
  3485. <form action="', $upcontext['form_url'], '&amp;filecount=', $upcontext['file_count'], '" name="upform" id="upform" method="post">
  3486. <input type="hidden" name="database_done" id="database_done" value="0" />';
  3487. // No javascript looks rubbish!
  3488. if (!$support_js)
  3489. {
  3490. foreach ($upcontext['actioned_items'] as $num => $item)
  3491. {
  3492. if ($num != 0)
  3493. echo ' Successful!';
  3494. echo '<br />' . $item;
  3495. }
  3496. if (!empty($upcontext['changes_complete']))
  3497. echo ' Successful!<br /><br /><span id="commess" style="font-weight: bold;">Database Updates Complete! Click Continue to Proceed.</span><br />';
  3498. }
  3499. else
  3500. {
  3501. // Tell them how many files we have in total.
  3502. if ($upcontext['file_count'] > 1)
  3503. echo '
  3504. <strong id="info1">Executing upgrade script <span id="file_done">', $upcontext['cur_file_num'], '</span> of ', $upcontext['file_count'], '.</strong>';
  3505. echo '
  3506. <h3 id="info2"><strong>Executing:</strong> &quot;<span id="cur_item_name">', $upcontext['current_item_name'], '</span>&quot; (<span id="item_num">', $upcontext['current_item_num'], '</span> of <span id="total_items"><span id="item_count">', $upcontext['total_items'], '</span>', $upcontext['file_count'] > 1 ? ' - of this script' : '', ')</span></h3>
  3507. <br /><span id="commess" style="font-weight: bold; display: ', !empty($upcontext['changes_complete']) || $upcontext['current_debug_item_num'] == $upcontext['debug_items'] ? 'inline' : 'none', ';">Database Updates Complete! Click Continue to Proceed.</span>';
  3508. if ($is_debug)
  3509. {
  3510. echo '
  3511. <div id="debug_section" style="height: 200px; overflow: auto;">
  3512. <span id="debuginfo"></span>
  3513. </div>';
  3514. }
  3515. }
  3516. // Place for the XML error message.
  3517. echo '
  3518. <div id="error_block" style="margin: 2ex; padding: 2ex; border: 2px dashed #cc3344; color: black; background-color: #ffe4e9; display: ', empty($upcontext['error_message']) ? 'none' : '', ';">
  3519. <div style="float: left; width: 2ex; font-size: 2em; color: red;">!!</div>
  3520. <strong style="text-decoration: underline;">Error!</strong><br />
  3521. <div style="padding-left: 6ex;" id="error_message">', isset($upcontext['error_message']) ? $upcontext['error_message'] : 'Unknown Error!', '</div>
  3522. </div>';
  3523. // We want to continue at some point!
  3524. $upcontext['continue'] = $support_js ? 2 : 1;
  3525. // If javascript allows we want to do this using XML.
  3526. if ($support_js)
  3527. {
  3528. echo '
  3529. <script type="text/javascript"><!-- // --><![CDATA[
  3530. var lastItem = ', $upcontext['current_debug_item_num'], ';
  3531. var sLastString = "', strtr($upcontext['current_debug_item_name'], array('"' => '&quot;')), '";
  3532. var iLastSubStepProgress = -1;
  3533. var curFile = ', $upcontext['cur_file_num'], ';
  3534. var totalItems = 0;
  3535. var prevFile = 0;
  3536. var retryCount = 0;
  3537. var testvar = 0;
  3538. var timeOutID = 0;
  3539. var getData = "";
  3540. var debugItems = ', $upcontext['debug_items'], ';
  3541. function getNextItem()
  3542. {
  3543. // We want to track this...
  3544. if (timeOutID)
  3545. clearTimeout(timeOutID);
  3546. timeOutID = window.setTimeout("retTimeout()", ', (10 * $timeLimitThreshold), '000);
  3547. getXMLDocument(\'', $upcontext['form_url'], '&xml&filecount=', $upcontext['file_count'], '&substep=\' + lastItem + getData, onItemUpdate);
  3548. }
  3549. // Got an update!
  3550. function onItemUpdate(oXMLDoc)
  3551. {
  3552. var sItemName = "";
  3553. var sDebugName = "";
  3554. var iItemNum = 0;
  3555. var iSubStepProgress = -1;
  3556. var iDebugNum = 0;
  3557. var bIsComplete = 0;
  3558. getData = "";
  3559. // We\'ve got something - so reset the timeout!
  3560. if (timeOutID)
  3561. clearTimeout(timeOutID);
  3562. // Assume no error at this time...
  3563. document.getElementById("error_block").style.display = "none";
  3564. // Are we getting some duff info?
  3565. if (!oXMLDoc.getElementsByTagName("item")[0])
  3566. {
  3567. // Too many errors?
  3568. if (retryCount > 15)
  3569. {
  3570. document.getElementById("error_block").style.display = "";
  3571. setInnerHTML(document.getElementById("error_message"), "Error retrieving information on step: " + (sDebugName == "" ? sLastString : sDebugName));';
  3572. if ($is_debug)
  3573. echo '
  3574. setOuterHTML(document.getElementById(\'debuginfo\'), \'<span style="color: red;">failed<\' + \'/span><span id="debuginfo"><\' + \'/span>\');';
  3575. echo '
  3576. }
  3577. else
  3578. {
  3579. retryCount++;
  3580. getNextItem();
  3581. }
  3582. return false;
  3583. }
  3584. // Never allow loops.
  3585. if (curFile == prevFile)
  3586. {
  3587. retryCount++;
  3588. if (retryCount > 10)
  3589. {
  3590. document.getElementById("error_block").style.display = "";
  3591. setInnerHTML(document.getElementById("error_message"), "Upgrade script appears to be going into a loop - step: " + sDebugName);';
  3592. if ($is_debug)
  3593. echo '
  3594. setOuterHTML(document.getElementById(\'debuginfo\'), \'<span style="color: red;">failed<\' + \'/span><span id="debuginfo"><\' + \'/span>\');';
  3595. echo '
  3596. }
  3597. }
  3598. retryCount = 0;
  3599. for (var i = 0; i < oXMLDoc.getElementsByTagName("item")[0].childNodes.length; i++)
  3600. sItemName += oXMLDoc.getElementsByTagName("item")[0].childNodes[i].nodeValue;
  3601. for (var i = 0; i < oXMLDoc.getElementsByTagName("debug")[0].childNodes.length; i++)
  3602. sDebugName += oXMLDoc.getElementsByTagName("debug")[0].childNodes[i].nodeValue;
  3603. for (var i = 0; i < oXMLDoc.getElementsByTagName("get").length; i++)
  3604. {
  3605. getData += "&" + oXMLDoc.getElementsByTagName("get")[i].getAttribute("key") + "=";
  3606. for (var j = 0; j < oXMLDoc.getElementsByTagName("get")[i].childNodes.length; j++)
  3607. {
  3608. getData += oXMLDoc.getElementsByTagName("get")[i].childNodes[j].nodeValue;
  3609. }
  3610. }
  3611. iItemNum = oXMLDoc.getElementsByTagName("item")[0].getAttribute("num");
  3612. iDebugNum = parseInt(oXMLDoc.getElementsByTagName("debug")[0].getAttribute("num"));
  3613. bIsComplete = parseInt(oXMLDoc.getElementsByTagName("debug")[0].getAttribute("complete"));
  3614. iSubStepProgress = parseFloat(oXMLDoc.getElementsByTagName("debug")[0].getAttribute("percent"));
  3615. sLastString = sDebugName + " (Item: " + iDebugNum + ")";
  3616. curFile = parseInt(oXMLDoc.getElementsByTagName("file")[0].getAttribute("num"));
  3617. debugItems = parseInt(oXMLDoc.getElementsByTagName("file")[0].getAttribute("debug_items"));
  3618. totalItems = parseInt(oXMLDoc.getElementsByTagName("file")[0].getAttribute("items"));
  3619. // If we have an error we haven\'t completed!
  3620. if (oXMLDoc.getElementsByTagName("error")[0] && bIsComplete)
  3621. iDebugNum = lastItem;
  3622. // Do we have the additional progress bar?
  3623. if (iSubStepProgress != -1)
  3624. {
  3625. document.getElementById("substep_bar_div").style.display = "";
  3626. document.getElementById("substep_bar_div2").style.display = "";
  3627. document.getElementById("substep_progress").style.width = iSubStepProgress + "%";
  3628. setInnerHTML(document.getElementById("substep_text"), iSubStepProgress + "%");
  3629. setInnerHTML(document.getElementById("substep_bar_div"), sDebugName.replace(/\./g, "") + ":");
  3630. }
  3631. else
  3632. {
  3633. document.getElementById("substep_bar_div").style.display = "none";
  3634. document.getElementById("substep_bar_div2").style.display = "none";
  3635. }
  3636. // Move onto the next item?
  3637. if (bIsComplete)
  3638. lastItem = iDebugNum;
  3639. else
  3640. lastItem = iDebugNum - 1;
  3641. // Are we finished?
  3642. if (bIsComplete && iDebugNum == -1 && curFile >= ', $upcontext['file_count'], ')
  3643. {';
  3644. if ($is_debug)
  3645. echo '
  3646. document.getElementById(\'debug_section\').style.display = "none";';
  3647. echo '
  3648. document.getElementById(\'commess\').style.display = "";
  3649. document.getElementById(\'contbutt\').disabled = 0;
  3650. document.getElementById(\'database_done\').value = 1;';
  3651. if ($upcontext['file_count'] > 1)
  3652. echo '
  3653. document.getElementById(\'info1\').style.display = "none";';
  3654. echo '
  3655. document.getElementById(\'info2\').style.display = "none";
  3656. updateStepProgress(100, 100, ', $upcontext['step_weight'] * ((100 - $upcontext['step_progress']) / 100), ');
  3657. return true;
  3658. }
  3659. // Was it the last step in the file?
  3660. else if (bIsComplete && iDebugNum == -1)
  3661. {
  3662. lastItem = 0;
  3663. prevFile = curFile;';
  3664. if ($is_debug)
  3665. echo '
  3666. setOuterHTML(document.getElementById(\'debuginfo\'), \'Moving to next script file...done<br /><span id="debuginfo"><\' + \'/span>\');';
  3667. echo '
  3668. getNextItem();
  3669. return true;
  3670. }';
  3671. // If debug scroll the screen.
  3672. if ($is_debug)
  3673. echo '
  3674. if (iLastSubStepProgress == -1)
  3675. {
  3676. // Give it consistent dots.
  3677. dots = sDebugName.match(/\./g);
  3678. numDots = dots ? dots.length : 0;
  3679. for (var i = numDots; i < 3; i++)
  3680. sDebugName += ".";
  3681. setOuterHTML(document.getElementById(\'debuginfo\'), sDebugName + \'<span id="debuginfo"><\' + \'/span>\');
  3682. }
  3683. iLastSubStepProgress = iSubStepProgress;
  3684. if (bIsComplete)
  3685. setOuterHTML(document.getElementById(\'debuginfo\'), \'done<br /><span id="debuginfo"><\' + \'/span>\');
  3686. else
  3687. setOuterHTML(document.getElementById(\'debuginfo\'), \'...<span id="debuginfo"><\' + \'/span>\');
  3688. if (document.getElementById(\'debug_section\').scrollHeight)
  3689. document.getElementById(\'debug_section\').scrollTop = document.getElementById(\'debug_section\').scrollHeight';
  3690. echo '
  3691. // Update the page.
  3692. setInnerHTML(document.getElementById(\'item_num\'), iItemNum);
  3693. setInnerHTML(document.getElementById(\'cur_item_name\'), sItemName);';
  3694. if ($upcontext['file_count'] > 1)
  3695. {
  3696. echo '
  3697. setInnerHTML(document.getElementById(\'file_done\'), curFile);
  3698. setInnerHTML(document.getElementById(\'item_count\'), totalItems);';
  3699. }
  3700. echo '
  3701. // Is there an error?
  3702. if (oXMLDoc.getElementsByTagName("error")[0])
  3703. {
  3704. var sErrorMsg = "";
  3705. for (var i = 0; i < oXMLDoc.getElementsByTagName("error")[0].childNodes.length; i++)
  3706. sErrorMsg += oXMLDoc.getElementsByTagName("error")[0].childNodes[i].nodeValue;
  3707. document.getElementById("error_block").style.display = "";
  3708. setInnerHTML(document.getElementById("error_message"), sErrorMsg);
  3709. return false;
  3710. }
  3711. // Get the progress bar right.
  3712. barTotal = debugItems * ', $upcontext['file_count'], ';
  3713. barDone = (debugItems * (curFile - 1)) + lastItem;
  3714. updateStepProgress(barDone, barTotal, ', $upcontext['step_weight'] * ((100 - $upcontext['step_progress']) / 100), ');
  3715. // Finally - update the time here as it shows the server is responding!
  3716. curTime = new Date();
  3717. iElapsed = (curTime.getTime() / 1000 - ', $upcontext['started'], ');
  3718. mins = parseInt(iElapsed / 60);
  3719. secs = parseInt(iElapsed - mins * 60);
  3720. setInnerHTML(document.getElementById("mins_elapsed"), mins);
  3721. setInnerHTML(document.getElementById("secs_elapsed"), secs);
  3722. getNextItem();
  3723. return true;
  3724. }
  3725. // What if we timeout?!
  3726. function retTimeout(attemptAgain)
  3727. {
  3728. // Oh noes...
  3729. if (!attemptAgain)
  3730. {
  3731. document.getElementById("error_block").style.display = "";
  3732. setInnerHTML(document.getElementById("error_message"), "Server has not responded for ', ($timeLimitThreshold * 10), ' seconds. It may be worth waiting a little longer or otherwise please click <a href=\"#\" onclick=\"retTimeout(true); return false;\">here<" + "/a> to try this step again");
  3733. }
  3734. else
  3735. {
  3736. document.getElementById("error_block").style.display = "none";
  3737. getNextItem();
  3738. }
  3739. }';
  3740. // Start things off assuming we've not errored.
  3741. if (empty($upcontext['error_message']))
  3742. echo '
  3743. getNextItem();';
  3744. echo '
  3745. // ]]></script>';
  3746. }
  3747. return;
  3748. }
  3749. function template_database_xml()
  3750. {
  3751. global $upcontext, $settings, $options, $txt;
  3752. echo '
  3753. <file num="', $upcontext['cur_file_num'], '" items="', $upcontext['total_items'], '" debug_items="', $upcontext['debug_items'], '">', $upcontext['cur_file_name'], '</file>
  3754. <item num="', $upcontext['current_item_num'], '">', $upcontext['current_item_name'], '</item>
  3755. <debug num="', $upcontext['current_debug_item_num'], '" percent="', isset($upcontext['substep_progress']) ? $upcontext['substep_progress'] : '-1', '" complete="', empty($upcontext['completed_step']) ? 0 : 1, '">', $upcontext['current_debug_item_name'], '</debug>';
  3756. if (!empty($upcontext['error_message']))
  3757. echo '
  3758. <error>', $upcontext['error_message'], '</error>';
  3759. }
  3760. function template_clean_mods()
  3761. {
  3762. global $upcontext, $modSettings, $upgradeurl, $disable_security, $settings, $boarddir, $db_prefix, $boardurl;
  3763. $upcontext['chmod_in_form'] = true;
  3764. echo '
  3765. <h3>SMF has detected some packages which were installed but not fully removed prior to upgrade. We recommend you remove the following mods and reinstall upon completion of the upgrade.</h3>
  3766. <form action="', $upcontext['form_url'], '&amp;ssi=1" name="upform" id="upform" method="post">';
  3767. // In case it's required.
  3768. template_chmod();
  3769. echo '
  3770. <table width="90%" align="center" cellspacing="1" cellpadding="2" style="background-color: black;">
  3771. <tr style="background-color: #eeeeee;">
  3772. <td width="40%"><strong>Modification Name</strong></td>
  3773. <td width="10%" align="center"><strong>Version</strong></td>
  3774. <td width="15%"><strong>Files Affected</strong></td>
  3775. <td width="20%"><strong>Status</strong></td>
  3776. <td width="5%" align="center"><strong>Fix?</strong></td>
  3777. </tr>';
  3778. foreach ($upcontext['packages'] as $package)
  3779. {
  3780. echo '
  3781. <tr style="background-color: #cccccc;">
  3782. <td width="40%">', $package['name'], '</td>
  3783. <td width="10%">', $package['version'], '</td>
  3784. <td width="15%">', $package['file_count'], ' <span class="smalltext">[<a href="#" onclick="alert(\'The following files are affected by this modification:\\n\\n', strtr(implode('<br />', $package['files']), array('\\' => '\\\\', '<br />' => '\\n')), '\'); return false;">details</a>]</td>
  3785. <td width="20%"><span style="font-weight: bold; color: ', $package['color'], '">', $package['status'], '</span></td>
  3786. <td width="5%" align="center">
  3787. <input type="hidden" name="remove[', $package['id'], ']" value="0" />
  3788. <input type="checkbox" name="remove[', $package['id'], ']"', $package['color'] == 'green' ? ' disabled="disabled"' : '', ' class="input_check" />
  3789. </td>
  3790. </tr>';
  3791. }
  3792. echo '
  3793. </table>
  3794. <input type="hidden" name="cleandone" value="1" />';
  3795. // Files to make writable?
  3796. if (!empty($upcontext['writable_files']))
  3797. echo '
  3798. <input type="hidden" name="writable_files" value="', base64_encode(serialize($upcontext['writable_files'])), '" />';
  3799. // We'll want a continue button...
  3800. if (empty($upcontext['chmod']['files']))
  3801. $upcontext['continue'] = 1;
  3802. }
  3803. // Finished with the mods - let them know what we've done.
  3804. function template_cleanup_done()
  3805. {
  3806. global $upcontext, $modSettings, $upgradeurl, $disable_security, $settings, $boarddir, $db_prefix, $boardurl;
  3807. echo '
  3808. <h3>SMF has attempted to fix and reinstall mods as required. We recommend you visit the package manager upon completing upgrade to check the status of your modifications.</h3>
  3809. <form action="', $upcontext['form_url'], '&amp;ssi=1" name="upform" id="upform" method="post">
  3810. <table width="90%" align="center" cellspacing="1" cellpadding="2" style="background-color: black;">
  3811. <tr style="background-color: #eeeeee;">
  3812. <td width="100%"><strong>Actions Completed:</strong></td>
  3813. </tr>';
  3814. foreach ($upcontext['packages'] as $package)
  3815. {
  3816. echo '
  3817. <tr style="background-color: #cccccc;">
  3818. <td>', $package['name'], '... <span style="font-weight: bold; color: ', $package['color'], ';">', $package['result'], '</span></td>
  3819. </tr>';
  3820. }
  3821. echo '
  3822. </table>
  3823. <input type="hidden" name="cleandone2" value="1" />';
  3824. // We'll want a continue button...
  3825. $upcontext['continue'] = 1;
  3826. }
  3827. // Do they want to upgrade their templates?
  3828. function template_upgrade_templates()
  3829. {
  3830. global $upcontext, $modSettings, $upgradeurl, $disable_security, $settings, $boarddir, $db_prefix, $boardurl;
  3831. echo '
  3832. <h3>There have been numerous language and template changes since the previous version of SMF. On this step the upgrader can attempt to automatically make these changes in your templates to save you from doing so manually.</h3>
  3833. <form action="', $upcontext['form_url'], '&amp;ssi=1', $upcontext['is_test'] ? '' : ';forreal=1', '" name="upform" id="upform" method="post">';
  3834. // Any files need to be writable?
  3835. $upcontext['chmod_in_form'] = true;
  3836. template_chmod();
  3837. // Language/Template files need an update?
  3838. if ($upcontext['temp_progress'] == 0 && !$upcontext['is_test'] && (!empty($upcontext['languages']) || !empty($upcontext['themes'])))
  3839. {
  3840. echo '
  3841. The following template files will be updated to ensure they are compatible with this version of SMF. Note that this can only fix a limited number of compatibility issues and in general you should seek out the latest version of these themes/language files.
  3842. <table width="90%" align="center" cellspacing="1" cellpadding="2" style="background-color: black;">
  3843. <tr style="background-color: #eeeeee;">
  3844. <td width="80%"><strong>Area</strong></td>
  3845. <td width="20%" align="center"><strong>Changes Required</strong></td>
  3846. </tr>';
  3847. foreach ($upcontext['languages'] as $language)
  3848. {
  3849. echo '
  3850. <tr style="background-color: #cccccc;">
  3851. <td width="80%">
  3852. &quot;', $language['name'], '&quot; Language Pack
  3853. <div class="smalltext">(';
  3854. foreach ($language['files'] as $k => $file)
  3855. echo $file['name'], $k + 1 != count($language['files']) ? ', ' : ')';
  3856. echo '
  3857. </div>
  3858. </td>
  3859. <td width="20%" align="center">', $language['edit_count'] == 0 ? 1 : $language['edit_count'], '</td>
  3860. </tr>';
  3861. }
  3862. foreach ($upcontext['themes'] as $theme)
  3863. {
  3864. echo '
  3865. <tr style="background-color: #CCCCCC;">
  3866. <td width="80%">
  3867. &quot;', $theme['name'], '&quot; Theme
  3868. <div class="smalltext">(';
  3869. foreach ($theme['files'] as $k => $file)
  3870. echo $file['name'], $k + 1 != count($theme['files']) ? ', ' : ')';
  3871. echo '
  3872. </div>
  3873. </td>
  3874. <td width="20%" align="center">', $theme['edit_count'] == 0 ? 1 : $theme['edit_count'], '</td>
  3875. </tr>';
  3876. }
  3877. echo '
  3878. </table>';
  3879. }
  3880. else
  3881. {
  3882. $langFiles = 0;
  3883. $themeFiles = 0;
  3884. if (!empty($upcontext['languages']))
  3885. foreach ($upcontext['languages'] as $lang)
  3886. $langFiles += count($lang['files']);
  3887. if (!empty($upcontext['themes']))
  3888. foreach ($upcontext['themes'] as $theme)
  3889. $themeFiles += count($theme['files']);
  3890. echo sprintf('Found <strong>%d</strong> language files and <strong>%d</strong> templates requiring an update so far.', $langFiles, $themeFiles) . '<br />';
  3891. // What we're currently doing?
  3892. if (!empty($upcontext['current_message']))
  3893. echo '
  3894. ', $upcontext['current_message'];
  3895. }
  3896. echo '
  3897. <input type="hidden" name="uptempdone" value="1" />';
  3898. if (!empty($upcontext['languages']))
  3899. echo '
  3900. <input type="hidden" name="languages" value="', base64_encode(serialize($upcontext['languages'])), '" />';
  3901. if (!empty($upcontext['themes']))
  3902. echo '
  3903. <input type="hidden" name="themes" value="', base64_encode(serialize($upcontext['themes'])), '" />';
  3904. if (!empty($upcontext['writable_files']))
  3905. echo '
  3906. <input type="hidden" name="writable_files" value="', base64_encode(serialize($upcontext['writable_files'])), '" />';
  3907. // Offer them the option to upgrade from YaBB SE?
  3908. if (!empty($upcontext['can_upgrade_yabbse']))
  3909. echo '
  3910. <br /><label for="conv"><input type="checkbox" name="conv" id="conv" value="1" class="input_check" /> Convert the existing YaBB SE template and set it as default.</label><br />';
  3911. // We'll want a continue button... assuming chmod is OK (Otherwise let them use connect!)
  3912. if (empty($upcontext['chmod']['files']) || $upcontext['is_test'])
  3913. $upcontext['continue'] = 1;
  3914. }
  3915. function template_upgrade_complete()
  3916. {
  3917. global $upcontext, $modSettings, $upgradeurl, $disable_security, $settings, $boarddir, $db_prefix, $boardurl;
  3918. echo '
  3919. <h3>That wasn\'t so hard, was it? Now you are ready to use <a href="', $boardurl, '/index.php">your installation of SMF</a>. Hope you like it!</h3>
  3920. <form action="', $boardurl, '/index.php">';
  3921. if (!empty($upcontext['can_delete_script']))
  3922. echo '
  3923. <label for="delete_self"><input type="checkbox" id="delete_self" onclick="doTheDelete(this);" class="input_check" /> Delete this upgrade.php and its data files now.</label> <em>(doesn\'t work on all servers.)</em>
  3924. <script type="text/javascript"><!-- // --><![CDATA[
  3925. function doTheDelete(theCheck)
  3926. {
  3927. var theImage = document.getElementById ? document.getElementById("delete_upgrader") : document.all.delete_upgrader;
  3928. theImage.src = "', $upgradeurl, '?delete=1&ts_" + (new Date().getTime());
  3929. theCheck.disabled = true;
  3930. }
  3931. // ]]></script>
  3932. <img src="', $settings['default_theme_url'], '/images/blank.png" alt="" id="delete_upgrader" /><br />';
  3933. echo '<br />
  3934. If you had any problems with this upgrade, or have any problems using SMF, please don\'t hesitate to <a href="http://www.simplemachines.org/community/index.php">look to us for assistance</a>.<br />
  3935. <br />
  3936. Best of luck,<br />
  3937. Simple Machines';
  3938. }
  3939. ?>