Subs-Package.php 91 KB

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