upgrade.php 154 KB

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