Subs-Package.php 92 KB

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