Subs-Package.php 91 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006
  1. <?php
  2. /**
  3. * This file's central purpose of existence is that of making the package
  4. * manager work nicely. It contains functions for handling tar.gz and zip
  5. * files, as well as a simple xml parser to handle the xml package stuff.
  6. * Not to mention a few functions to make file handling easier.
  7. *
  8. * Simple Machines Forum (SMF)
  9. *
  10. * @package SMF
  11. * @author Simple Machines http://www.simplemachines.org
  12. * @copyright 2011 Simple Machines
  13. * @license http://www.simplemachines.org/about/smf/license.php BSD
  14. *
  15. * @version 2.1 Alpha 1
  16. */
  17. if (!defined('SMF'))
  18. die('Hacking attempt...');
  19. /**
  20. * Reads a .tar.gz file, filename, in and extracts file(s) from it.
  21. * essentially just a shortcut for read_tgz_data().
  22. * @param string $filename
  23. * @param string $destination
  24. * @param bool $single_file = false
  25. * @param bool $overwrite = false
  26. * @param array $files_to_extract = null
  27. */
  28. function read_tgz_file($gzfilename, $destination, $single_file = false, $overwrite = false, $files_to_extract = null)
  29. {
  30. if (strpos($gzfilename, 'http://') === 0)
  31. {
  32. $data = fetch_web_data($gzfilename);
  33. if ($data === false)
  34. return false;
  35. }
  36. else
  37. {
  38. $data = @file_get_contents($gzfilename);
  39. if ($data === false)
  40. return false;
  41. }
  42. return read_tgz_data($data, $destination, $single_file, $overwrite, $files_to_extract);
  43. }
  44. /**
  45. * Extracts a file or files from the .tar.gz contained in data.
  46. * detects if the file is really a .zip file, and if so returns the result of read_zip_data
  47. * if destination is null, returns a list of files in the archive.
  48. * if single_file is true, returns the contents of the file specified by destination, if it exists, or false.
  49. * if single_file is true, destination can start with * and / to signify that the file may come from any directory.
  50. * destination should not begin with a / if single_file is true.
  51. * overwrites existing files with newer modification times if and only if overwrite is true.
  52. * creates the destination directory if it doesn't exist, and is is specified.
  53. * requires zlib support be built into PHP.
  54. * returns an array of the files extracted.
  55. * if files_to_extract is not equal to null only extracts file within this array.
  56. * @param string data,
  57. * @param string destination,
  58. * @param bool single_file = false,
  59. * @param bool overwrite = false,
  60. * @param array files_to_extract = null
  61. * @return array
  62. */
  63. function read_tgz_data($data, $destination, $single_file = false, $overwrite = false, $files_to_extract = null)
  64. {
  65. // Make sure we have this loaded.
  66. loadLanguage('Packages');
  67. // This function sorta needs gzinflate!
  68. if (!function_exists('gzinflate'))
  69. fatal_lang_error('package_no_zlib', 'critical');
  70. umask(0);
  71. if (!$single_file && $destination !== null && !file_exists($destination))
  72. mktree($destination, 0777);
  73. // No signature?
  74. if (strlen($data) < 2)
  75. return false;
  76. $id = unpack('H2a/H2b', substr($data, 0, 2));
  77. if (strtolower($id['a'] . $id['b']) != '1f8b')
  78. {
  79. // Okay, this ain't no tar.gz, but maybe it's a zip file.
  80. if (strpos($data, 'PK') === 0)
  81. return read_zip_data($data, $destination, $single_file, $overwrite, $files_to_extract);
  82. else
  83. return false;
  84. }
  85. $flags = unpack('Ct/Cf', substr($data, 2, 2));
  86. // Not deflate!
  87. if ($flags['t'] != 8)
  88. return false;
  89. $flags = $flags['f'];
  90. $offset = 10;
  91. $octdec = array('mode', 'uid', 'gid', 'size', 'mtime', 'checksum', 'type');
  92. // "Read" the filename and comment.
  93. // @todo Might be mussed.
  94. if ($flags & 12)
  95. {
  96. while ($flags & 8 && $data{$offset++} != "\0")
  97. continue;
  98. while ($flags & 4 && $data{$offset++} != "\0")
  99. continue;
  100. }
  101. $crc = unpack('Vcrc32/Visize', substr($data, strlen($data) - 8, 8));
  102. $data = @gzinflate(substr($data, $offset, strlen($data) - 8 - $offset));
  103. // smf_crc32 and crc32 may not return the same results, so we accept either.
  104. if ($crc['crc32'] != smf_crc32($data) && $crc['crc32'] != crc32($data))
  105. return false;
  106. $blocks = strlen($data) / 512 - 1;
  107. $offset = 0;
  108. $return = array();
  109. while ($offset < $blocks)
  110. {
  111. $header = substr($data, $offset << 9, 512);
  112. $current = unpack('a100filename/a8mode/a8uid/a8gid/a12size/a12mtime/a8checksum/a1type/a100linkname/a6magic/a2version/a32uname/a32gname/a8devmajor/a8devminor/a155path', $header);
  113. // Blank record? This is probably at the end of the file.
  114. if (empty($current['filename']))
  115. {
  116. $offset += 512;
  117. continue;
  118. }
  119. if ($current['type'] == 5 && substr($current['filename'], -1) != '/')
  120. $current['filename'] .= '/';
  121. foreach ($current as $k => $v)
  122. {
  123. if (in_array($k, $octdec))
  124. $current[$k] = octdec(trim($v));
  125. else
  126. $current[$k] = trim($v);
  127. }
  128. $checksum = 256;
  129. for ($i = 0; $i < 148; $i++)
  130. $checksum += ord($header{$i});
  131. for ($i = 156; $i < 512; $i++)
  132. $checksum += ord($header{$i});
  133. if ($current['checksum'] != $checksum)
  134. break;
  135. $size = ceil($current['size'] / 512);
  136. $current['data'] = substr($data, ++$offset << 9, $current['size']);
  137. $offset += $size;
  138. // Not a directory and doesn't exist already...
  139. if (substr($current['filename'], -1, 1) != '/' && !file_exists($destination . '/' . $current['filename']))
  140. $write_this = true;
  141. // File exists... check if it is newer.
  142. elseif (substr($current['filename'], -1, 1) != '/')
  143. $write_this = $overwrite || filemtime($destination . '/' . $current['filename']) < $current['mtime'];
  144. // Folder... create.
  145. elseif ($destination !== null && !$single_file)
  146. {
  147. // Protect from accidental parent directory writing...
  148. $current['filename'] = strtr($current['filename'], array('../' => '', '/..' => ''));
  149. if (!file_exists($destination . '/' . $current['filename']))
  150. mktree($destination . '/' . $current['filename'], 0777);
  151. $write_this = false;
  152. }
  153. else
  154. $write_this = false;
  155. if ($write_this && $destination !== null)
  156. {
  157. if (strpos($current['filename'], '/') !== false && !$single_file)
  158. mktree($destination . '/' . dirname($current['filename']), 0777);
  159. // Is this the file we're looking for?
  160. if ($single_file && ($destination == $current['filename'] || $destination == '*/' . basename($current['filename'])))
  161. return $current['data'];
  162. // If we're looking for another file, keep going.
  163. elseif ($single_file)
  164. continue;
  165. // Looking for restricted files?
  166. elseif ($files_to_extract !== null && !in_array($current['filename'], $files_to_extract))
  167. continue;
  168. package_put_contents($destination . '/' . $current['filename'], $current['data']);
  169. }
  170. if (substr($current['filename'], -1, 1) != '/')
  171. $return[] = array(
  172. 'filename' => $current['filename'],
  173. 'md5' => md5($current['data']),
  174. 'preview' => substr($current['data'], 0, 100),
  175. 'size' => $current['size'],
  176. 'skipped' => false
  177. );
  178. }
  179. if ($destination !== null && !$single_file)
  180. package_flush_cache();
  181. if ($single_file)
  182. return false;
  183. else
  184. return $return;
  185. }
  186. // Extract zip data. If destination is null, return a listing.
  187. function read_zip_data($data, $destination, $single_file = false, $overwrite = false, $files_to_extract = null)
  188. {
  189. umask(0);
  190. if ($destination !== null && !file_exists($destination) && !$single_file)
  191. mktree($destination, 0777);
  192. // Look for the PK header...
  193. if (strpos($data, 'PK') !== 0)
  194. return false;
  195. // Find the central whosamawhatsit at the end; if there's a comment it's a pain.
  196. if (substr($data, -22, 4) == 'PK' . chr(5) . chr(6))
  197. $p = -22;
  198. else
  199. {
  200. // Have to find where the comment begins, ugh.
  201. for ($p = -22; $p > -strlen($data); $p--)
  202. {
  203. if (substr($data, $p, 4) == 'PK' . chr(5) . chr(6))
  204. break;
  205. }
  206. }
  207. $return = array();
  208. // Get the basic zip file info.
  209. $zip_info = unpack('vfiles/Vsize/Voffset', substr($data, $p + 10, 10));
  210. $p = $zip_info['offset'];
  211. for ($i = 0; $i < $zip_info['files']; $i++)
  212. {
  213. // Make sure this is a file entry...
  214. if (substr($data, $p, 4) != 'PK' . chr(1) . chr(2))
  215. return false;
  216. // Get all the important file information.
  217. $file_info = unpack('Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len/vcomment_len/vdisk/vinternal/Vexternal/Voffset', substr($data, $p + 16, 30));
  218. $file_info['filename'] = substr($data, $p + 46, $file_info['filename_len']);
  219. // Skip all the information we don't care about anyway.
  220. $p += 46 + $file_info['filename_len'] + $file_info['extra_len'] + $file_info['comment_len'];
  221. // If this is a file, and it doesn't exist.... happy days!
  222. if (substr($file_info['filename'], -1, 1) != '/' && !file_exists($destination . '/' . $file_info['filename']))
  223. $write_this = true;
  224. // If the file exists, we may not want to overwrite it.
  225. elseif (substr($file_info['filename'], -1, 1) != '/')
  226. $write_this = $overwrite;
  227. // This is a directory, so we're gonna want to create it. (probably...)
  228. elseif ($destination !== null && !$single_file)
  229. {
  230. // Just a little accident prevention, don't mind me.
  231. $file_info['filename'] = strtr($file_info['filename'], array('../' => '', '/..' => ''));
  232. if (!file_exists($destination . '/' . $file_info['filename']))
  233. mktree($destination . '/' . $file_info['filename'], 0777);
  234. $write_this = false;
  235. }
  236. else
  237. $write_this = false;
  238. // Check that the data is there and does exist.
  239. if (substr($data, $file_info['offset'], 4) != 'PK' . chr(3) . chr(4))
  240. return false;
  241. // Get the actual compressed data.
  242. $file_info['data'] = substr($data, $file_info['offset'] + 30 + $file_info['filename_len'], $file_info['compressed_size']);
  243. // Only inflate it if we need to ;).
  244. if ($file_info['compressed_size'] != $file_info['size'])
  245. $file_info['data'] = @gzinflate($file_info['data']);
  246. // Okay! We can write this file, looks good from here...
  247. if ($write_this && $destination !== null)
  248. {
  249. if (strpos($file_info['filename'], '/') !== false && !$single_file)
  250. mktree($destination . '/' . dirname($file_info['filename']), 0777);
  251. // If we're looking for a specific file, and this is it... ka-bam, baby.
  252. if ($single_file && ($destination == $file_info['filename'] || $destination == '*/' . basename($file_info['filename'])))
  253. return $file_info['data'];
  254. // Oh? Another file. Fine. You don't like this file, do you? I know how it is. Yeah... just go away. No, don't apologize. I know this file's just not *good enough* for you.
  255. elseif ($single_file)
  256. continue;
  257. // Don't really want this?
  258. elseif ($files_to_extract !== null && !in_array($file_info['filename'], $files_to_extract))
  259. continue;
  260. package_put_contents($destination . '/' . $file_info['filename'], $file_info['data']);
  261. }
  262. if (substr($file_info['filename'], -1, 1) != '/')
  263. $return[] = array(
  264. 'filename' => $file_info['filename'],
  265. 'md5' => md5($file_info['data']),
  266. 'preview' => substr($file_info['data'], 0, 100),
  267. 'size' => $file_info['size'],
  268. 'skipped' => false
  269. );
  270. }
  271. if ($destination !== null && !$single_file)
  272. package_flush_cache();
  273. if ($single_file)
  274. return false;
  275. else
  276. return $return;
  277. }
  278. /**
  279. * Checks the existence of a remote file since file_exists() does not do remote.
  280. * will return false if the file is "moved permanently" or similar.
  281. * @param string url
  282. * @return bool true if the remote url exists.
  283. */
  284. function url_exists($url)
  285. {
  286. $a_url = parse_url($url);
  287. if (!isset($a_url['scheme']))
  288. return false;
  289. // Attempt to connect...
  290. $temp = '';
  291. $fid = fsockopen($a_url['host'], !isset($a_url['port']) ? 80 : $a_url['port'], $temp, $temp, 8);
  292. if (!$fid)
  293. return false;
  294. fputs($fid, 'HEAD ' . $a_url['path'] . ' HTTP/1.0' . "\r\n" . 'Host: ' . $a_url['host'] . "\r\n\r\n");
  295. $head = fread($fid, 1024);
  296. fclose($fid);
  297. return preg_match('~^HTTP/.+\s+(20[01]|30[127])~i', $head) == 1;
  298. }
  299. /**
  300. * Loads and returns an array of installed packages.
  301. * gets this information from Packages/installed.list.
  302. * returns the array of data.
  303. * @return array
  304. */
  305. function loadInstalledPackages()
  306. {
  307. global $boarddir, $smcFunc;
  308. // First, check that the database is valid, installed.list is still king.
  309. $install_file = implode('', file($boarddir . '/Packages/installed.list'));
  310. if (trim($install_file) == '')
  311. {
  312. $smcFunc['db_query']('', '
  313. UPDATE {db_prefix}log_packages
  314. SET install_state = {int:not_installed}',
  315. array(
  316. 'not_installed' => 0,
  317. )
  318. );
  319. // Don't have anything left, so send an empty array.
  320. return array();
  321. }
  322. // Load the packages from the database - note this is ordered by install time to ensure latest package uninstalled first.
  323. $request = $smcFunc['db_query']('', '
  324. SELECT id_install, package_id, filename, name, version
  325. FROM {db_prefix}log_packages
  326. WHERE install_state != {int:not_installed}
  327. ORDER BY time_installed DESC',
  328. array(
  329. 'not_installed' => 0,
  330. )
  331. );
  332. $installed = array();
  333. $found = array();
  334. while ($row = $smcFunc['db_fetch_assoc']($request))
  335. {
  336. // Already found this? If so don't add it twice!
  337. if (in_array($row['package_id'], $found))
  338. continue;
  339. $found[] = $row['package_id'];
  340. $installed[] = array(
  341. 'id' => $row['id_install'],
  342. 'name' => $row['name'],
  343. 'filename' => $row['filename'],
  344. 'package_id' => $row['package_id'],
  345. 'version' => $row['version'],
  346. );
  347. }
  348. $smcFunc['db_free_result']($request);
  349. return $installed;
  350. }
  351. /**
  352. * Loads a package's information and returns a representative array.
  353. * expects the file to be a package in Packages/.
  354. * returns a error string if the package-info is invalid.
  355. * returns a basic array of id, version, filename, and similar information.
  356. * in the array returned, an xmlArray is available in 'xml'.
  357. * @param string $filename
  358. * @return array
  359. */
  360. function getPackageInfo($gzfilename)
  361. {
  362. global $boarddir;
  363. // Extract package-info.xml from downloaded file. (*/ is used because it could be in any directory.)
  364. if (strpos($gzfilename, 'http://') !== false)
  365. $packageInfo = read_tgz_data(fetch_web_data($gzfilename, '', true), '*/package-info.xml', true);
  366. else
  367. {
  368. if (!file_exists($boarddir . '/Packages/' . $gzfilename))
  369. return 'package_get_error_not_found';
  370. if (is_file($boarddir . '/Packages/' . $gzfilename))
  371. $packageInfo = read_tgz_file($boarddir . '/Packages/' . $gzfilename, '*/package-info.xml', true);
  372. elseif (file_exists($boarddir . '/Packages/' . $gzfilename . '/package-info.xml'))
  373. $packageInfo = file_get_contents($boarddir . '/Packages/' . $gzfilename . '/package-info.xml');
  374. else
  375. return 'package_get_error_missing_xml';
  376. }
  377. // Nothing?
  378. if (empty($packageInfo))
  379. return 'package_get_error_is_zero';
  380. // Parse package-info.xml into an xmlArray.
  381. loadClassFile('Class-Package.php');
  382. $packageInfo = new xmlArray($packageInfo);
  383. // @todo Error message of some sort?
  384. if (!$packageInfo->exists('package-info[0]'))
  385. return 'package_get_error_packageinfo_corrupt';
  386. $packageInfo = $packageInfo->path('package-info[0]');
  387. $package = $packageInfo->to_array();
  388. $package['xml'] = $packageInfo;
  389. $package['filename'] = $gzfilename;
  390. if (!isset($package['type']))
  391. $package['type'] = 'modification';
  392. return $package;
  393. }
  394. // Create a chmod control for chmoding files.
  395. function create_chmod_control($chmodFiles = array(), $chmodOptions = array(), $restore_write_status = false)
  396. {
  397. global $context, $modSettings, $package_ftp, $boarddir, $txt, $sourcedir, $scripturl;
  398. // If we're restoring the status of existing files prepare the data.
  399. if ($restore_write_status && isset($_SESSION['pack_ftp']) && !empty($_SESSION['pack_ftp']['original_perms']))
  400. {
  401. function list_restoreFiles($dummy1, $dummy2, $dummy3, $do_change)
  402. {
  403. global $txt;
  404. $restore_files = array();
  405. foreach ($_SESSION['pack_ftp']['original_perms'] as $file => $perms)
  406. {
  407. // Check the file still exists, and the permissions were indeed different than now.
  408. $file_permissions = @fileperms($file);
  409. if (!file_exists($file) || $file_permissions == $perms)
  410. {
  411. unset($_SESSION['pack_ftp']['original_perms'][$file]);
  412. continue;
  413. }
  414. // Are we wanting to change the permission?
  415. if ($do_change && isset($_POST['restore_files']) && in_array($file, $_POST['restore_files']))
  416. {
  417. // Use FTP if we have it.
  418. // @todo where does $package_ftp get set?
  419. if (!empty($package_ftp))
  420. {
  421. $ftp_file = strtr($file, array($_SESSION['pack_ftp']['root'] => ''));
  422. $package_ftp->chmod($ftp_file, $perms);
  423. }
  424. else
  425. @chmod($file, $perms);
  426. $new_permissions = @fileperms($file);
  427. $result = $new_permissions == $perms ? 'success' : 'failure';
  428. unset($_SESSION['pack_ftp']['original_perms'][$file]);
  429. }
  430. elseif ($do_change)
  431. {
  432. $new_permissions = '';
  433. $result = 'skipped';
  434. unset($_SESSION['pack_ftp']['original_perms'][$file]);
  435. }
  436. // Record the results!
  437. $restore_files[] = array(
  438. 'path' => $file,
  439. 'old_perms_raw' => $perms,
  440. 'old_perms' => substr(sprintf('%o', $perms), -4),
  441. 'cur_perms' => substr(sprintf('%o', $file_permissions), -4),
  442. 'new_perms' => isset($new_permissions) ? substr(sprintf('%o', $new_permissions), -4) : '',
  443. 'result' => isset($result) ? $result : '',
  444. 'writable_message' => '<span style="color: ' . (@is_writable($file) ? 'green' : 'red') . '">' . (@is_writable($file) ? $txt['package_file_perms_writable'] : $txt['package_file_perms_not_writable']) . '</span>',
  445. );
  446. }
  447. return $restore_files;
  448. }
  449. $listOptions = array(
  450. 'id' => 'restore_file_permissions',
  451. 'title' => $txt['package_restore_permissions'],
  452. 'get_items' => array(
  453. 'function' => 'list_restoreFiles',
  454. 'params' => array(
  455. !empty($_POST['restore_perms']),
  456. ),
  457. ),
  458. 'columns' => array(
  459. 'path' => array(
  460. 'header' => array(
  461. 'value' => $txt['package_restore_permissions_filename'],
  462. ),
  463. 'data' => array(
  464. 'db' => 'path',
  465. 'class' => 'smalltext',
  466. ),
  467. ),
  468. 'old_perms' => array(
  469. 'header' => array(
  470. 'value' => $txt['package_restore_permissions_orig_status'],
  471. ),
  472. 'data' => array(
  473. 'db' => 'old_perms',
  474. 'class' => 'smalltext',
  475. ),
  476. ),
  477. 'cur_perms' => array(
  478. 'header' => array(
  479. 'value' => $txt['package_restore_permissions_cur_status'],
  480. ),
  481. 'data' => array(
  482. 'function' => create_function('$rowData', '
  483. global $txt;
  484. $formatTxt = $rowData[\'result\'] == \'\' || $rowData[\'result\'] == \'skipped\' ? $txt[\'package_restore_permissions_pre_change\'] : $txt[\'package_restore_permissions_post_change\'];
  485. return sprintf($formatTxt, $rowData[\'cur_perms\'], $rowData[\'new_perms\'], $rowData[\'writable_message\']);
  486. '),
  487. 'class' => 'smalltext',
  488. ),
  489. ),
  490. 'check' => array(
  491. 'header' => array(
  492. 'value' => '<input type="checkbox" onclick="invertAll(this, this.form);" class="input_check" />',
  493. ),
  494. 'data' => array(
  495. 'sprintf' => array(
  496. 'format' => '<input type="checkbox" name="restore_files[]" value="%1$s" class="input_check" />',
  497. 'params' => array(
  498. 'path' => false,
  499. ),
  500. ),
  501. 'style' => 'text-align: center',
  502. ),
  503. ),
  504. 'result' => array(
  505. 'header' => array(
  506. 'value' => $txt['package_restore_permissions_result'],
  507. ),
  508. 'data' => array(
  509. 'function' => create_function('$rowData', '
  510. global $txt;
  511. return $txt[\'package_restore_permissions_action_\' . $rowData[\'result\']];
  512. '),
  513. 'class' => 'smalltext',
  514. ),
  515. ),
  516. ),
  517. 'form' => array(
  518. 'href' => !empty($chmodOptions['destination_url']) ? $chmodOptions['destination_url'] : $scripturl . '?action=admin;area=packages;sa=perms;restore;' . $context['session_var'] . '=' . $context['session_id'],
  519. ),
  520. 'additional_rows' => array(
  521. array(
  522. 'position' => 'below_table_data',
  523. 'value' => '<input type="submit" name="restore_perms" value="' . $txt['package_restore_permissions_restore'] . '" class="button_submit" />',
  524. 'class' => 'titlebg',
  525. 'style' => 'text-align: right;',
  526. ),
  527. array(
  528. 'position' => 'after_title',
  529. 'value' => '<span class="smalltext">' . $txt['package_restore_permissions_desc'] . '</span>',
  530. 'class' => 'windowbg2',
  531. ),
  532. ),
  533. );
  534. // Work out what columns and the like to show.
  535. if (!empty($_POST['restore_perms']))
  536. {
  537. $listOptions['additional_rows'][1]['value'] = sprintf($txt['package_restore_permissions_action_done'], $scripturl . '?action=admin;area=packages;sa=perms;' . $context['session_var'] . '=' . $context['session_id']);
  538. unset($listOptions['columns']['check'], $listOptions['form'], $listOptions['additional_rows'][0]);
  539. $context['sub_template'] = 'show_list';
  540. $context['default_list'] = 'restore_file_permissions';
  541. }
  542. else
  543. {
  544. unset($listOptions['columns']['result']);
  545. }
  546. // Create the list for display.
  547. require_once($sourcedir . '/Subs-List.php');
  548. createList($listOptions);
  549. // If we just restored permissions then whereever we are, we are now done and dusted.
  550. if (!empty($_POST['restore_perms']))
  551. obExit();
  552. }
  553. // Otherwise, it's entirely irrelevant?
  554. elseif ($restore_write_status)
  555. return true;
  556. // This is where we report what we got up to.
  557. $return_data = array(
  558. 'files' => array(
  559. 'writable' => array(),
  560. 'notwritable' => array(),
  561. ),
  562. );
  563. // If we have some FTP information already, then let's assume it was required and try to get ourselves connected.
  564. if (!empty($_SESSION['pack_ftp']['connected']))
  565. {
  566. // Load the file containing the ftp_connection class.
  567. loadClassFile('Class-Package.php');
  568. $package_ftp = new ftp_connection($_SESSION['pack_ftp']['server'], $_SESSION['pack_ftp']['port'], $_SESSION['pack_ftp']['username'], package_crypt($_SESSION['pack_ftp']['password']));
  569. }
  570. // Just got a submission did we?
  571. if (empty($package_ftp) && isset($_POST['ftp_username']))
  572. {
  573. loadClassFile('Class-Package.php');
  574. $ftp = new ftp_connection($_POST['ftp_server'], $_POST['ftp_port'], $_POST['ftp_username'], $_POST['ftp_password']);
  575. // We're connected, jolly good!
  576. if ($ftp->error === false)
  577. {
  578. // Common mistake, so let's try to remedy it...
  579. if (!$ftp->chdir($_POST['ftp_path']))
  580. {
  581. $ftp_error = $ftp->last_message;
  582. $ftp->chdir(preg_replace('~^/home[2]?/[^/]+?~', '', $_POST['ftp_path']));
  583. }
  584. if (!in_array($_POST['ftp_path'], array('', '/')))
  585. {
  586. $ftp_root = strtr($boarddir, array($_POST['ftp_path'] => ''));
  587. if (substr($ftp_root, -1) == '/' && ($_POST['ftp_path'] == '' || strpos($_POST['ftp_path'], '/') === 0))
  588. $ftp_root = substr($ftp_root, 0, -1);
  589. }
  590. else
  591. $ftp_root = $boarddir;
  592. $_SESSION['pack_ftp'] = array(
  593. 'server' => $_POST['ftp_server'],
  594. 'port' => $_POST['ftp_port'],
  595. 'username' => $_POST['ftp_username'],
  596. 'password' => package_crypt($_POST['ftp_password']),
  597. 'path' => $_POST['ftp_path'],
  598. 'root' => $ftp_root,
  599. 'connected' => true,
  600. );
  601. if (!isset($modSettings['package_path']) || $modSettings['package_path'] != $_POST['ftp_path'])
  602. updateSettings(array('package_path' => $_POST['ftp_path']));
  603. // This is now the primary connection.
  604. $package_ftp = $ftp;
  605. }
  606. }
  607. // Now try to simply make the files writable, with whatever we might have.
  608. if (!empty($chmodFiles))
  609. {
  610. foreach ($chmodFiles as $k => $file)
  611. {
  612. // Sometimes this can somehow happen maybe?
  613. if (empty($file))
  614. unset($chmodFiles[$k]);
  615. // Already writable?
  616. elseif (@is_writable($file))
  617. $return_data['files']['writable'][] = $file;
  618. else
  619. {
  620. // Now try to change that.
  621. $return_data['files'][package_chmod($file, 'writable', true) ? 'writable' : 'notwritable'][] = $file;
  622. }
  623. }
  624. }
  625. // Have we still got nasty files which ain't writable? Dear me we need more FTP good sir.
  626. if (empty($package_ftp) && (!empty($return_data['files']['notwritable']) || !empty($chmodOptions['force_find_error'])))
  627. {
  628. if (!isset($ftp) || $ftp->error !== false)
  629. {
  630. if (!isset($ftp))
  631. {
  632. loadClassFile('Class-Package.php');
  633. $ftp = new ftp_connection(null);
  634. }
  635. elseif ($ftp->error !== false && !isset($ftp_error))
  636. $ftp_error = $ftp->last_message === null ? '' : $ftp->last_message;
  637. list ($username, $detect_path, $found_path) = $ftp->detect_path($boarddir);
  638. if ($found_path)
  639. $_POST['ftp_path'] = $detect_path;
  640. elseif (!isset($_POST['ftp_path']))
  641. $_POST['ftp_path'] = isset($modSettings['package_path']) ? $modSettings['package_path'] : $detect_path;
  642. if (!isset($_POST['ftp_username']))
  643. $_POST['ftp_username'] = $username;
  644. }
  645. $context['package_ftp'] = array(
  646. 'server' => isset($_POST['ftp_server']) ? $_POST['ftp_server'] : (isset($modSettings['package_server']) ? $modSettings['package_server'] : 'localhost'),
  647. 'port' => isset($_POST['ftp_port']) ? $_POST['ftp_port'] : (isset($modSettings['package_port']) ? $modSettings['package_port'] : '21'),
  648. 'username' => isset($_POST['ftp_username']) ? $_POST['ftp_username'] : (isset($modSettings['package_username']) ? $modSettings['package_username'] : ''),
  649. 'path' => $_POST['ftp_path'],
  650. 'error' => empty($ftp_error) ? null : $ftp_error,
  651. 'destination' => !empty($chmodOptions['destination_url']) ? $chmodOptions['destination_url'] : '',
  652. );
  653. // Which files failed?
  654. if (!isset($context['notwritable_files']))
  655. $context['notwritable_files'] = array();
  656. $context['notwritable_files'] = array_merge($context['notwritable_files'], $return_data['files']['notwritable']);
  657. // Sent here to die?
  658. if (!empty($chmodOptions['crash_on_error']))
  659. {
  660. $context['page_title'] = $txt['package_ftp_necessary'];
  661. $context['sub_template'] = 'ftp_required';
  662. obExit();
  663. }
  664. }
  665. return $return_data;
  666. }
  667. /**
  668. * @param string $destination_url
  669. * @param array $files = none
  670. * @param bool $return = false
  671. */
  672. function packageRequireFTP($destination_url, $files = null, $return = false)
  673. {
  674. global $context, $modSettings, $package_ftp, $boarddir, $txt;
  675. // Try to make them writable the manual way.
  676. if ($files !== null)
  677. {
  678. foreach ($files as $k => $file)
  679. {
  680. // If this file doesn't exist, then we actually want to look at the directory, no?
  681. if (!file_exists($file))
  682. $file = dirname($file);
  683. // This looks odd, but it's an attempt to work around PHP suExec.
  684. if (!@is_writable($file))
  685. @chmod($file, 0755);
  686. if (!@is_writable($file))
  687. @chmod($file, 0777);
  688. if (!@is_writable(dirname($file)))
  689. @chmod($file, 0755);
  690. if (!@is_writable(dirname($file)))
  691. @chmod($file, 0777);
  692. $fp = is_dir($file) ? @opendir($file) : @fopen($file, 'rb');
  693. if (@is_writable($file) && $fp)
  694. {
  695. unset($files[$k]);
  696. if (!is_dir($file))
  697. fclose($fp);
  698. else
  699. closedir($fp);
  700. }
  701. }
  702. // No FTP required!
  703. if (empty($files))
  704. return array();
  705. }
  706. // They've opted to not use FTP, and try anyway.
  707. if (isset($_SESSION['pack_ftp']) && $_SESSION['pack_ftp'] == false)
  708. {
  709. if ($files === null)
  710. return array();
  711. foreach ($files as $k => $file)
  712. {
  713. // This looks odd, but it's an attempt to work around PHP suExec.
  714. if (!file_exists($file))
  715. {
  716. mktree(dirname($file), 0755);
  717. @touch($file);
  718. @chmod($file, 0755);
  719. }
  720. if (!@is_writable($file))
  721. @chmod($file, 0777);
  722. if (!@is_writable(dirname($file)))
  723. @chmod(dirname($file), 0777);
  724. if (@is_writable($file))
  725. unset($files[$k]);
  726. }
  727. return $files;
  728. }
  729. elseif (isset($_SESSION['pack_ftp']))
  730. {
  731. // Load the file containing the ftp_connection class.
  732. loadClassFile('Class-Package.php');
  733. $package_ftp = new ftp_connection($_SESSION['pack_ftp']['server'], $_SESSION['pack_ftp']['port'], $_SESSION['pack_ftp']['username'], package_crypt($_SESSION['pack_ftp']['password']));
  734. if ($files === null)
  735. return array();
  736. foreach ($files as $k => $file)
  737. {
  738. $ftp_file = strtr($file, array($_SESSION['pack_ftp']['root'] => ''));
  739. // This looks odd, but it's an attempt to work around PHP suExec.
  740. if (!file_exists($file))
  741. {
  742. mktree(dirname($file), 0755);
  743. $package_ftp->create_file($ftp_file);
  744. $package_ftp->chmod($ftp_file, 0755);
  745. }
  746. if (!@is_writable($file))
  747. $package_ftp->chmod($ftp_file, 0777);
  748. if (!@is_writable(dirname($file)))
  749. $package_ftp->chmod(dirname($ftp_file), 0777);
  750. if (@is_writable($file))
  751. unset($files[$k]);
  752. }
  753. return $files;
  754. }
  755. if (isset($_POST['ftp_none']))
  756. {
  757. $_SESSION['pack_ftp'] = false;
  758. $files = packageRequireFTP($destination_url, $files, $return);
  759. return $files;
  760. }
  761. elseif (isset($_POST['ftp_username']))
  762. {
  763. loadClassFile('Class-Package.php');
  764. $ftp = new ftp_connection($_POST['ftp_server'], $_POST['ftp_port'], $_POST['ftp_username'], $_POST['ftp_password']);
  765. if ($ftp->error === false)
  766. {
  767. // Common mistake, so let's try to remedy it...
  768. if (!$ftp->chdir($_POST['ftp_path']))
  769. {
  770. $ftp_error = $ftp->last_message;
  771. $ftp->chdir(preg_replace('~^/home[2]?/[^/]+?~', '', $_POST['ftp_path']));
  772. }
  773. }
  774. }
  775. if (!isset($ftp) || $ftp->error !== false)
  776. {
  777. if (!isset($ftp))
  778. {
  779. loadClassFile('Class-Package.php');
  780. $ftp = new ftp_connection(null);
  781. }
  782. elseif ($ftp->error !== false && !isset($ftp_error))
  783. $ftp_error = $ftp->last_message === null ? '' : $ftp->last_message;
  784. list ($username, $detect_path, $found_path) = $ftp->detect_path($boarddir);
  785. if ($found_path)
  786. $_POST['ftp_path'] = $detect_path;
  787. elseif (!isset($_POST['ftp_path']))
  788. $_POST['ftp_path'] = isset($modSettings['package_path']) ? $modSettings['package_path'] : $detect_path;
  789. if (!isset($_POST['ftp_username']))
  790. $_POST['ftp_username'] = $username;
  791. $context['package_ftp'] = array(
  792. 'server' => isset($_POST['ftp_server']) ? $_POST['ftp_server'] : (isset($modSettings['package_server']) ? $modSettings['package_server'] : 'localhost'),
  793. 'port' => isset($_POST['ftp_port']) ? $_POST['ftp_port'] : (isset($modSettings['package_port']) ? $modSettings['package_port'] : '21'),
  794. 'username' => isset($_POST['ftp_username']) ? $_POST['ftp_username'] : (isset($modSettings['package_username']) ? $modSettings['package_username'] : ''),
  795. 'path' => $_POST['ftp_path'],
  796. 'error' => empty($ftp_error) ? null : $ftp_error,
  797. 'destination' => $destination_url,
  798. );
  799. // If we're returning dump out here.
  800. if ($return)
  801. return $files;
  802. $context['page_title'] = $txt['package_ftp_necessary'];
  803. $context['sub_template'] = 'ftp_required';
  804. obExit();
  805. }
  806. else
  807. {
  808. if (!in_array($_POST['ftp_path'], array('', '/')))
  809. {
  810. $ftp_root = strtr($boarddir, array($_POST['ftp_path'] => ''));
  811. if (substr($ftp_root, -1) == '/' && ($_POST['ftp_path'] == '' || strpos($_POST['ftp_path'], '/') === 0))
  812. $ftp_root = substr($ftp_root, 0, -1);
  813. }
  814. else
  815. $ftp_root = $boarddir;
  816. $_SESSION['pack_ftp'] = array(
  817. 'server' => $_POST['ftp_server'],
  818. 'port' => $_POST['ftp_port'],
  819. 'username' => $_POST['ftp_username'],
  820. 'password' => package_crypt($_POST['ftp_password']),
  821. 'path' => $_POST['ftp_path'],
  822. 'root' => $ftp_root,
  823. );
  824. if (!isset($modSettings['package_path']) || $modSettings['package_path'] != $_POST['ftp_path'])
  825. updateSettings(array('package_path' => $_POST['ftp_path']));
  826. $files = packageRequireFTP($destination_url, $files, $return);
  827. }
  828. return $files;
  829. }
  830. /**
  831. * Parses the actions in package-info.xml files from packages.
  832. * package should be an xmlArray with package-info as its base.
  833. * testing_only should be true if the package should not actually be applied.
  834. * method is upgrade, install, or uninstall. Its default is install.
  835. * previous_version should be set to the previous installed version of this package, if any.
  836. * does not handle failure terribly well; testing first is always better.
  837. * @param xmlArray &$package
  838. * @param bool $testing_only = true
  839. * @param string $method = 'install' ('install', 'upgrade', or 'uninstall')
  840. * @param string $previous_version = ''
  841. * @return array an array of those changes made.
  842. */
  843. function parsePackageInfo(&$packageXML, $testing_only = true, $method = 'install', $previous_version = '')
  844. {
  845. global $boarddir, $forum_version, $context, $temp_path, $language;
  846. // Mayday! That action doesn't exist!!
  847. if (empty($packageXML) || !$packageXML->exists($method))
  848. return array();
  849. // We haven't found the package script yet...
  850. $script = false;
  851. $the_version = strtr($forum_version, array('SMF ' => ''));
  852. // Emulation support...
  853. if (!empty($_SESSION['version_emulate']))
  854. $the_version = $_SESSION['version_emulate'];
  855. // Get all the versions of this method and find the right one.
  856. $these_methods = $packageXML->set($method);
  857. foreach ($these_methods as $this_method)
  858. {
  859. // They specified certain versions this part is for.
  860. if ($this_method->exists('@for'))
  861. {
  862. // Don't keep going if this won't work for this version of SMF.
  863. if (!matchPackageVersion($the_version, $this_method->fetch('@for')))
  864. continue;
  865. }
  866. // Upgrades may go from a certain old version of the mod.
  867. if ($method == 'upgrade' && $this_method->exists('@from'))
  868. {
  869. // Well, this is for the wrong old version...
  870. if (!matchPackageVersion($previous_version, $this_method->fetch('@from')))
  871. continue;
  872. }
  873. // We've found it!
  874. $script = $this_method;
  875. break;
  876. }
  877. // Bad news, a matching script wasn't found!
  878. if ($script === false)
  879. return array();
  880. // Find all the actions in this method - in theory, these should only be allowed actions. (* means all.)
  881. $actions = $script->set('*');
  882. $return = array();
  883. $temp_auto = 0;
  884. $temp_path = $boarddir . '/Packages/temp/' . (isset($context['base_path']) ? $context['base_path'] : '');
  885. $context['readmes'] = array();
  886. // This is the testing phase... nothing shall be done yet.
  887. foreach ($actions as $action)
  888. {
  889. $actionType = $action->name();
  890. if (in_array($actionType, array('readme', 'code', 'database', 'modification', 'redirect')))
  891. {
  892. // Allow for translated readme files.
  893. if ($actionType == 'readme')
  894. {
  895. if ($action->exists('@lang'))
  896. {
  897. // Auto-select a readme language based on either request variable or current language.
  898. if ((isset($_REQUEST['readme']) && $action->fetch('@lang') == $_REQUEST['readme']) || (!isset($_REQUEST['readme']) && $action->fetch('@lang') == $language))
  899. {
  900. // In case the user put the readme blocks in the wrong order.
  901. if (isset($context['readmes']['selected']) && $context['readmes']['selected'] == 'default')
  902. $context['readmes'][] = 'default';
  903. $context['readmes']['selected'] = htmlspecialchars($action->fetch('@lang'));
  904. }
  905. else
  906. {
  907. // We don't want this readme now, but we'll allow the user to select to read it.
  908. $context['readmes'][] = htmlspecialchars($action->fetch('@lang'));
  909. continue;
  910. }
  911. }
  912. // Fallback readme. Without lang parameter.
  913. else
  914. {
  915. // Already selected a readme.
  916. if (isset($context['readmes']['selected']))
  917. {
  918. $context['readmes'][] = 'default';
  919. continue;
  920. }
  921. else
  922. $context['readmes']['selected'] = 'default';
  923. }
  924. }
  925. // @todo Make sure the file actually exists? Might not work when testing?
  926. if ($action->exists('@type') && $action->fetch('@type') == 'inline')
  927. {
  928. $filename = $temp_path . '$auto_' . $temp_auto++ . ($actionType == 'readme' || $actionType == 'redirect' ? '.txt' : ($actionType == 'code' || $actionType == 'database' ? '.php' : '.mod'));
  929. package_put_contents($filename, $action->fetch('.'));
  930. $filename = strtr($filename, array($temp_path => ''));
  931. }
  932. else
  933. $filename = $action->fetch('.');
  934. $return[] = array(
  935. 'type' => $actionType,
  936. 'filename' => $filename,
  937. 'description' => '',
  938. 'reverse' => $action->exists('@reverse') && $action->fetch('@reverse') == 'true',
  939. 'boardmod' => $action->exists('@format') && $action->fetch('@format') == 'boardmod',
  940. 'redirect_url' => $action->exists('@url') ? $action->fetch('@url') : '',
  941. 'redirect_timeout' => $action->exists('@timeout') ? (int) $action->fetch('@timeout') : '',
  942. 'parse_bbc' => $action->exists('@parsebbc') && $action->fetch('@parsebbc') == 'true',
  943. 'language' => ($actionType == 'readme' && $action->exists('@lang') && $action->fetch('@lang') == $language) ? $language : '',
  944. );
  945. continue;
  946. }
  947. elseif ($actionType == 'hook')
  948. {
  949. $return[] = array(
  950. 'type' => $actionType,
  951. 'function' => $action->exists('@function') ? $action->fetch('@function') : '',
  952. 'hook' => $action->exists('@hook') ? $action->fetch('@hook') : $action->fetch('.'),
  953. 'reverse' => $action->exists('@reverse') && $action->fetch('@reverse') == 'true' ? true : false,
  954. 'description' => '',
  955. );
  956. continue;
  957. }
  958. elseif ($actionType == 'error')
  959. {
  960. $return[] = array(
  961. 'type' => 'error',
  962. );
  963. }
  964. $this_action = &$return[];
  965. $this_action = array(
  966. 'type' => $actionType,
  967. 'filename' => $action->fetch('@name'),
  968. 'description' => $action->fetch('.')
  969. );
  970. // If there is a destination, make sure it makes sense.
  971. if (strpos($actionType, 'remove') !== 0)
  972. {
  973. $this_action['unparsed_destination'] = $action->fetch('@destination');
  974. $this_action['destination'] = parse_path($action->fetch('@destination')) . '/' . basename($this_action['filename']);
  975. }
  976. else
  977. {
  978. $this_action['unparsed_filename'] = $this_action['filename'];
  979. $this_action['filename'] = parse_path($this_action['filename']);
  980. }
  981. // If we're moving or requiring (copying) a file.
  982. if (strpos($actionType, 'move') === 0 || strpos($actionType, 'require') === 0)
  983. {
  984. if ($action->exists('@from'))
  985. $this_action['source'] = parse_path($action->fetch('@from'));
  986. else
  987. $this_action['source'] = $temp_path . $this_action['filename'];
  988. }
  989. // Check if these things can be done. (chmod's etc.)
  990. if ($actionType == 'create-dir')
  991. {
  992. if (!mktree($this_action['destination'], false))
  993. {
  994. $temp = $this_action['destination'];
  995. while (!file_exists($temp) && strlen($temp) > 1)
  996. $temp = dirname($temp);
  997. $return[] = array(
  998. 'type' => 'chmod',
  999. 'filename' => $temp
  1000. );
  1001. }
  1002. }
  1003. elseif ($actionType == 'create-file')
  1004. {
  1005. if (!mktree(dirname($this_action['destination']), false))
  1006. {
  1007. $temp = dirname($this_action['destination']);
  1008. while (!file_exists($temp) && strlen($temp) > 1)
  1009. $temp = dirname($temp);
  1010. $return[] = array(
  1011. 'type' => 'chmod',
  1012. 'filename' => $temp
  1013. );
  1014. }
  1015. if (!is_writable($this_action['destination']) && (file_exists($this_action['destination']) || !is_writable(dirname($this_action['destination']))))
  1016. $return[] = array(
  1017. 'type' => 'chmod',
  1018. 'filename' => $this_action['destination']
  1019. );
  1020. }
  1021. elseif ($actionType == 'require-dir')
  1022. {
  1023. if (!mktree($this_action['destination'], false))
  1024. {
  1025. $temp = $this_action['destination'];
  1026. while (!file_exists($temp) && strlen($temp) > 1)
  1027. $temp = dirname($temp);
  1028. $return[] = array(
  1029. 'type' => 'chmod',
  1030. 'filename' => $temp
  1031. );
  1032. }
  1033. }
  1034. elseif ($actionType == 'require-file')
  1035. {
  1036. if ($action->exists('@theme'))
  1037. $this_action['theme_action'] = $action->fetch('@theme');
  1038. if (!mktree(dirname($this_action['destination']), false))
  1039. {
  1040. $temp = dirname($this_action['destination']);
  1041. while (!file_exists($temp) && strlen($temp) > 1)
  1042. $temp = dirname($temp);
  1043. $return[] = array(
  1044. 'type' => 'chmod',
  1045. 'filename' => $temp
  1046. );
  1047. }
  1048. if (!is_writable($this_action['destination']) && (file_exists($this_action['destination']) || !is_writable(dirname($this_action['destination']))))
  1049. $return[] = array(
  1050. 'type' => 'chmod',
  1051. 'filename' => $this_action['destination']
  1052. );
  1053. }
  1054. elseif ($actionType == 'move-dir' || $actionType == 'move-file')
  1055. {
  1056. if (!mktree(dirname($this_action['destination']), false))
  1057. {
  1058. $temp = dirname($this_action['destination']);
  1059. while (!file_exists($temp) && strlen($temp) > 1)
  1060. $temp = dirname($temp);
  1061. $return[] = array(
  1062. 'type' => 'chmod',
  1063. 'filename' => $temp
  1064. );
  1065. }
  1066. if (!is_writable($this_action['destination']) && (file_exists($this_action['destination']) || !is_writable(dirname($this_action['destination']))))
  1067. $return[] = array(
  1068. 'type' => 'chmod',
  1069. 'filename' => $this_action['destination']
  1070. );
  1071. }
  1072. elseif ($actionType == 'remove-dir')
  1073. {
  1074. if (!is_writable($this_action['filename']) && file_exists($this_action['destination']))
  1075. $return[] = array(
  1076. 'type' => 'chmod',
  1077. 'filename' => $this_action['filename']
  1078. );
  1079. }
  1080. elseif ($actionType == 'remove-file')
  1081. {
  1082. if (!is_writable($this_action['filename']) && file_exists($this_action['filename']))
  1083. $return[] = array(
  1084. 'type' => 'chmod',
  1085. 'filename' => $this_action['filename']
  1086. );
  1087. }
  1088. }
  1089. // Only testing - just return a list of things to be done.
  1090. if ($testing_only)
  1091. return $return;
  1092. umask(0);
  1093. $failure = false;
  1094. $not_done = array(array('type' => '!'));
  1095. foreach ($return as $action)
  1096. {
  1097. if ($action['type'] == 'modification' || $action['type'] == 'code' || $action['type'] == 'database' || $action['type'] == 'redirect')
  1098. $not_done[] = $action;
  1099. if ($action['type'] == 'create-dir')
  1100. {
  1101. if (!mktree($action['destination'], 0755) || !is_writable($action['destination']))
  1102. $failure |= !mktree($action['destination'], 0777);
  1103. }
  1104. elseif ($action['type'] == 'create-file')
  1105. {
  1106. if (!mktree(dirname($action['destination']), 0755) || !is_writable(dirname($action['destination'])))
  1107. $failure |= !mktree(dirname($action['destination']), 0777);
  1108. // Create an empty file.
  1109. package_put_contents($action['destination'], package_get_contents($action['source']), $testing_only);
  1110. if (!file_exists($action['destination']))
  1111. $failure = true;
  1112. }
  1113. elseif ($action['type'] == 'require-dir')
  1114. {
  1115. copytree($action['source'], $action['destination']);
  1116. // Any other theme folders?
  1117. if (!empty($context['theme_copies']) && !empty($context['theme_copies'][$action['type']][$action['destination']]))
  1118. foreach ($context['theme_copies'][$action['type']][$action['destination']] as $theme_destination)
  1119. copytree($action['source'], $theme_destination);
  1120. }
  1121. elseif ($action['type'] == 'require-file')
  1122. {
  1123. if (!mktree(dirname($action['destination']), 0755) || !is_writable(dirname($action['destination'])))
  1124. $failure |= !mktree(dirname($action['destination']), 0777);
  1125. package_put_contents($action['destination'], package_get_contents($action['source']), $testing_only);
  1126. $failure |= !copy($action['source'], $action['destination']);
  1127. // Any other theme files?
  1128. if (!empty($context['theme_copies']) && !empty($context['theme_copies'][$action['type']][$action['destination']]))
  1129. foreach ($context['theme_copies'][$action['type']][$action['destination']] as $theme_destination)
  1130. {
  1131. if (!mktree(dirname($theme_destination), 0755) || !is_writable(dirname($theme_destination)))
  1132. $failure |= !mktree(dirname($theme_destination), 0777);
  1133. package_put_contents($theme_destination, package_get_contents($action['source']), $testing_only);
  1134. $failure |= !copy($action['source'], $theme_destination);
  1135. }
  1136. }
  1137. elseif ($action['type'] == 'move-file')
  1138. {
  1139. if (!mktree(dirname($action['destination']), 0755) || !is_writable(dirname($action['destination'])))
  1140. $failure |= !mktree(dirname($action['destination']), 0777);
  1141. $failure |= !rename($action['source'], $action['destination']);
  1142. }
  1143. elseif ($action['type'] == 'move-dir')
  1144. {
  1145. if (!mktree($action['destination'], 0755) || !is_writable($action['destination']))
  1146. $failure |= !mktree($action['destination'], 0777);
  1147. $failure |= !rename($action['source'], $action['destination']);
  1148. }
  1149. elseif ($action['type'] == 'remove-dir')
  1150. {
  1151. deltree($action['filename']);
  1152. // Any other theme folders?
  1153. if (!empty($context['theme_copies']) && !empty($context['theme_copies'][$action['type']][$action['filename']]))
  1154. foreach ($context['theme_copies'][$action['type']][$action['filename']] as $theme_destination)
  1155. deltree($theme_destination);
  1156. }
  1157. elseif ($action['type'] == 'remove-file')
  1158. {
  1159. // Make sure the file exists before deleting it.
  1160. if (file_exists($action['filename']))
  1161. {
  1162. package_chmod($action['filename']);
  1163. $failure |= !unlink($action['filename']);
  1164. }
  1165. // The file that was supposed to be deleted couldn't be found.
  1166. else
  1167. $failure = true;
  1168. // Any other theme folders?
  1169. if (!empty($context['theme_copies']) && !empty($context['theme_copies'][$action['type']][$action['filename']]))
  1170. foreach ($context['theme_copies'][$action['type']][$action['filename']] as $theme_destination)
  1171. if (file_exists($theme_destination))
  1172. $failure |= !unlink($theme_destination);
  1173. else
  1174. $failure = true;
  1175. }
  1176. }
  1177. return $not_done;
  1178. }
  1179. /**
  1180. * Checks if version matches any of the versions in versions.
  1181. * supports comma separated version numbers, with or without whitespace.
  1182. * supports lower and upper bounds. (1.0-1.2)
  1183. * returns true if the version matched.
  1184. * @param string $version
  1185. * @param string $versions
  1186. * @return bool
  1187. */
  1188. function matchPackageVersion($version, $versions)
  1189. {
  1190. // Make sure everything is lowercase and clean of spaces and unpleasant history.
  1191. $version = str_replace(array(' ', '2.0rc1-1'), array('', '2.0rc1.1'), strtolower($version));
  1192. $versions = explode(',', str_replace(array(' ', '2.0rc1-1'), array('', '2.0rc1.1'), strtolower($versions)));
  1193. // Perhaps we do accept anything?
  1194. if (in_array('all', $versions))
  1195. return true;
  1196. // Loop through each version.
  1197. foreach ($versions as $for)
  1198. {
  1199. // Wild card spotted?
  1200. if (strpos($for, '*') !== false)
  1201. $for = str_replace('*', '0dev0', $for) . '-' . str_replace('*', '999', $for);
  1202. // Do we have a range?
  1203. if (strpos($for, '-') !== false)
  1204. {
  1205. list ($lower, $upper) = explode('-', $for);
  1206. // Compare the version against lower and upper bounds.
  1207. if (compareVersions($version, $lower) > -1 && compareVersions($version, $upper) < 1)
  1208. return true;
  1209. }
  1210. // Otherwise check if they are equal...
  1211. elseif (compareVersions($version, $for) === 0)
  1212. return true;
  1213. }
  1214. return false;
  1215. }
  1216. /**
  1217. * Compares two versions.
  1218. * @param string version1
  1219. * @param string version2
  1220. * @return int (-1 if version1 is lower than version2, 0 if version1 is equal to version2; 1 if version1 is higher than version2)
  1221. */
  1222. function compareVersions($version1, $version2)
  1223. {
  1224. static $categories;
  1225. $versions = array();
  1226. foreach (array(1 => $version1, $version2) as $id => $version)
  1227. {
  1228. // Clean the version and extract the version parts.
  1229. $clean = str_replace(array(' ', '2.0rc1-1'), array('', '2.0rc1.1'), strtolower($version));
  1230. preg_match('~(\d+)(?:\.(\d+|))?(?:\.)?(\d+|)(?:(alpha|beta|rc)(\d+|)(?:\.)?(\d+|))?(?:(dev))?(\d+|)~', $clean, $parts);
  1231. // Build an array of parts.
  1232. $versions[$id] = array(
  1233. 'major' => (int) $parts[1],
  1234. 'minor' => !empty($parts[2]) ? (int) $parts[2] : 0,
  1235. 'patch' => !empty($parts[3]) ? (int) $parts[3] : 0,
  1236. 'type' => empty($parts[4]) ? 'stable' : $parts[4],
  1237. 'type_major' => !empty($parts[6]) ? (int) $parts[5] : 0,
  1238. 'type_minor' => !empty($parts[6]) ? (int) $parts[6] : 0,
  1239. 'dev' => !empty($parts[7]),
  1240. );
  1241. }
  1242. // Are they the same, perhaps?
  1243. if ($versions[1] === $versions[2])
  1244. return 0;
  1245. // Get version numbering categories...
  1246. if (!isset($categories))
  1247. $categories = array_keys($versions[1]);
  1248. // Loop through each category.
  1249. foreach ($categories as $category)
  1250. {
  1251. // Is there something for us to calculate?
  1252. if ($versions[1][$category] !== $versions[2][$category])
  1253. {
  1254. // Dev builds are a problematic exception.
  1255. // (stable) dev < (stable) but (unstable) dev = (unstable)
  1256. if ($category == 'type')
  1257. return $versions[1][$category] > $versions[2][$category] ? ($versions[1]['dev'] ? -1 : 1) : ($versions[2]['dev'] ? 1 : -1);
  1258. elseif ($category == 'dev')
  1259. return $versions[1]['dev'] ? ($versions[2]['type'] == 'stable' ? -1 : 0) : ($versions[1]['type'] == 'stable' ? 1 : 0);
  1260. // Otherwise a simple comparison.
  1261. else
  1262. return $versions[1][$category] > $versions[2][$category] ? 1 : -1;
  1263. }
  1264. }
  1265. // They are the same!
  1266. return 0;
  1267. }
  1268. /**
  1269. * Parses special identifiers out of the specified path.
  1270. * @param string $path
  1271. * @return string The parsed path
  1272. */
  1273. function parse_path($path)
  1274. {
  1275. global $modSettings, $boarddir, $sourcedir, $settings, $temp_path;
  1276. $dirs = array(
  1277. '\\' => '/',
  1278. '$boarddir' => $boarddir,
  1279. '$sourcedir' => $sourcedir,
  1280. '$avatardir' => $modSettings['avatar_directory'],
  1281. '$avatars_dir' => $modSettings['avatar_directory'],
  1282. '$themedir' => $settings['default_theme_dir'],
  1283. '$imagesdir' => $settings['default_theme_dir'] . '/' . basename($settings['default_images_url']),
  1284. '$themes_dir' => $boarddir . '/Themes',
  1285. '$languagedir' => $settings['default_theme_dir'] . '/languages',
  1286. '$languages_dir' => $settings['default_theme_dir'] . '/languages',
  1287. '$smileysdir' => $modSettings['smileys_dir'],
  1288. '$smileys_dir' => $modSettings['smileys_dir'],
  1289. );
  1290. // do we parse in a package directory?
  1291. if (!empty($temp_path))
  1292. $dirs['$package'] = $temp_path;
  1293. if (strlen($path) == 0)
  1294. trigger_error('parse_path(): There should never be an empty filename', E_USER_ERROR);
  1295. return strtr($path, $dirs);
  1296. }
  1297. /**
  1298. * Deletes a directory, and all the files and direcories inside it.
  1299. * requires access to delete these files.
  1300. * @param string $path
  1301. * @param bool $delete_directory = true
  1302. */
  1303. function deltree($dir, $delete_dir = true)
  1304. {
  1305. global $package_ftp;
  1306. if (!file_exists($dir))
  1307. return;
  1308. $current_dir = @opendir($dir);
  1309. if ($current_dir == false)
  1310. {
  1311. if ($delete_dir && isset($package_ftp))
  1312. {
  1313. $ftp_file = strtr($dir, array($_SESSION['pack_ftp']['root'] => ''));
  1314. // @todo $entryname is never set
  1315. if (!is_writable($dir . '/' . $entryname))
  1316. $package_ftp->chmod($ftp_file, 0777);
  1317. $package_ftp->unlink($ftp_file);
  1318. }
  1319. return;
  1320. }
  1321. while ($entryname = readdir($current_dir))
  1322. {
  1323. if (in_array($entryname, array('.', '..')))
  1324. continue;
  1325. if (is_dir($dir . '/' . $entryname))
  1326. deltree($dir . '/' . $entryname);
  1327. else
  1328. {
  1329. // Here, 755 doesn't really matter since we're deleting it anyway.
  1330. if (isset($package_ftp))
  1331. {
  1332. $ftp_file = strtr($dir . '/' . $entryname, array($_SESSION['pack_ftp']['root'] => ''));
  1333. if (!is_writable($dir . '/' . $entryname))
  1334. $package_ftp->chmod($ftp_file, 0777);
  1335. $package_ftp->unlink($ftp_file);
  1336. }
  1337. else
  1338. {
  1339. if (!is_writable($dir . '/' . $entryname))
  1340. @chmod($dir . '/' . $entryname, 0777);
  1341. unlink($dir . '/' . $entryname);
  1342. }
  1343. }
  1344. }
  1345. closedir($current_dir);
  1346. if ($delete_dir)
  1347. {
  1348. if (isset($package_ftp))
  1349. {
  1350. $ftp_file = strtr($dir, array($_SESSION['pack_ftp']['root'] => ''));
  1351. if (!is_writable($dir . '/' . $entryname))
  1352. $package_ftp->chmod($ftp_file, 0777);
  1353. $package_ftp->unlink($ftp_file);
  1354. }
  1355. else
  1356. {
  1357. if (!is_writable($dir))
  1358. @chmod($dir, 0777);
  1359. @rmdir($dir);
  1360. }
  1361. }
  1362. }
  1363. /**
  1364. * Creates the specified tree structure with the mode specified.
  1365. * creates every directory in path until it finds one that already exists.
  1366. * @param string $path
  1367. * @param int $mode
  1368. * @return bool true if successful, false otherwise
  1369. */
  1370. function mktree($strPath, $mode)
  1371. {
  1372. global $package_ftp;
  1373. if (is_dir($strPath))
  1374. {
  1375. if (!is_writable($strPath) && $mode !== false)
  1376. {
  1377. if (isset($package_ftp))
  1378. $package_ftp->chmod(strtr($strPath, array($_SESSION['pack_ftp']['root'] => '')), $mode);
  1379. else
  1380. @chmod($strPath, $mode);
  1381. }
  1382. $test = @opendir($strPath);
  1383. if ($test)
  1384. {
  1385. closedir($test);
  1386. return is_writable($strPath);
  1387. }
  1388. else
  1389. return false;
  1390. }
  1391. // Is this an invalid path and/or we can't make the directory?
  1392. if ($strPath == dirname($strPath) || !mktree(dirname($strPath), $mode))
  1393. return false;
  1394. if (!is_writable(dirname($strPath)) && $mode !== false)
  1395. {
  1396. if (isset($package_ftp))
  1397. $package_ftp->chmod(dirname(strtr($strPath, array($_SESSION['pack_ftp']['root'] => ''))), $mode);
  1398. else
  1399. @chmod(dirname($strPath), $mode);
  1400. }
  1401. if ($mode !== false && isset($package_ftp))
  1402. return $package_ftp->create_dir(strtr($strPath, array($_SESSION['pack_ftp']['root'] => '')));
  1403. elseif ($mode === false)
  1404. {
  1405. $test = @opendir(dirname($strPath));
  1406. if ($test)
  1407. {
  1408. closedir($test);
  1409. return true;
  1410. }
  1411. else
  1412. return false;
  1413. }
  1414. else
  1415. {
  1416. @mkdir($strPath, $mode);
  1417. $test = @opendir($strPath);
  1418. if ($test)
  1419. {
  1420. closedir($test);
  1421. return true;
  1422. }
  1423. else
  1424. return false;
  1425. }
  1426. }
  1427. /**
  1428. * Copies one directory structure over to another.
  1429. * requires the destination to be writable.
  1430. * @param string $source
  1431. * @param string $destination
  1432. */
  1433. function copytree($source, $destination)
  1434. {
  1435. global $package_ftp;
  1436. if (!file_exists($destination) || !is_writable($destination))
  1437. mktree($destination, 0755);
  1438. if (!is_writable($destination))
  1439. mktree($destination, 0777);
  1440. $current_dir = opendir($source);
  1441. if ($current_dir == false)
  1442. return;
  1443. while ($entryname = readdir($current_dir))
  1444. {
  1445. if (in_array($entryname, array('.', '..')))
  1446. continue;
  1447. if (isset($package_ftp))
  1448. $ftp_file = strtr($destination . '/' . $entryname, array($_SESSION['pack_ftp']['root'] => ''));
  1449. if (is_file($source . '/' . $entryname))
  1450. {
  1451. if (isset($package_ftp) && !file_exists($destination . '/' . $entryname))
  1452. $package_ftp->create_file($ftp_file);
  1453. elseif (!file_exists($destination . '/' . $entryname))
  1454. @touch($destination . '/' . $entryname);
  1455. }
  1456. package_chmod($destination . '/' . $entryname);
  1457. if (is_dir($source . '/' . $entryname))
  1458. copytree($source . '/' . $entryname, $destination . '/' . $entryname);
  1459. elseif (file_exists($destination . '/' . $entryname))
  1460. package_put_contents($destination . '/' . $entryname, package_get_contents($source . '/' . $entryname));
  1461. else
  1462. copy($source . '/' . $entryname, $destination . '/' . $entryname);
  1463. }
  1464. closedir($current_dir);
  1465. }
  1466. /**
  1467. * @param string $path
  1468. * @param string $sub_path = ''
  1469. * @return array
  1470. */
  1471. function listtree($path, $sub_path = '')
  1472. {
  1473. $data = array();
  1474. $dir = @dir($path . $sub_path);
  1475. if (!$dir)
  1476. return array();
  1477. while ($entry = $dir->read())
  1478. {
  1479. if ($entry == '.' || $entry == '..')
  1480. continue;
  1481. if (is_dir($path . $sub_path . '/' . $entry))
  1482. $data = array_merge($data, listtree($path, $sub_path . '/' . $entry));
  1483. else
  1484. $data[] = array(
  1485. 'filename' => $sub_path == '' ? $entry : $sub_path . '/' . $entry,
  1486. 'size' => filesize($path . $sub_path . '/' . $entry),
  1487. 'skipped' => false,
  1488. );
  1489. }
  1490. $dir->close();
  1491. return $data;
  1492. }
  1493. /**
  1494. * Parses a xml-style modification file (file).
  1495. * @param string $file
  1496. * @param bool $testing = true tells it the modifications shouldn't actually be saved.
  1497. * @param bool $undo = false specifies that the modifications the file requests should be undone; this doesn't work with everything (regular expressions.)
  1498. * @param array $theme_paths = array()
  1499. * @return array an array of those changes made.
  1500. */
  1501. function parseModification($file, $testing = true, $undo = false, $theme_paths = array())
  1502. {
  1503. global $boarddir, $sourcedir, $settings, $txt, $modSettings, $package_ftp;
  1504. @set_time_limit(600);
  1505. loadClassFile('Class-Package.php');
  1506. $xml = new xmlArray(strtr($file, array("\r" => '')));
  1507. $actions = array();
  1508. $everything_found = true;
  1509. if (!$xml->exists('modification') || !$xml->exists('modification/file'))
  1510. {
  1511. $actions[] = array(
  1512. 'type' => 'error',
  1513. 'filename' => '-',
  1514. 'debug' => $txt['package_modification_malformed']
  1515. );
  1516. return $actions;
  1517. }
  1518. // Get the XML data.
  1519. $files = $xml->set('modification/file');
  1520. // Use this for holding all the template changes in this mod.
  1521. $template_changes = array();
  1522. // This is needed to hold the long paths, as they can vary...
  1523. $long_changes = array();
  1524. // First, we need to build the list of all the files likely to get changed.
  1525. foreach ($files as $file)
  1526. {
  1527. // What is the filename we're currently on?
  1528. $filename = parse_path(trim($file->fetch('@name')));
  1529. // Now, we need to work out whether this is even a template file...
  1530. foreach ($theme_paths as $id => $theme)
  1531. {
  1532. // If this filename is relative, if so take a guess at what it should be.
  1533. $real_filename = $filename;
  1534. if (strpos($filename, 'Themes') === 0)
  1535. $real_filename = $boarddir . '/' . $filename;
  1536. if (strpos($real_filename, $theme['theme_dir']) === 0)
  1537. {
  1538. $template_changes[$id][] = substr($real_filename, strlen($theme['theme_dir']) + 1);
  1539. $long_changes[$id][] = $filename;
  1540. }
  1541. }
  1542. }
  1543. // Custom themes to add.
  1544. $custom_themes_add = array();
  1545. // If we have some template changes, we need to build a master link of what new ones are required for the custom themes.
  1546. if (!empty($template_changes[1]))
  1547. {
  1548. foreach ($theme_paths as $id => $theme)
  1549. {
  1550. // Default is getting done anyway, so no need for involvement here.
  1551. if ($id == 1)
  1552. continue;
  1553. // For every template, do we want it? Yea, no, maybe?
  1554. foreach ($template_changes[1] as $index => $template_file)
  1555. {
  1556. // What, it exists and we haven't already got it?! Lordy, get it in!
  1557. if (file_exists($theme['theme_dir'] . '/' . $template_file) && (!isset($template_changes[$id]) || !in_array($template_file, $template_changes[$id])))
  1558. {
  1559. // Now let's add it to the "todo" list.
  1560. $custom_themes_add[$long_changes[1][$index]][$id] = $theme['theme_dir'] . '/' . $template_file;
  1561. }
  1562. }
  1563. }
  1564. }
  1565. foreach ($files as $file)
  1566. {
  1567. // This is the actual file referred to in the XML document...
  1568. $files_to_change = array(
  1569. 1 => parse_path(trim($file->fetch('@name'))),
  1570. );
  1571. // Sometimes though, we have some additional files for other themes, if we have add them to the mix.
  1572. if (isset($custom_themes_add[$files_to_change[1]]))
  1573. $files_to_change += $custom_themes_add[$files_to_change[1]];
  1574. // Now, loop through all the files we're changing, and, well, change them ;)
  1575. foreach ($files_to_change as $theme => $working_file)
  1576. {
  1577. if ($working_file[0] != '/' && $working_file[1] != ':')
  1578. {
  1579. trigger_error('parseModification(): The filename \'' . $working_file . '\' is not a full path!', E_USER_WARNING);
  1580. $working_file = $boarddir . '/' . $working_file;
  1581. }
  1582. // Doesn't exist - give an error or what?
  1583. if (!file_exists($working_file) && (!$file->exists('@error') || !in_array(trim($file->fetch('@error')), array('ignore', 'skip'))))
  1584. {
  1585. $actions[] = array(
  1586. 'type' => 'missing',
  1587. 'filename' => $working_file,
  1588. 'debug' => $txt['package_modification_missing']
  1589. );
  1590. $everything_found = false;
  1591. continue;
  1592. }
  1593. // Skip the file if it doesn't exist.
  1594. elseif (!file_exists($working_file) && $file->exists('@error') && trim($file->fetch('@error')) == 'skip')
  1595. {
  1596. $actions[] = array(
  1597. 'type' => 'skipping',
  1598. 'filename' => $working_file,
  1599. );
  1600. continue;
  1601. }
  1602. // Okay, we're creating this file then...?
  1603. elseif (!file_exists($working_file))
  1604. $working_data = '';
  1605. // Phew, it exists! Load 'er up!
  1606. else
  1607. $working_data = str_replace("\r", '', package_get_contents($working_file));
  1608. $actions[] = array(
  1609. 'type' => 'opened',
  1610. 'filename' => $working_file
  1611. );
  1612. $operations = $file->exists('operation') ? $file->set('operation') : array();
  1613. foreach ($operations as $operation)
  1614. {
  1615. // Convert operation to an array.
  1616. $actual_operation = array(
  1617. 'searches' => array(),
  1618. 'error' => $operation->exists('@error') && in_array(trim($operation->fetch('@error')), array('ignore', 'fatal', 'required')) ? trim($operation->fetch('@error')) : 'fatal',
  1619. );
  1620. // The 'add' parameter is used for all searches in this operation.
  1621. $add = $operation->exists('add') ? $operation->fetch('add') : '';
  1622. // Grab all search items of this operation (in most cases just 1).
  1623. $searches = $operation->set('search');
  1624. foreach ($searches as $i => $search)
  1625. $actual_operation['searches'][] = array(
  1626. 'position' => $search->exists('@position') && in_array(trim($search->fetch('@position')), array('before', 'after', 'replace', 'end')) ? trim($search->fetch('@position')) : 'replace',
  1627. 'is_reg_exp' => $search->exists('@regexp') && trim($search->fetch('@regexp')) === 'true',
  1628. 'loose_whitespace' => $search->exists('@whitespace') && trim($search->fetch('@whitespace')) === 'loose',
  1629. 'search' => $search->fetch('.'),
  1630. 'add' => $add,
  1631. 'preg_search' => '',
  1632. 'preg_replace' => '',
  1633. );
  1634. // At least one search should be defined.
  1635. if (empty($actual_operation['searches']))
  1636. {
  1637. $actions[] = array(
  1638. 'type' => 'failure',
  1639. 'filename' => $working_file,
  1640. 'search' => $search['search'],
  1641. 'is_custom' => $theme > 1 ? $theme : 0,
  1642. );
  1643. // Skip to the next operation.
  1644. continue;
  1645. }
  1646. // Reverse the operations in case of undoing stuff.
  1647. if ($undo)
  1648. {
  1649. foreach ($actual_operation['searches'] as $i => $search)
  1650. {
  1651. // Reverse modification of regular expressions are not allowed.
  1652. if ($search['is_reg_exp'])
  1653. {
  1654. if ($actual_operation['error'] === 'fatal')
  1655. $actions[] = array(
  1656. 'type' => 'failure',
  1657. 'filename' => $working_file,
  1658. 'search' => $search['search'],
  1659. 'is_custom' => $theme > 1 ? $theme : 0,
  1660. );
  1661. // Continue to the next operation.
  1662. continue 2;
  1663. }
  1664. // The replacement is now the search subject...
  1665. if ($search['position'] === 'replace' || $search['position'] === 'end')
  1666. $actual_operation['searches'][$i]['search'] = $search['add'];
  1667. else
  1668. {
  1669. // Reversing a before/after modification becomes a replacement.
  1670. $actual_operation['searches'][$i]['position'] = 'replace';
  1671. if ($search['position'] === 'before')
  1672. $actual_operation['searches'][$i]['search'] .= $search['add'];
  1673. elseif ($search['position'] === 'after')
  1674. $actual_operation['searches'][$i]['search'] = $search['add'] . $search['search'];
  1675. }
  1676. // ...and the search subject is now the replacement.
  1677. $actual_operation['searches'][$i]['add'] = $search['search'];
  1678. }
  1679. }
  1680. // Sort the search list so the replaces come before the add before/after's.
  1681. if (count($actual_operation['searches']) !== 1)
  1682. {
  1683. $replacements = array();
  1684. foreach ($actual_operation['searches'] as $i => $search)
  1685. {
  1686. if ($search['position'] === 'replace')
  1687. {
  1688. $replacements[] = $search;
  1689. unset($actual_operation['searches'][$i]);
  1690. }
  1691. }
  1692. $actual_operation['searches'] = array_merge($replacements, $actual_operation['searches']);
  1693. }
  1694. // Create regular expression replacements from each search.
  1695. foreach ($actual_operation['searches'] as $i => $search)
  1696. {
  1697. // Not much needed if the search subject is already a regexp.
  1698. if ($search['is_reg_exp'])
  1699. $actual_operation['searches'][$i]['preg_search'] = $search['search'];
  1700. else
  1701. {
  1702. // Make the search subject fit into a regular expression.
  1703. $actual_operation['searches'][$i]['preg_search'] = preg_quote($search['search'], '~');
  1704. // Using 'loose', a random amount of tabs and spaces may be used.
  1705. if ($search['loose_whitespace'])
  1706. $actual_operation['searches'][$i]['preg_search'] = preg_replace('~[ \t]+~', '[ \t]+', $actual_operation['searches'][$i]['preg_search']);
  1707. }
  1708. // Shuzzup. This is done so we can safely use a regular expression. ($0 is bad!!)
  1709. $actual_operation['searches'][$i]['preg_replace'] = strtr($search['add'], array('$' => '[$PACK' . 'AGE1$]', '\\' => '[$PACK' . 'AGE2$]'));
  1710. // Before, so the replacement comes after the search subject :P
  1711. if ($search['position'] === 'before')
  1712. {
  1713. $actual_operation['searches'][$i]['preg_search'] = '(' . $actual_operation['searches'][$i]['preg_search'] . ')';
  1714. $actual_operation['searches'][$i]['preg_replace'] = '$1' . $actual_operation['searches'][$i]['preg_replace'];
  1715. }
  1716. // After, after what?
  1717. elseif ($search['position'] === 'after')
  1718. {
  1719. $actual_operation['searches'][$i]['preg_search'] = '(' . $actual_operation['searches'][$i]['preg_search'] . ')';
  1720. $actual_operation['searches'][$i]['preg_replace'] .= '$1';
  1721. }
  1722. // Position the replacement at the end of the file (or just before the closing PHP tags).
  1723. elseif ($search['position'] === 'end')
  1724. {
  1725. if ($undo)
  1726. {
  1727. $actual_operation['searches'][$i]['preg_replace'] = '';
  1728. }
  1729. else
  1730. {
  1731. $actual_operation['searches'][$i]['preg_search'] = '(\\n\\?\\>)?$';
  1732. $actual_operation['searches'][$i]['preg_replace'] .= '$1';
  1733. }
  1734. }
  1735. // Testing 1, 2, 3...
  1736. $failed = preg_match('~' . $actual_operation['searches'][$i]['preg_search'] . '~s', $working_data) === 0;
  1737. // Nope, search pattern not found.
  1738. if ($failed && $actual_operation['error'] === 'fatal')
  1739. {
  1740. $actions[] = array(
  1741. 'type' => 'failure',
  1742. 'filename' => $working_file,
  1743. 'search' => $actual_operation['searches'][$i]['preg_search'],
  1744. 'search_original' => $actual_operation['searches'][$i]['search'],
  1745. 'replace_original' => $actual_operation['searches'][$i]['add'],
  1746. 'position' => $search['position'],
  1747. 'is_custom' => $theme > 1 ? $theme : 0,
  1748. 'failed' => $failed,
  1749. );
  1750. $everything_found = false;
  1751. continue;
  1752. }
  1753. // Found, but in this case, that means failure!
  1754. elseif (!$failed && $actual_operation['error'] === 'required')
  1755. {
  1756. $actions[] = array(
  1757. 'type' => 'failure',
  1758. 'filename' => $working_file,
  1759. 'search' => $actual_operation['searches'][$i]['preg_search'],
  1760. 'search_original' => $actual_operation['searches'][$i]['search'],
  1761. 'replace_original' => $actual_operation['searches'][$i]['add'],
  1762. 'position' => $search['position'],
  1763. 'is_custom' => $theme > 1 ? $theme : 0,
  1764. 'failed' => $failed,
  1765. );
  1766. $everything_found = false;
  1767. continue;
  1768. }
  1769. // Replace it into nothing? That's not an option...unless it's an undoing end.
  1770. if ($search['add'] === '' && ($search['position'] !== 'end' || !$undo))
  1771. continue;
  1772. // Finally, we're doing some replacements.
  1773. $working_data = preg_replace('~' . $actual_operation['searches'][$i]['preg_search'] . '~s', $actual_operation['searches'][$i]['preg_replace'], $working_data, 1);
  1774. $actions[] = array(
  1775. 'type' => 'replace',
  1776. 'filename' => $working_file,
  1777. 'search' => $actual_operation['searches'][$i]['preg_search'],
  1778. 'replace' => $actual_operation['searches'][$i]['preg_replace'],
  1779. 'search_original' => $actual_operation['searches'][$i]['search'],
  1780. 'replace_original' => $actual_operation['searches'][$i]['add'],
  1781. 'position' => $search['position'],
  1782. 'failed' => $failed,
  1783. 'ignore_failure' => $failed && $actual_operation['error'] === 'ignore',
  1784. 'is_custom' => $theme > 1 ? $theme : 0,
  1785. );
  1786. }
  1787. }
  1788. // Fix any little helper symbols ;).
  1789. $working_data = strtr($working_data, array('[$PACK' . 'AGE1$]' => '$', '[$PACK' . 'AGE2$]' => '\\'));
  1790. package_chmod($working_file);
  1791. if ((file_exists($working_file) && !is_writable($working_file)) || (!file_exists($working_file) && !is_writable(dirname($working_file))))
  1792. $actions[] = array(
  1793. 'type' => 'chmod',
  1794. 'filename' => $working_file
  1795. );
  1796. if (basename($working_file) == 'Settings_bak.php')
  1797. continue;
  1798. if (!$testing && !empty($modSettings['package_make_backups']) && file_exists($working_file))
  1799. {
  1800. // No, no, not Settings.php!
  1801. if (basename($working_file) == 'Settings.php')
  1802. @copy($working_file, dirname($working_file) . '/Settings_bak.php');
  1803. else
  1804. @copy($working_file, $working_file . '~');
  1805. }
  1806. // Always call this, even if in testing, because it won't really be written in testing mode.
  1807. package_put_contents($working_file, $working_data, $testing);
  1808. $actions[] = array(
  1809. 'type' => 'saved',
  1810. 'filename' => $working_file,
  1811. 'is_custom' => $theme > 1 ? $theme : 0,
  1812. );
  1813. }
  1814. }
  1815. $actions[] = array(
  1816. 'type' => 'result',
  1817. 'status' => $everything_found
  1818. );
  1819. return $actions;
  1820. }
  1821. /**
  1822. * Parses a boardmod-style modification file (file).
  1823. * @param string $file
  1824. * @param bool $testing = true tells it the modifications shouldn't actually be saved.
  1825. * @param bool $undo = false specifies that the modifications the file requests should be undone.
  1826. * @param array $theme_paths = array()
  1827. * @return array an array of those changes made.
  1828. */
  1829. function parseBoardMod($file, $testing = true, $undo = false, $theme_paths = array())
  1830. {
  1831. global $boarddir, $sourcedir, $settings, $txt, $modSettings;
  1832. @set_time_limit(600);
  1833. $file = strtr($file, array("\r" => ''));
  1834. $working_file = null;
  1835. $working_search = null;
  1836. $working_data = '';
  1837. $replace_with = null;
  1838. $actions = array();
  1839. $everything_found = true;
  1840. // This holds all the template changes in the standard mod file.
  1841. $template_changes = array();
  1842. // This is just the temporary file.
  1843. $temp_file = $file;
  1844. // This holds the actual changes on a step counter basis.
  1845. $temp_changes = array();
  1846. $counter = 0;
  1847. $step_counter = 0;
  1848. // Before we do *anything*, let's build a list of what we're editing, as it's going to be used for other theme edits.
  1849. while (preg_match('~<(edit file|file|search|search for|add|add after|replace|add before|add above|above|before)>\n(.*?)\n</\\1>~is', $temp_file, $code_match) != 0)
  1850. {
  1851. $counter++;
  1852. // Get rid of the old stuff.
  1853. $temp_file = substr_replace($temp_file, '', strpos($temp_file, $code_match[0]), strlen($code_match[0]));
  1854. // No interest to us?
  1855. if ($code_match[1] != 'edit file' && $code_match[1] != 'file')
  1856. {
  1857. // It's a step, let's add that to the current steps.
  1858. if (isset($temp_changes[$step_counter]))
  1859. $temp_changes[$step_counter]['changes'][] = $code_match[0];
  1860. continue;
  1861. }
  1862. // We've found a new edit - let's make ourself heard, kind of.
  1863. $step_counter = $counter;
  1864. $temp_changes[$step_counter] = array(
  1865. 'title' => $code_match[0],
  1866. 'changes' => array(),
  1867. );
  1868. $filename = parse_path($code_match[2]);
  1869. // Now, is this a template file, and if so, which?
  1870. foreach ($theme_paths as $id => $theme)
  1871. {
  1872. // If this filename is relative, if so take a guess at what it should be.
  1873. if (strpos($filename, 'Themes') === 0)
  1874. $filename = $boarddir . '/' . $filename;
  1875. if (strpos($filename, $theme['theme_dir']) === 0)
  1876. $template_changes[$id][$counter] = substr($filename, strlen($theme['theme_dir']) + 1);
  1877. }
  1878. }
  1879. // Anything above $counter must be for custom themes.
  1880. $custom_template_begin = $counter;
  1881. // Reference for what theme ID this action belongs to.
  1882. $theme_id_ref = array();
  1883. // Now we know what templates we need to touch, cycle through each theme and work out what we need to edit.
  1884. if (!empty($template_changes[1]))
  1885. {
  1886. foreach ($theme_paths as $id => $theme)
  1887. {
  1888. // Don't do default, it means nothing to me.
  1889. if ($id == 1)
  1890. continue;
  1891. // Now, for each file do we need to edit it?
  1892. foreach ($template_changes[1] as $pos => $template_file)
  1893. {
  1894. // It does? Add it to the list darlin'.
  1895. if (file_exists($theme['theme_dir'] . '/' . $template_file) && (!isset($template_changes[$id][$pos]) || !in_array($template_file, $template_changes[$id][$pos])))
  1896. {
  1897. // Actually add it to the mod file too, so we can see that it will work ;)
  1898. if (!empty($temp_changes[$pos]['changes']))
  1899. {
  1900. $file .= "\n\n" . '<edit file>' . "\n" . $theme['theme_dir'] . '/' . $template_file . "\n" . '</edit file>' . "\n\n" . implode("\n\n", $temp_changes[$pos]['changes']);
  1901. $theme_id_ref[$counter] = $id;
  1902. $counter += 1 + count($temp_changes[$pos]['changes']);
  1903. }
  1904. }
  1905. }
  1906. }
  1907. }
  1908. $counter = 0;
  1909. $is_custom = 0;
  1910. while (preg_match('~<(edit file|file|search|search for|add|add after|replace|add before|add above|above|before)>\n(.*?)\n</\\1>~is', $file, $code_match) != 0)
  1911. {
  1912. // This is for working out what we should be editing.
  1913. $counter++;
  1914. // Edit a specific file.
  1915. if ($code_match[1] == 'file' || $code_match[1] == 'edit file')
  1916. {
  1917. // Backup the old file.
  1918. if ($working_file !== null)
  1919. {
  1920. package_chmod($working_file);
  1921. // Don't even dare.
  1922. if (basename($working_file) == 'Settings_bak.php')
  1923. continue;
  1924. if (!is_writable($working_file))
  1925. $actions[] = array(
  1926. 'type' => 'chmod',
  1927. 'filename' => $working_file
  1928. );
  1929. if (!$testing && !empty($modSettings['package_make_backups']) && file_exists($working_file))
  1930. {
  1931. if (basename($working_file) == 'Settings.php')
  1932. @copy($working_file, dirname($working_file) . '/Settings_bak.php');
  1933. else
  1934. @copy($working_file, $working_file . '~');
  1935. }
  1936. package_put_contents($working_file, $working_data, $testing);
  1937. }
  1938. if ($working_file !== null)
  1939. $actions[] = array(
  1940. 'type' => 'saved',
  1941. 'filename' => $working_file,
  1942. 'is_custom' => $is_custom,
  1943. );
  1944. // Is this "now working on" file a theme specific one?
  1945. $is_custom = isset($theme_id_ref[$counter - 1]) ? $theme_id_ref[$counter - 1] : 0;
  1946. // Make sure the file exists!
  1947. $working_file = parse_path($code_match[2]);
  1948. if ($working_file[0] != '/' && $working_file[1] != ':')
  1949. {
  1950. trigger_error('parseBoardMod(): The filename \'' . $working_file . '\' is not a full path!', E_USER_WARNING);
  1951. $working_file = $boarddir . '/' . $working_file;
  1952. }
  1953. if (!file_exists($working_file))
  1954. {
  1955. $places_to_check = array($boarddir, $sourcedir, $settings['default_theme_dir'], $settings['default_theme_dir'] . '/languages');
  1956. foreach ($places_to_check as $place)
  1957. if (file_exists($place . '/' . $working_file))
  1958. {
  1959. $working_file = $place . '/' . $working_file;
  1960. break;
  1961. }
  1962. }
  1963. if (file_exists($working_file))
  1964. {
  1965. // Load the new file.
  1966. $working_data = str_replace("\r", '', package_get_contents($working_file));
  1967. $actions[] = array(
  1968. 'type' => 'opened',
  1969. 'filename' => $working_file
  1970. );
  1971. }
  1972. else
  1973. {
  1974. $actions[] = array(
  1975. 'type' => 'missing',
  1976. 'filename' => $working_file
  1977. );
  1978. $working_file = null;
  1979. $everything_found = false;
  1980. }
  1981. // Can't be searching for something...
  1982. $working_search = null;
  1983. }
  1984. // Search for a specific string.
  1985. elseif (($code_match[1] == 'search' || $code_match[1] == 'search for') && $working_file !== null)
  1986. {
  1987. if ($working_search !== null)
  1988. {
  1989. $actions[] = array(
  1990. 'type' => 'error',
  1991. 'filename' => $working_file
  1992. );
  1993. $everything_found = false;
  1994. }
  1995. $working_search = $code_match[2];
  1996. }
  1997. // Must've already loaded a search string.
  1998. elseif ($working_search !== null)
  1999. {
  2000. // This is the base string....
  2001. $replace_with = $code_match[2];
  2002. // Add this afterward...
  2003. if ($code_match[1] == 'add' || $code_match[1] == 'add after')
  2004. $replace_with = $working_search . "\n" . $replace_with;
  2005. // Add this beforehand.
  2006. elseif ($code_match[1] == 'before' || $code_match[1] == 'add before' || $code_match[1] == 'above' || $code_match[1] == 'add above')
  2007. $replace_with .= "\n" . $working_search;
  2008. // Otherwise.. replace with $replace_with ;).
  2009. }
  2010. // If we have a search string, replace string, and open file..
  2011. if ($working_search !== null && $replace_with !== null && $working_file !== null)
  2012. {
  2013. // Make sure it's somewhere in the string.
  2014. if ($undo)
  2015. {
  2016. $temp = $replace_with;
  2017. $replace_with = $working_search;
  2018. $working_search = $temp;
  2019. }
  2020. if (strpos($working_data, $working_search) !== false)
  2021. {
  2022. $working_data = str_replace($working_search, $replace_with, $working_data);
  2023. $actions[] = array(
  2024. 'type' => 'replace',
  2025. 'filename' => $working_file,
  2026. 'search' => $working_search,
  2027. 'replace' => $replace_with,
  2028. 'search_original' => $working_search,
  2029. 'replace_original' => $replace_with,
  2030. 'position' => $code_match[1] == 'replace' ? 'replace' : ($code_match[1] == 'add' || $code_match[1] == 'add after' ? 'before' : 'after'),
  2031. 'is_custom' => $is_custom,
  2032. 'failed' => false,
  2033. );
  2034. }
  2035. // It wasn't found!
  2036. else
  2037. {
  2038. $actions[] = array(
  2039. 'type' => 'failure',
  2040. 'filename' => $working_file,
  2041. 'search' => $working_search,
  2042. 'is_custom' => $is_custom,
  2043. 'search_original' => $working_search,
  2044. 'replace_original' => $replace_with,
  2045. 'position' => $code_match[1] == 'replace' ? 'replace' : ($code_match[1] == 'add' || $code_match[1] == 'add after' ? 'before' : 'after'),
  2046. 'is_custom' => $is_custom,
  2047. 'failed' => true,
  2048. );
  2049. $everything_found = false;
  2050. }
  2051. // These don't hold any meaning now.
  2052. $working_search = null;
  2053. $replace_with = null;
  2054. }
  2055. // Get rid of the old tag.
  2056. $file = substr_replace($file, '', strpos($file, $code_match[0]), strlen($code_match[0]));
  2057. }
  2058. // Backup the old file.
  2059. if ($working_file !== null)
  2060. {
  2061. package_chmod($working_file);
  2062. if (!is_writable($working_file))
  2063. $actions[] = array(
  2064. 'type' => 'chmod',
  2065. 'filename' => $working_file
  2066. );
  2067. if (!$testing && !empty($modSettings['package_make_backups']) && file_exists($working_file))
  2068. {
  2069. if (basename($working_file) == 'Settings.php')
  2070. @copy($working_file, dirname($working_file) . '/Settings_bak.php');
  2071. else
  2072. @copy($working_file, $working_file . '~');
  2073. }
  2074. package_put_contents($working_file, $working_data, $testing);
  2075. }
  2076. if ($working_file !== null)
  2077. $actions[] = array(
  2078. 'type' => 'saved',
  2079. 'filename' => $working_file,
  2080. 'is_custom' => $is_custom,
  2081. );
  2082. $actions[] = array(
  2083. 'type' => 'result',
  2084. 'status' => $everything_found
  2085. );
  2086. return $actions;
  2087. }
  2088. function package_get_contents($filename)
  2089. {
  2090. global $package_cache, $modSettings;
  2091. if (!isset($package_cache))
  2092. {
  2093. // Windows doesn't seem to care about the memory_limit.
  2094. if (!empty($modSettings['package_disable_cache']) || ini_set('memory_limit', '128M') !== false || strpos(strtolower(PHP_OS), 'win') !== false)
  2095. $package_cache = array();
  2096. else
  2097. $package_cache = false;
  2098. }
  2099. if (strpos($filename, 'Packages/') !== false || $package_cache === false || !isset($package_cache[$filename]))
  2100. return file_get_contents($filename);
  2101. else
  2102. return $package_cache[$filename];
  2103. }
  2104. /**
  2105. * Writes data to a file, almost exactly like the file_put_contents() function.
  2106. * uses FTP to create/chmod the file when necessary and available.
  2107. * uses text mode for text mode file extensions.
  2108. * returns the number of bytes written.
  2109. * @param string $filename
  2110. * @param string $data
  2111. * @return int
  2112. */
  2113. function package_put_contents($filename, $data, $testing = false)
  2114. {
  2115. global $package_ftp, $package_cache, $modSettings;
  2116. static $text_filetypes = array('php', 'txt', '.js', 'css', 'vbs', 'tml', 'htm');
  2117. if (!isset($package_cache))
  2118. {
  2119. // Try to increase the memory limit - we don't want to run out of ram!
  2120. if (!empty($modSettings['package_disable_cache']) || ini_set('memory_limit', '128M') !== false || strpos(strtolower(PHP_OS), 'win') !== false)
  2121. $package_cache = array();
  2122. else
  2123. $package_cache = false;
  2124. }
  2125. if (isset($package_ftp))
  2126. $ftp_file = strtr($filename, array($_SESSION['pack_ftp']['root'] => ''));
  2127. if (!file_exists($filename) && isset($package_ftp))
  2128. $package_ftp->create_file($ftp_file);
  2129. elseif (!file_exists($filename))
  2130. @touch($filename);
  2131. package_chmod($filename);
  2132. if (!$testing && (strpos($filename, 'Packages/') !== false || $package_cache === false))
  2133. {
  2134. $fp = @fopen($filename, in_array(substr($filename, -3), $text_filetypes) ? 'w' : 'wb');
  2135. // We should show an error message or attempt a rollback, no?
  2136. if (!$fp)
  2137. return false;
  2138. fwrite($fp, $data);
  2139. fclose($fp);
  2140. }
  2141. elseif (strpos($filename, 'Packages/') !== false || $package_cache === false)
  2142. return strlen($data);
  2143. else
  2144. {
  2145. $package_cache[$filename] = $data;
  2146. // Permission denied, eh?
  2147. $fp = @fopen($filename, 'r+');
  2148. if (!$fp)
  2149. return false;
  2150. fclose($fp);
  2151. }
  2152. return strlen($data);
  2153. }
  2154. function package_flush_cache($trash = false)
  2155. {
  2156. global $package_ftp, $package_cache;
  2157. static $text_filetypes = array('php', 'txt', '.js', 'css', 'vbs', 'tml', 'htm');
  2158. if (empty($package_cache))
  2159. return;
  2160. // First, let's check permissions!
  2161. foreach ($package_cache as $filename => $data)
  2162. {
  2163. if (isset($package_ftp))
  2164. $ftp_file = strtr($filename, array($_SESSION['pack_ftp']['root'] => ''));
  2165. if (!file_exists($filename) && isset($package_ftp))
  2166. $package_ftp->create_file($ftp_file);
  2167. elseif (!file_exists($filename))
  2168. @touch($filename);
  2169. package_chmod($filename);
  2170. $fp = fopen($filename, 'r+');
  2171. if (!$fp && !$trash)
  2172. {
  2173. // We should have package_chmod()'d them before, no?!
  2174. trigger_error('package_flush_cache(): some files are still not writable', E_USER_WARNING);
  2175. return;
  2176. }
  2177. fclose($fp);
  2178. }
  2179. if ($trash)
  2180. {
  2181. $package_cache = array();
  2182. return;
  2183. }
  2184. foreach ($package_cache as $filename => $data)
  2185. {
  2186. $fp = fopen($filename, in_array(substr($filename, -3), $text_filetypes) ? 'w' : 'wb');
  2187. fwrite($fp, $data);
  2188. fclose($fp);
  2189. }
  2190. $package_cache = array();
  2191. }
  2192. /**
  2193. * Try to make a file writable.
  2194. * @param string $filename
  2195. * @param string $perm_state = 'writable'
  2196. * @param bool $track_change = false
  2197. * @return bool True if it worked, false if it didn't
  2198. */
  2199. function package_chmod($filename, $perm_state = 'writable', $track_change = false)
  2200. {
  2201. global $package_ftp;
  2202. if (file_exists($filename) && is_writable($filename) && $perm_state == 'writable')
  2203. return true;
  2204. // Start off checking without FTP.
  2205. if (!isset($package_ftp) || $package_ftp === false)
  2206. {
  2207. for ($i = 0; $i < 2; $i++)
  2208. {
  2209. $chmod_file = $filename;
  2210. // Start off with a less agressive test.
  2211. if ($i == 0)
  2212. {
  2213. // If this file doesn't exist, then we actually want to look at whatever parent directory does.
  2214. $subTraverseLimit = 2;
  2215. while (!file_exists($chmod_file) && $subTraverseLimit)
  2216. {
  2217. $chmod_file = dirname($chmod_file);
  2218. $subTraverseLimit--;
  2219. }
  2220. // Keep track of the writable status here.
  2221. $file_permissions = @fileperms($chmod_file);
  2222. }
  2223. else
  2224. {
  2225. // This looks odd, but it's an attempt to work around PHP suExec.
  2226. if (!file_exists($chmod_file) && $perm_state == 'writable')
  2227. {
  2228. $file_permissions = @fileperms(dirname($chmod_file));
  2229. mktree(dirname($chmod_file), 0755);
  2230. @touch($chmod_file);
  2231. @chmod($chmod_file, 0755);
  2232. }
  2233. else
  2234. $file_permissions = @fileperms($chmod_file);
  2235. }
  2236. // This looks odd, but it's another attempt to work around PHP suExec.
  2237. if ($perm_state != 'writable')
  2238. @chmod($chmod_file, $perm_state == 'execute' ? 0755 : 0644);
  2239. else
  2240. {
  2241. if (!@is_writable($chmod_file))
  2242. @chmod($chmod_file, 0755);
  2243. if (!@is_writable($chmod_file))
  2244. @chmod($chmod_file, 0777);
  2245. if (!@is_writable(dirname($chmod_file)))
  2246. @chmod($chmod_file, 0755);
  2247. if (!@is_writable(dirname($chmod_file)))
  2248. @chmod($chmod_file, 0777);
  2249. }
  2250. // The ultimate writable test.
  2251. if ($perm_state == 'writable')
  2252. {
  2253. $fp = is_dir($chmod_file) ? @opendir($chmod_file) : @fopen($chmod_file, 'rb');
  2254. if (@is_writable($chmod_file) && $fp)
  2255. {
  2256. if (!is_dir($chmod_file))
  2257. fclose($fp);
  2258. else
  2259. closedir($fp);
  2260. // It worked!
  2261. if ($track_change)
  2262. $_SESSION['pack_ftp']['original_perms'][$chmod_file] = $file_permissions;
  2263. return true;
  2264. }
  2265. }
  2266. elseif ($perm_state != 'writable' && isset($_SESSION['pack_ftp']['original_perms'][$chmod_file]))
  2267. unset($_SESSION['pack_ftp']['original_perms'][$chmod_file]);
  2268. }
  2269. // If we're here we're a failure.
  2270. return false;
  2271. }
  2272. // Otherwise we do have FTP?
  2273. elseif ($package_ftp !== false && !empty($_SESSION['pack_ftp']))
  2274. {
  2275. $ftp_file = strtr($filename, array($_SESSION['pack_ftp']['root'] => ''));
  2276. // This looks odd, but it's an attempt to work around PHP suExec.
  2277. if (!file_exists($filename) && $perm_state == 'writable')
  2278. {
  2279. $file_permissions = @fileperms(dirname($filename));
  2280. mktree(dirname($filename), 0755);
  2281. $package_ftp->create_file($ftp_file);
  2282. $package_ftp->chmod($ftp_file, 0755);
  2283. }
  2284. else
  2285. $file_permissions = @fileperms($filename);
  2286. if ($perm_state != 'writable')
  2287. {
  2288. $package_ftp->chmod($ftp_file, $perm_state == 'execute' ? 0755 : 0644);
  2289. }
  2290. else
  2291. {
  2292. if (!@is_writable($filename))
  2293. $package_ftp->chmod($ftp_file, 0777);
  2294. if (!@is_writable(dirname($filename)))
  2295. $package_ftp->chmod(dirname($ftp_file), 0777);
  2296. }
  2297. if (@is_writable($filename))
  2298. {
  2299. if ($track_change)
  2300. $_SESSION['pack_ftp']['original_perms'][$filename] = $file_permissions;
  2301. return true;
  2302. }
  2303. elseif ($perm_state != 'writable' && isset($_SESSION['pack_ftp']['original_perms'][$filename]))
  2304. unset($_SESSION['pack_ftp']['original_perms'][$filename]);
  2305. }
  2306. // Oh dear, we failed if we get here.
  2307. return false;
  2308. }
  2309. /**
  2310. * @param string $pass
  2311. * @return string The encrypted password
  2312. */
  2313. function package_crypt($pass)
  2314. {
  2315. $n = strlen($pass);
  2316. $salt = session_id();
  2317. while (strlen($salt) < $n)
  2318. $salt .= session_id();
  2319. for ($i = 0; $i < $n; $i++)
  2320. $pass{$i} = chr(ord($pass{$i}) ^ (ord($salt{$i}) - 32));
  2321. return $pass;
  2322. }
  2323. /**
  2324. * @todo Document this
  2325. * @param string $id
  2326. */
  2327. function package_create_backup($id = 'backup')
  2328. {
  2329. global $sourcedir, $boarddir, $smcFunc;
  2330. $files = array();
  2331. $base_files = array('index.php', 'SSI.php', 'agreement.txt', 'ssi_examples.php', 'ssi_examples.shtml', 'subscriptions.php');
  2332. foreach ($base_files as $file)
  2333. {
  2334. if (file_exists($boarddir . '/' . $file))
  2335. $files[realpath($boarddir . '/' . $file)] = array(
  2336. empty($_REQUEST['use_full_paths']) ? $file : $boarddir . '/' . $file,
  2337. stat($boarddir . '/' . $file)
  2338. );
  2339. }
  2340. $dirs = array(
  2341. $sourcedir => empty($_REQUEST['use_full_paths']) ? 'Sources/' : strtr($sourcedir . '/', '\\', '/')
  2342. );
  2343. $request = $smcFunc['db_query']('', '
  2344. SELECT value
  2345. FROM {db_prefix}themes
  2346. WHERE id_member = {int:no_member}
  2347. AND variable = {string:theme_dir}',
  2348. array(
  2349. 'no_member' => 0,
  2350. 'theme_dir' => 'theme_dir',
  2351. )
  2352. );
  2353. while ($row = $smcFunc['db_fetch_assoc']($request))
  2354. $dirs[$row['value']] = empty($_REQUEST['use_full_paths']) ? 'Themes/' . basename($row['value']) . '/' : strtr($row['value'] . '/', '\\', '/');
  2355. $smcFunc['db_free_result']($request);
  2356. while (!empty($dirs))
  2357. {
  2358. list ($dir, $dest) = each($dirs);
  2359. unset($dirs[$dir]);
  2360. $listing = @dir($dir);
  2361. if (!$listing)
  2362. continue;
  2363. while ($entry = $listing->read())
  2364. {
  2365. if (preg_match('~^(\.{1,2}|CVS|backup.*|help|images|.*\~)$~', $entry) != 0)
  2366. continue;
  2367. $filepath = realpath($dir . '/' . $entry);
  2368. if (isset($files[$filepath]))
  2369. continue;
  2370. $stat = stat($dir . '/' . $entry);
  2371. if ($stat['mode'] & 040000)
  2372. {
  2373. $files[$filepath] = array($dest . $entry . '/', $stat);
  2374. $dirs[$dir . '/' . $entry] = $dest . $entry . '/';
  2375. }
  2376. else
  2377. $files[$filepath] = array($dest . $entry, $stat);
  2378. }
  2379. $listing->close();
  2380. }
  2381. if (!file_exists($boarddir . '/Packages/backups'))
  2382. mktree($boarddir . '/Packages/backups', 0777);
  2383. if (!is_writable($boarddir . '/Packages/backups'))
  2384. package_chmod($boarddir . '/Packages/backups');
  2385. $output_file = $boarddir . '/Packages/backups/' . strftime('%Y-%m-%d_') . preg_replace('~[$\\\\/:<>|?*"\']~', '', $id);
  2386. $output_ext = '.tar' . (function_exists('gzopen') ? '.gz' : '');
  2387. if (file_exists($output_file . $output_ext))
  2388. {
  2389. $i = 2;
  2390. while (file_exists($output_file . '_' . $i . $output_ext))
  2391. $i++;
  2392. $output_file = $output_file . '_' . $i . $output_ext;
  2393. }
  2394. else
  2395. $output_file .= $output_ext;
  2396. @set_time_limit(300);
  2397. if (function_exists('apache_reset_timeout'))
  2398. @apache_reset_timeout();
  2399. if (function_exists('gzopen'))
  2400. {
  2401. $fwrite = 'gzwrite';
  2402. $fclose = 'gzclose';
  2403. $output = gzopen($output_file, 'wb');
  2404. }
  2405. else
  2406. {
  2407. $fwrite = 'fwrite';
  2408. $fclose = 'fclose';
  2409. $output = fopen($output_file, 'wb');
  2410. }
  2411. foreach ($files as $real_file => $file)
  2412. {
  2413. if (!file_exists($real_file))
  2414. continue;
  2415. $stat = $file[1];
  2416. if (substr($file[0], -1) == '/')
  2417. $stat['size'] = 0;
  2418. $current = pack('a100a8a8a8a12a12a8a1a100a6a2a32a32a8a8a155a12', $file[0], decoct($stat['mode']), sprintf('%06d', decoct($stat['uid'])), sprintf('%06d', decoct($stat['gid'])), decoct($stat['size']), decoct($stat['mtime']), '', 0, '', '', '', '', '', '', '', '', '');
  2419. $checksum = 256;
  2420. for ($i = 0; $i < 512; $i++)
  2421. $checksum += ord($current{$i});
  2422. $fwrite($output, substr($current, 0, 148) . pack('a8', decoct($checksum)) . substr($current, 156, 511));
  2423. if ($stat['size'] == 0)
  2424. continue;
  2425. $fp = fopen($real_file, 'rb');
  2426. while (!feof($fp))
  2427. $fwrite($output, fread($fp, 16384));
  2428. fclose($fp);
  2429. $fwrite($output, pack('a' . (512 - $stat['size'] % 512), ''));
  2430. }
  2431. $fwrite($output, pack('a1024', ''));
  2432. $fclose($output);
  2433. }
  2434. /**
  2435. * Get the contents of a URL, irrespective of allow_url_fopen.
  2436. * @param string $url
  2437. * @param string $post_data = ''
  2438. * @param bool $keep_alive = false
  2439. * @param $redirection_level = 0
  2440. * @return string
  2441. */
  2442. function fetch_web_data($url, $post_data = '', $keep_alive = false, $redirection_level = 0)
  2443. {
  2444. global $webmaster_email;
  2445. static $keep_alive_dom = null, $keep_alive_fp = null;
  2446. preg_match('~^(http|ftp)(s)?://([^/:]+)(:(\d+))?(.+)$~', $url, $match);
  2447. // An FTP url. We should try connecting and RETRieving it...
  2448. if (empty($match[1]))
  2449. return false;
  2450. elseif ($match[1] == 'ftp')
  2451. {
  2452. // Include the file containing the ftp_connection class.
  2453. loadClassFile('Class-Package.php');
  2454. // Establish a connection and attempt to enable passive mode.
  2455. $ftp = new ftp_connection(($match[2] ? 'ssl://' : '') . $match[3], empty($match[5]) ? 21 : $match[5], 'anonymous', $webmaster_email);
  2456. if ($ftp->error !== false || !$ftp->passive())
  2457. return false;
  2458. // I want that one *points*!
  2459. fwrite($ftp->connection, 'RETR ' . $match[6] . "\r\n");
  2460. // Since passive mode worked (or we would have returned already!) open the connection.
  2461. $fp = @fsockopen($ftp->pasv['ip'], $ftp->pasv['port'], $err, $err, 5);
  2462. if (!$fp)
  2463. return false;
  2464. // The server should now say something in acknowledgement.
  2465. $ftp->check_response(150);
  2466. $data = '';
  2467. while (!feof($fp))
  2468. $data .= fread($fp, 4096);
  2469. fclose($fp);
  2470. // All done, right? Good.
  2471. $ftp->check_response(226);
  2472. $ftp->close();
  2473. }
  2474. // This is more likely; a standard HTTP URL.
  2475. elseif (isset($match[1]) && $match[1] == 'http')
  2476. {
  2477. if ($keep_alive && $match[3] == $keep_alive_dom)
  2478. $fp = $keep_alive_fp;
  2479. if (empty($fp))
  2480. {
  2481. // Open the socket on the port we want...
  2482. $fp = @fsockopen(($match[2] ? 'ssl://' : '') . $match[3], empty($match[5]) ? ($match[2] ? 443 : 80) : $match[5], $err, $err, 5);
  2483. if (!$fp)
  2484. return false;
  2485. }
  2486. if ($keep_alive)
  2487. {
  2488. $keep_alive_dom = $match[3];
  2489. $keep_alive_fp = $fp;
  2490. }
  2491. // I want this, from there, and I'm not going to be bothering you for more (probably.)
  2492. if (empty($post_data))
  2493. {
  2494. fwrite($fp, 'GET ' . $match[6] . ' HTTP/1.0' . "\r\n");
  2495. fwrite($fp, 'Host: ' . $match[3] . (empty($match[5]) ? ($match[2] ? ':443' : '') : ':' . $match[5]) . "\r\n");
  2496. fwrite($fp, 'User-Agent: PHP/SMF' . "\r\n");
  2497. if ($keep_alive)
  2498. fwrite($fp, 'Connection: Keep-Alive' . "\r\n\r\n");
  2499. else
  2500. fwrite($fp, 'Connection: close' . "\r\n\r\n");
  2501. }
  2502. else
  2503. {
  2504. fwrite($fp, 'POST ' . $match[6] . ' HTTP/1.0' . "\r\n");
  2505. fwrite($fp, 'Host: ' . $match[3] . (empty($match[5]) ? ($match[2] ? ':443' : '') : ':' . $match[5]) . "\r\n");
  2506. fwrite($fp, 'User-Agent: PHP/SMF' . "\r\n");
  2507. if ($keep_alive)
  2508. fwrite($fp, 'Connection: Keep-Alive' . "\r\n");
  2509. else
  2510. fwrite($fp, 'Connection: close' . "\r\n");
  2511. fwrite($fp, 'Content-Type: application/x-www-form-urlencoded' . "\r\n");
  2512. fwrite($fp, 'Content-Length: ' . strlen($post_data) . "\r\n\r\n");
  2513. fwrite($fp, $post_data);
  2514. }
  2515. $response = fgets($fp, 768);
  2516. // Redirect in case this location is permanently or temporarily moved.
  2517. if ($redirection_level < 3 && preg_match('~^HTTP/\S+\s+30[127]~i', $response) === 1)
  2518. {
  2519. $header = '';
  2520. $location = '';
  2521. while (!feof($fp) && trim($header = fgets($fp, 4096)) != '')
  2522. if (strpos($header, 'Location:') !== false)
  2523. $location = trim(substr($header, strpos($header, ':') + 1));
  2524. if (empty($location))
  2525. return false;
  2526. else
  2527. {
  2528. if (!$keep_alive)
  2529. fclose($fp);
  2530. return fetch_web_data($location, $post_data, $keep_alive, $redirection_level + 1);
  2531. }
  2532. }
  2533. // Make sure we get a 200 OK.
  2534. elseif (preg_match('~^HTTP/\S+\s+20[01]~i', $response) === 0)
  2535. return false;
  2536. // Skip the headers...
  2537. while (!feof($fp) && trim($header = fgets($fp, 4096)) != '')
  2538. {
  2539. if (preg_match('~content-length:\s*(\d+)~i', $header, $match) != 0)
  2540. $content_length = $match[1];
  2541. elseif (preg_match('~connection:\s*close~i', $header) != 0)
  2542. {
  2543. $keep_alive_dom = null;
  2544. $keep_alive = false;
  2545. }
  2546. continue;
  2547. }
  2548. $data = '';
  2549. if (isset($content_length))
  2550. {
  2551. while (!feof($fp) && strlen($data) < $content_length)
  2552. $data .= fread($fp, $content_length - strlen($data));
  2553. }
  2554. else
  2555. {
  2556. while (!feof($fp))
  2557. $data .= fread($fp, 4096);
  2558. }
  2559. if (!$keep_alive)
  2560. fclose($fp);
  2561. }
  2562. else
  2563. {
  2564. // Umm, this shouldn't happen?
  2565. trigger_error('fetch_web_data(): Bad URL', E_USER_NOTICE);
  2566. $data = false;
  2567. }
  2568. return $data;
  2569. }
  2570. // crc32 doesn't work as expected on 64-bit functions - make our own.
  2571. // http://www.php.net/crc32#79567
  2572. if (!function_exists('smf_crc32'))
  2573. {
  2574. function smf_crc32($number)
  2575. {
  2576. $crc = crc32($number);
  2577. if ($crc & 0x80000000)
  2578. {
  2579. $crc ^= 0xffffffff;
  2580. $crc += 1;
  2581. $crc = -$crc;
  2582. }
  2583. return $crc;
  2584. }
  2585. }
  2586. ?>