Subs-Package.php 91 KB

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