Subs-Package.php 95 KB

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