Subs-Package.php 92 KB

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