Subs-Package.php 97 KB

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