Subs-Package.php 97 KB

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