Subs-Package.php 92 KB

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