Subs-Package.php 98 KB

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