Subs-Package.php 98 KB

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