Subs-Package.php 92 KB

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