Subs-Package.php 96 KB

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