Subs-Package.php 91 KB

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