PageRenderTime 37ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/php/Sources/Subs-Package.php

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