PageRenderTime 39ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/sources/admin/Packages.php

https://github.com/Arantor/Elkarte
PHP | 2709 lines | 2157 code | 267 blank | 285 comment | 423 complexity | 9469e76cdb62de258aba71020cb11359 MD5 | raw file
Possible License(s): BSD-3-Clause, LGPL-3.0
  1. <?php
  2. /**
  3. * @name ElkArte Forum
  4. * @copyright ElkArte Forum contributors
  5. * @license BSD http://opensource.org/licenses/BSD-3-Clause
  6. *
  7. * This software is a derived product, based on:
  8. *
  9. * Simple Machines Forum (SMF)
  10. * copyright: 2011 Simple Machines (http://www.simplemachines.org)
  11. * license: BSD, See included LICENSE.TXT for terms and conditions.
  12. *
  13. * @version 1.0 Alpha
  14. *
  15. * This file is the main Package Manager.
  16. *
  17. */
  18. if (!defined('ELKARTE'))
  19. die('No access...');
  20. /**
  21. * This is the notoriously defunct package manager..... :/.
  22. */
  23. function Packages()
  24. {
  25. global $txt, $scripturl, $context;
  26. // @todo Remove this!
  27. if (isset($_GET['get']) || isset($_GET['pgdownload']))
  28. {
  29. require_once(ADMINDIR . '/PackageServers.php');
  30. return PackageServers();
  31. }
  32. isAllowedTo('admin_forum');
  33. // Load all the basic stuff.
  34. require_once(SUBSDIR . '/Package.subs.php');
  35. loadLanguage('Packages');
  36. loadTemplate('Packages', 'admin');
  37. $context['page_title'] = $txt['package'];
  38. // Delegation makes the world... that is, the package manager go 'round.
  39. $subActions = array(
  40. 'browse' => 'PackageBrowse',
  41. 'remove' => 'PackageRemove',
  42. 'list' => 'PackageList',
  43. 'ftptest' => 'PackageFTPTest',
  44. 'install' => 'PackageInstallTest',
  45. 'install2' => 'PackageInstall',
  46. 'uninstall' => 'PackageInstallTest',
  47. 'uninstall2' => 'PackageInstall',
  48. 'installed' => 'PackageBrowse',
  49. 'options' => 'PackageOptions',
  50. 'perms' => 'PackagePermissions',
  51. 'flush' => 'FlushInstall',
  52. 'examine' => 'ExamineFile',
  53. 'showoperations' => 'ViewOperations',
  54. );
  55. // Work out exactly who it is we are calling.
  56. if (isset($_REQUEST['sa']) && isset($subActions[$_REQUEST['sa']]))
  57. $context['sub_action'] = $_REQUEST['sa'];
  58. else
  59. $context['sub_action'] = 'browse';
  60. // Set up some tabs...
  61. $context[$context['admin_menu_name']]['tab_data'] = array(
  62. 'title' => $txt['package_manager'],
  63. // @todo 'help' => 'registrations',
  64. 'description' => $txt['package_manager_desc'],
  65. 'tabs' => array(
  66. 'browse' => array(
  67. ),
  68. 'packageget' => array(
  69. 'description' => $txt['download_packages_desc'],
  70. ),
  71. 'installed' => array(
  72. 'description' => $txt['installed_packages_desc'],
  73. ),
  74. 'perms' => array(
  75. 'description' => $txt['package_file_perms_desc'],
  76. ),
  77. 'options' => array(
  78. 'description' => $txt['package_install_options_desc'],
  79. ),
  80. ),
  81. );
  82. // Call the function we're handing control to.
  83. $subActions[$context['sub_action']]();
  84. }
  85. /**
  86. * Test install a package.
  87. */
  88. function PackageInstallTest()
  89. {
  90. global $txt, $context, $scripturl, $modSettings, $smcFunc, $settings;
  91. // You have to specify a file!!
  92. if (!isset($_REQUEST['package']) || $_REQUEST['package'] == '')
  93. redirectexit('action=admin;area=packages');
  94. $context['filename'] = preg_replace('~[\.]+~', '.', $_REQUEST['package']);
  95. // Do we have an existing id, for uninstalls and the like.
  96. $context['install_id'] = isset($_REQUEST['pid']) ? (int) $_REQUEST['pid'] : 0;
  97. require_once(SUBSDIR . '/Package.subs.php');
  98. // Load up the package FTP information?
  99. create_chmod_control();
  100. // Make sure temp directory exists and is empty.
  101. if (file_exists(BOARDDIR . '/packages/temp'))
  102. deltree(BOARDDIR . '/packages/temp', false);
  103. if (!mktree(BOARDDIR . '/packages/temp', 0755))
  104. {
  105. deltree(BOARDDIR . '/packages/temp', false);
  106. if (!mktree(BOARDDIR . '/packages/temp', 0777))
  107. {
  108. deltree(BOARDDIR . '/packages/temp', false);
  109. create_chmod_control(array(BOARDDIR . '/packages/temp/delme.tmp'), array('destination_url' => $scripturl . '?action=admin;area=packages;sa=' . $_REQUEST['sa'] . ';package=' . $_REQUEST['package'], 'crash_on_error' => true));
  110. deltree(BOARDDIR . '/packages/temp', false);
  111. if (!mktree(BOARDDIR . '/packages/temp', 0777))
  112. fatal_lang_error('package_cant_download', false);
  113. }
  114. }
  115. $context['uninstalling'] = $_REQUEST['sa'] == 'uninstall';
  116. // Change our last link tree item for more information on this Packages area.
  117. $context['linktree'][count($context['linktree']) - 1] = array(
  118. 'url' => $scripturl . '?action=admin;area=packages;sa=browse',
  119. 'name' => $context['uninstalling'] ? $txt['package_uninstall_actions'] : $txt['install_actions']
  120. );
  121. $context['page_title'] .= ' - ' . ($context['uninstalling'] ? $txt['package_uninstall_actions'] : $txt['install_actions']);
  122. $context['sub_template'] = 'view_package';
  123. if (!file_exists(BOARDDIR . '/packages/' . $context['filename']))
  124. {
  125. deltree(BOARDDIR . '/packages/temp');
  126. fatal_lang_error('package_no_file', false);
  127. }
  128. // Extract the files so we can get things like the readme, etc.
  129. if (is_file(BOARDDIR . '/packages/' . $context['filename']))
  130. {
  131. $context['extracted_files'] = read_tgz_file(BOARDDIR . '/packages/' . $context['filename'], BOARDDIR . '/packages/temp');
  132. if ($context['extracted_files'] && !file_exists(BOARDDIR . '/packages/temp/package-info.xml'))
  133. foreach ($context['extracted_files'] as $file)
  134. if (basename($file['filename']) == 'package-info.xml')
  135. {
  136. $context['base_path'] = dirname($file['filename']) . '/';
  137. break;
  138. }
  139. if (!isset($context['base_path']))
  140. $context['base_path'] = '';
  141. }
  142. elseif (is_dir(BOARDDIR . '/packages/' . $context['filename']))
  143. {
  144. copytree(BOARDDIR . '/packages/' . $context['filename'], BOARDDIR . '/packages/temp');
  145. $context['extracted_files'] = listtree(BOARDDIR . '/packages/temp');
  146. $context['base_path'] = '';
  147. }
  148. else
  149. fatal_lang_error('no_access', false);
  150. // Load up any custom themes we may want to install into...
  151. $request = $smcFunc['db_query']('', '
  152. SELECT id_theme, variable, value
  153. FROM {db_prefix}themes
  154. WHERE (id_theme = {int:default_theme} OR id_theme IN ({array_int:known_theme_list}))
  155. AND variable IN ({string:name}, {string:theme_dir})',
  156. array(
  157. 'known_theme_list' => explode(',', $modSettings['knownThemes']),
  158. 'default_theme' => 1,
  159. 'name' => 'name',
  160. 'theme_dir' => 'theme_dir',
  161. )
  162. );
  163. $theme_paths = array();
  164. while ($row = $smcFunc['db_fetch_assoc']($request))
  165. $theme_paths[$row['id_theme']][$row['variable']] = $row['value'];
  166. $smcFunc['db_free_result']($request);
  167. // Get the package info...
  168. $packageInfo = getPackageInfo($context['filename']);
  169. if (!is_array($packageInfo))
  170. fatal_lang_error($packageInfo);
  171. $packageInfo['filename'] = $context['filename'];
  172. $context['package_name'] = isset($packageInfo['name']) ? $packageInfo['name'] : $context['filename'];
  173. // Set the type of extraction...
  174. $context['extract_type'] = isset($packageInfo['type']) ? $packageInfo['type'] : 'modification';
  175. // The mod isn't installed.... unless proven otherwise.
  176. $context['is_installed'] = false;
  177. // See if it is installed?
  178. $request = $smcFunc['db_query']('', '
  179. SELECT version, themes_installed, db_changes
  180. FROM {db_prefix}log_packages
  181. WHERE package_id = {string:current_package}
  182. AND install_state != {int:not_installed}
  183. ORDER BY time_installed DESC
  184. LIMIT 1',
  185. array(
  186. 'not_installed' => 0,
  187. 'current_package' => $packageInfo['id'],
  188. )
  189. );
  190. while ($row = $smcFunc['db_fetch_assoc']($request))
  191. {
  192. $old_themes = explode(',', $row['themes_installed']);
  193. $old_version = $row['version'];
  194. $db_changes = empty($row['db_changes']) ? array() : unserialize($row['db_changes']);
  195. }
  196. $smcFunc['db_free_result']($request);
  197. $context['database_changes'] = array();
  198. if (isset($packageInfo['uninstall']['database']))
  199. $context['database_changes'][] = $txt['execute_database_changes'] . ' - ' . $packageInfo['uninstall']['database'];
  200. elseif (!empty($db_changes))
  201. {
  202. foreach ($db_changes as $change)
  203. {
  204. if (isset($change[2]) && isset($txt['package_db_' . $change[0]]))
  205. $context['database_changes'][] = sprintf($txt['package_db_' . $change[0]], $change[1], $change[2]);
  206. elseif (isset($txt['package_db_' . $change[0]]))
  207. $context['database_changes'][] = sprintf($txt['package_db_' . $change[0]], $change[1]);
  208. else
  209. $context['database_changes'][] = $change[0] . '-' . $change[1] . (isset($change[2]) ? '-' . $change[2] : '');
  210. }
  211. }
  212. // Uninstalling?
  213. if ($context['uninstalling'])
  214. {
  215. // Wait, it's not installed yet!
  216. if (!isset($old_version) && $context['uninstalling'])
  217. {
  218. deltree(BOARDDIR . '/packages/temp');
  219. fatal_lang_error('package_cant_uninstall', false);
  220. }
  221. $actions = parsePackageInfo($packageInfo['xml'], true, 'uninstall');
  222. // Gadzooks! There's no uninstaller at all!?
  223. if (empty($actions))
  224. {
  225. deltree(BOARDDIR . '/packages/temp');
  226. fatal_lang_error('package_uninstall_cannot', false);
  227. }
  228. // Can't edit the custom themes it's edited if you're unisntalling, they must be removed.
  229. $context['themes_locked'] = true;
  230. // Only let them uninstall themes it was installed into.
  231. foreach ($theme_paths as $id => $data)
  232. if ($id != 1 && !in_array($id, $old_themes))
  233. unset($theme_paths[$id]);
  234. }
  235. elseif (isset($old_version) && $old_version != $packageInfo['version'])
  236. {
  237. // Look for an upgrade...
  238. $actions = parsePackageInfo($packageInfo['xml'], true, 'upgrade', $old_version);
  239. // There was no upgrade....
  240. if (empty($actions))
  241. $context['is_installed'] = true;
  242. else
  243. {
  244. // Otherwise they can only upgrade themes from the first time around.
  245. foreach ($theme_paths as $id => $data)
  246. if ($id != 1 && !in_array($id, $old_themes))
  247. unset($theme_paths[$id]);
  248. }
  249. }
  250. elseif (isset($old_version) && $old_version == $packageInfo['version'])
  251. $context['is_installed'] = true;
  252. if (!isset($old_version) || $context['is_installed'])
  253. $actions = parsePackageInfo($packageInfo['xml'], true, 'install');
  254. $context['actions'] = array();
  255. $context['ftp_needed'] = false;
  256. $context['has_failure'] = false;
  257. $chmod_files = array();
  258. // no actions found, return so we can display an error
  259. if (empty($actions))
  260. return;
  261. // This will hold data about anything that can be installed in other themes.
  262. $themeFinds = array(
  263. 'candidates' => array(),
  264. 'other_themes' => array(),
  265. );
  266. // Now prepare things for the template.
  267. foreach ($actions as $action)
  268. {
  269. // Not failed until proven otherwise.
  270. $failed = false;
  271. $thisAction = array();
  272. if ($action['type'] == 'chmod')
  273. {
  274. $chmod_files[] = $action['filename'];
  275. continue;
  276. }
  277. elseif ($action['type'] == 'readme' || $action['type'] == 'license')
  278. {
  279. $type = 'package_' . $action['type'];
  280. if (file_exists(BOARDDIR . '/packages/temp/' . $context['base_path'] . $action['filename']))
  281. $context[$type] = htmlspecialchars(trim(file_get_contents(BOARDDIR . '/packages/temp/' . $context['base_path'] . $action['filename']), "\n\r"));
  282. elseif (file_exists($action['filename']))
  283. $context[$type] = htmlspecialchars(trim(file_get_contents($action['filename']), "\n\r"));
  284. if (!empty($action['parse_bbc']))
  285. {
  286. require_once(SUBSDIR . '/Post.subs.php');
  287. preparsecode($context[$type]);
  288. $context[$type] = parse_bbc($context[$type]);
  289. }
  290. else
  291. $context[$type] = nl2br($context[$type]);
  292. continue;
  293. }
  294. // Don't show redirects.
  295. elseif ($action['type'] == 'redirect')
  296. continue;
  297. elseif ($action['type'] == 'error')
  298. {
  299. $context['has_failure'] = true;
  300. if (isset($action['error_msg']) && isset($action['error_var']))
  301. $context['failure_details'] = sprintf($txt['package_will_fail_' . $action['error_msg']], $action['error_var']);
  302. elseif (isset($action['error_msg']))
  303. $context['failure_details'] = isset($txt['package_will_fail_' . $action['error_msg']]) ? $txt['package_will_fail_' . $action['error_msg']] : $action['error_msg'];
  304. }
  305. elseif ($action['type'] == 'modification')
  306. {
  307. if (!file_exists(BOARDDIR . '/packages/temp/' . $context['base_path'] . $action['filename']))
  308. {
  309. $context['has_failure'] = true;
  310. $context['actions'][] = array(
  311. 'type' => $txt['execute_modification'],
  312. 'action' => $smcFunc['htmlspecialchars'](strtr($action['filename'], array(BOARDDIR => '.'))),
  313. 'description' => $txt['package_action_error'],
  314. 'failed' => true,
  315. );
  316. }
  317. else
  318. {
  319. if ($action['boardmod'])
  320. $mod_actions = parseBoardMod(@file_get_contents(BOARDDIR . '/packages/temp/' . $context['base_path'] . $action['filename']), true, $action['reverse'], $theme_paths);
  321. else
  322. $mod_actions = parseModification(@file_get_contents(BOARDDIR . '/packages/temp/' . $context['base_path'] . $action['filename']), true, $action['reverse'], $theme_paths);
  323. if (count($mod_actions) == 1 && isset($mod_actions[0]) && $mod_actions[0]['type'] == 'error' && $mod_actions[0]['filename'] == '-')
  324. $mod_actions[0]['filename'] = $action['filename'];
  325. foreach ($mod_actions as $key => $mod_action)
  326. {
  327. // Lets get the last section of the file name.
  328. if (isset($mod_action['filename']) && substr($mod_action['filename'], -13) != '.template.php')
  329. $actual_filename = strtolower(substr(strrchr($mod_action['filename'], '/'), 1) . '||' . $action['filename']);
  330. elseif (isset($mod_action['filename']) && preg_match('~([\w]*)/([\w]*)\.template\.php$~', $mod_action['filename'], $matches))
  331. $actual_filename = strtolower($matches[1] . '/' . $matches[2] . '.template.php' . '||' . $action['filename']);
  332. else
  333. $actual_filename = $key;
  334. if ($mod_action['type'] == 'opened')
  335. $failed = false;
  336. elseif ($mod_action['type'] == 'failure')
  337. {
  338. if (empty($mod_action['is_custom']))
  339. $context['has_failure'] = true;
  340. $failed = true;
  341. }
  342. elseif ($mod_action['type'] == 'chmod')
  343. {
  344. $chmod_files[] = $mod_action['filename'];
  345. }
  346. elseif ($mod_action['type'] == 'saved')
  347. {
  348. if (!empty($mod_action['is_custom']))
  349. {
  350. if (!isset($context['theme_actions'][$mod_action['is_custom']]))
  351. $context['theme_actions'][$mod_action['is_custom']] = array(
  352. 'name' => $theme_paths[$mod_action['is_custom']]['name'],
  353. 'actions' => array(),
  354. 'has_failure' => $failed,
  355. );
  356. else
  357. $context['theme_actions'][$mod_action['is_custom']]['has_failure'] |= $failed;
  358. $context['theme_actions'][$mod_action['is_custom']]['actions'][$actual_filename] = array(
  359. 'type' => $txt['execute_modification'],
  360. 'action' => $smcFunc['htmlspecialchars'](strtr($mod_action['filename'], array(BOARDDIR => '.'))),
  361. 'description' => $failed ? $txt['package_action_failure'] : $txt['package_action_success'],
  362. 'failed' => $failed,
  363. );
  364. }
  365. elseif (!isset($context['actions'][$actual_filename]))
  366. {
  367. $context['actions'][$actual_filename] = array(
  368. 'type' => $txt['execute_modification'],
  369. 'action' => $smcFunc['htmlspecialchars'](strtr($mod_action['filename'], array(BOARDDIR => '.'))),
  370. 'description' => $failed ? $txt['package_action_failure'] : $txt['package_action_success'],
  371. 'failed' => $failed,
  372. );
  373. }
  374. else
  375. {
  376. $context['actions'][$actual_filename]['failed'] |= $failed;
  377. $context['actions'][$actual_filename]['description'] = $context['actions'][$actual_filename]['failed'] ? $txt['package_action_failure'] : $txt['package_action_success'];
  378. }
  379. }
  380. elseif ($mod_action['type'] == 'skipping')
  381. {
  382. $context['actions'][$actual_filename] = array(
  383. 'type' => $txt['execute_modification'],
  384. 'action' => $smcFunc['htmlspecialchars'](strtr($mod_action['filename'], array(BOARDDIR => '.'))),
  385. 'description' => $txt['package_action_skipping']
  386. );
  387. }
  388. elseif ($mod_action['type'] == 'missing' && empty($mod_action['is_custom']))
  389. {
  390. $context['has_failure'] = true;
  391. $context['actions'][$actual_filename] = array(
  392. 'type' => $txt['execute_modification'],
  393. 'action' => $smcFunc['htmlspecialchars'](strtr($mod_action['filename'], array(BOARDDIR => '.'))),
  394. 'description' => $txt['package_action_missing'],
  395. 'failed' => true,
  396. );
  397. }
  398. elseif ($mod_action['type'] == 'error')
  399. $context['actions'][$actual_filename] = array(
  400. 'type' => $txt['execute_modification'],
  401. 'action' => $smcFunc['htmlspecialchars'](strtr($mod_action['filename'], array(BOARDDIR => '.'))),
  402. 'description' => $txt['package_action_error'],
  403. 'failed' => true,
  404. );
  405. }
  406. // We need to loop again just to get the operations down correctly.
  407. foreach ($mod_actions as $operation_key => $mod_action)
  408. {
  409. // Lets get the last section of the file name.
  410. if (isset($mod_action['filename']) && substr($mod_action['filename'], -13) != '.template.php')
  411. $actual_filename = strtolower(substr(strrchr($mod_action['filename'], '/'), 1) . '||' . $action['filename']);
  412. elseif (isset($mod_action['filename']) && preg_match('~([\w]*)/([\w]*)\.template\.php$~', $mod_action['filename'], $matches))
  413. $actual_filename = strtolower($matches[1] . '/' . $matches[2] . '.template.php' . '||' . $action['filename']);
  414. else
  415. $actual_filename = $key;
  416. // We just need it for actual parse changes.
  417. if (!in_array($mod_action['type'], array('error', 'result', 'opened', 'saved', 'end', 'missing', 'skipping', 'chmod')))
  418. {
  419. if (empty($mod_action['is_custom']))
  420. $context['actions'][$actual_filename]['operations'][] = array(
  421. 'type' => $txt['execute_modification'],
  422. 'action' => $smcFunc['htmlspecialchars'](strtr($mod_action['filename'], array(BOARDDIR => '.'))),
  423. 'description' => $mod_action['failed'] ? $txt['package_action_failure'] : $txt['package_action_success'],
  424. 'position' => $mod_action['position'],
  425. 'operation_key' => $operation_key,
  426. 'filename' => $action['filename'],
  427. 'is_boardmod' => $action['boardmod'],
  428. 'failed' => $mod_action['failed'],
  429. 'ignore_failure' => !empty($mod_action['ignore_failure']),
  430. );
  431. // Themes are under the saved type.
  432. if (isset($mod_action['is_custom']) && isset($context['theme_actions'][$mod_action['is_custom']]))
  433. $context['theme_actions'][$mod_action['is_custom']]['actions'][$actual_filename]['operations'][] = array(
  434. 'type' => $txt['execute_modification'],
  435. 'action' => $smcFunc['htmlspecialchars'](strtr($mod_action['filename'], array(BOARDDIR => '.'))),
  436. 'description' => $mod_action['failed'] ? $txt['package_action_failure'] : $txt['package_action_success'],
  437. 'position' => $mod_action['position'],
  438. 'operation_key' => $operation_key,
  439. 'filename' => $action['filename'],
  440. 'is_boardmod' => $action['boardmod'],
  441. 'failed' => $mod_action['failed'],
  442. 'ignore_failure' => !empty($mod_action['ignore_failure']),
  443. );
  444. }
  445. }
  446. }
  447. }
  448. elseif ($action['type'] == 'code')
  449. {
  450. $thisAction = array(
  451. 'type' => $txt['execute_code'],
  452. 'action' => $smcFunc['htmlspecialchars']($action['filename']),
  453. );
  454. }
  455. elseif ($action['type'] == 'database')
  456. {
  457. $thisAction = array(
  458. 'type' => $txt['execute_database_changes'],
  459. 'action' => $smcFunc['htmlspecialchars']($action['filename']),
  460. );
  461. }
  462. elseif (in_array($action['type'], array('create-dir', 'create-file')))
  463. {
  464. $thisAction = array(
  465. 'type' => $txt['package_create'] . ' ' . ($action['type'] == 'create-dir' ? $txt['package_tree'] : $txt['package_file']),
  466. 'action' => $smcFunc['htmlspecialchars'](strtr($action['destination'], array(BOARDDIR => '.')))
  467. );
  468. }
  469. elseif ($action['type'] == 'hook')
  470. {
  471. $action['description'] = !isset($action['hook'], $action['function']) ? $txt['package_action_failure'] : $txt['package_action_success'];
  472. if (!isset($action['hook'], $action['function']))
  473. $context['has_failure'] = true;
  474. $thisAction = array(
  475. 'type' => $action['reverse'] ? $txt['execute_hook_remove'] : $txt['execute_hook_add'],
  476. 'action' => sprintf($txt['execute_hook_action'], $smcFunc['htmlspecialchars']($action['hook'])),
  477. );
  478. }
  479. elseif ($action['type'] == 'credits')
  480. {
  481. $thisAction = array(
  482. 'type' => $txt['execute_credits_add'],
  483. 'action' => sprintf($txt['execute_credits_action'], $smcFunc['htmlspecialchars']($action['title'])),
  484. );
  485. }
  486. elseif ($action['type'] == 'requires')
  487. {
  488. $installed = false;
  489. $version = true;
  490. // package missing required values?
  491. if (!isset($action['id']))
  492. $context['has_failure'] = true;
  493. else
  494. {
  495. // See if this dependancy is installed
  496. $request = $smcFunc['db_query']('', '
  497. SELECT version
  498. FROM {db_prefix}log_packages
  499. WHERE package_id = {string:current_package}
  500. AND install_state != {int:not_installed}
  501. ORDER BY time_installed DESC
  502. LIMIT 1',
  503. array(
  504. 'not_installed' => 0,
  505. 'current_package' => $action['id'],
  506. )
  507. );
  508. $installed = ($smcFunc['db_num_rows']($request) !== 0);
  509. if ($installed)
  510. list($version) = $smcFunc['db_fetch_row']($request);
  511. $smcFunc['db_free_result']($request);
  512. // do a version level check (if requested) in the most basic way
  513. $version = (isset($action['version']) ? $version == $action['version'] : true);
  514. }
  515. // Set success or failure information
  516. $action['description'] = ($installed && $version) ? $txt['package_action_success'] : $txt['package_action_failure'];
  517. $context['has_failure'] = !($installed && $version);
  518. $thisAction = array(
  519. 'type' => $txt['package_requires'],
  520. 'action' => $txt['package_check_for'] . ' ' . $action['id'] . (isset($action['version']) ? (' / ' . ($version ? $action['version'] : '<span class="error">' . $action['version'] . '</span>')) : ''),
  521. );
  522. }
  523. elseif (in_array($action['type'], array('require-dir', 'require-file')))
  524. {
  525. // Do this one...
  526. $thisAction = array(
  527. 'type' => $txt['package_extract'] . ' ' . ($action['type'] == 'require-dir' ? $txt['package_tree'] : $txt['package_file']),
  528. 'action' => $smcFunc['htmlspecialchars'](strtr($action['destination'], array(BOARDDIR => '.')))
  529. );
  530. // Could this be theme related?
  531. if (!empty($action['unparsed_destination']) && preg_match('~^\$(languagedir|languages_dir|imagesdir|themedir|themes_dir)~i', $action['unparsed_destination'], $matches))
  532. {
  533. // Is the action already stated?
  534. $theme_action = !empty($action['theme_action']) && in_array($action['theme_action'], array('no', 'yes', 'auto')) ? $action['theme_action'] : 'auto';
  535. // If it's not auto do we think we have something we can act upon?
  536. if ($theme_action != 'auto' && !in_array($matches[1], array('languagedir', 'languages_dir', 'imagesdir', 'themedir')))
  537. $theme_action = '';
  538. // ... or if it's auto do we even want to do anything?
  539. elseif ($theme_action == 'auto' && $matches[1] != 'imagesdir')
  540. $theme_action = '';
  541. // So, we still want to do something?
  542. if ($theme_action != '')
  543. $themeFinds['candidates'][] = $action;
  544. // Otherwise is this is going into another theme record it.
  545. elseif ($matches[1] == 'themes_dir')
  546. $themeFinds['other_themes'][] = strtolower(strtr(parse_path($action['unparsed_destination']), array('\\' => '/')) . '/' . basename($action['filename']));
  547. }
  548. }
  549. elseif (in_array($action['type'], array('move-dir', 'move-file')))
  550. $thisAction = array(
  551. 'type' => $txt['package_move'] . ' ' . ($action['type'] == 'move-dir' ? $txt['package_tree'] : $txt['package_file']),
  552. 'action' => $smcFunc['htmlspecialchars'](strtr($action['source'], array(BOARDDIR => '.'))) . ' => ' . $smcFunc['htmlspecialchars'](strtr($action['destination'], array(BOARDDIR => '.')))
  553. );
  554. elseif (in_array($action['type'], array('remove-dir', 'remove-file')))
  555. {
  556. $thisAction = array(
  557. 'type' => $txt['package_delete'] . ' ' . ($action['type'] == 'remove-dir' ? $txt['package_tree'] : $txt['package_file']),
  558. 'action' => $smcFunc['htmlspecialchars'](strtr($action['filename'], array(BOARDDIR => '.')))
  559. );
  560. // Could this be theme related?
  561. if (!empty($action['unparsed_filename']) && preg_match('~^\$(languagedir|languages_dir|imagesdir|themedir|themes_dir)~i', $action['unparsed_filename'], $matches))
  562. {
  563. // Is the action already stated?
  564. $theme_action = !empty($action['theme_action']) && in_array($action['theme_action'], array('no', 'yes', 'auto')) ? $action['theme_action'] : 'auto';
  565. $action['unparsed_destination'] = $action['unparsed_filename'];
  566. // If it's not auto do we think we have something we can act upon?
  567. if ($theme_action != 'auto' && !in_array($matches[1], array('languagedir', 'languages_dir', 'imagesdir', 'themedir')))
  568. $theme_action = '';
  569. // ... or if it's auto do we even want to do anything?
  570. elseif ($theme_action == 'auto' && $matches[1] != 'imagesdir')
  571. $theme_action = '';
  572. // So, we still want to do something?
  573. if ($theme_action != '')
  574. $themeFinds['candidates'][] = $action;
  575. // Otherwise is this is going into another theme record it.
  576. elseif ($matches[1] == 'themes_dir')
  577. $themeFinds['other_themes'][] = strtolower(strtr(parse_path($action['unparsed_filename']), array('\\' => '/')) . '/' . basename($action['filename']));
  578. }
  579. }
  580. if (empty($thisAction))
  581. continue;
  582. if ($context['uninstalling'])
  583. $file = in_array($action['type'], array('remove-dir', 'remove-file')) ? $action['filename'] : BOARDDIR . '/packages/temp/' . $context['base_path'] . $action['filename'];
  584. else
  585. $file = BOARDDIR . '/packages/temp/' . $context['base_path'] . $action['filename'];
  586. if (isset($action['filename']) && !file_exists($file))
  587. {
  588. $context['has_failure'] = true;
  589. $thisAction += array(
  590. 'description' => $txt['package_action_error'],
  591. 'failed' => true,
  592. );
  593. }
  594. // @todo None given?
  595. if (empty($thisAction['description']))
  596. $thisAction['description'] = isset($action['description']) ? $action['description'] : '';
  597. $context['actions'][] = $thisAction;
  598. }
  599. // Have we got some things which we might want to do "multi-theme"?
  600. if (!empty($themeFinds['candidates']))
  601. {
  602. foreach ($themeFinds['candidates'] as $action_data)
  603. {
  604. // Get the part of the file we'll be dealing with.
  605. preg_match('~^\$(languagedir|languages_dir|imagesdir|themedir)(\\|/)*(.+)*~i', $action_data['unparsed_destination'], $matches);
  606. if ($matches[1] == 'imagesdir')
  607. $path = '/' . basename($settings['default_images_url']);
  608. elseif ($matches[1] == 'languagedir' || $matches[1] == 'languages_dir')
  609. $path = '/languages';
  610. else
  611. $path = '';
  612. if (!empty($matches[3]))
  613. $path .= $matches[3];
  614. if (!$context['uninstalling'])
  615. $path .= '/' . basename($action_data['filename']);
  616. // Loop through each custom theme to note it's candidacy!
  617. foreach ($theme_paths as $id => $theme_data)
  618. {
  619. if (isset($theme_data['theme_dir']) && $id != 1)
  620. {
  621. $real_path = $theme_data['theme_dir'] . $path;
  622. // Confirm that we don't already have this dealt with by another entry.
  623. if (!in_array(strtolower(strtr($real_path, array('\\' => '/'))), $themeFinds['other_themes']))
  624. {
  625. // Check if we will need to chmod this.
  626. if (!mktree(dirname($real_path), false))
  627. {
  628. $temp = dirname($real_path);
  629. while (!file_exists($temp) && strlen($temp) > 1)
  630. $temp = dirname($temp);
  631. $chmod_files[] = $temp;
  632. }
  633. if ($action_data['type'] == 'require-dir' && !is_writable($real_path) && (file_exists($real_path) || !is_writable(dirname($real_path))))
  634. $chmod_files[] = $real_path;
  635. if (!isset($context['theme_actions'][$id]))
  636. $context['theme_actions'][$id] = array(
  637. 'name' => $theme_data['name'],
  638. 'actions' => array(),
  639. );
  640. if ($context['uninstalling'])
  641. $context['theme_actions'][$id]['actions'][] = array(
  642. 'type' => $txt['package_delete'] . ' ' . ($action_data['type'] == 'require-dir' ? $txt['package_tree'] : $txt['package_file']),
  643. 'action' => strtr($real_path, array('\\' => '/', BOARDDIR => '.')),
  644. 'description' => '',
  645. 'value' => base64_encode(serialize(array('type' => $action_data['type'], 'orig' => $action_data['filename'], 'future' => $real_path, 'id' => $id))),
  646. 'not_mod' => true,
  647. );
  648. else
  649. $context['theme_actions'][$id]['actions'][] = array(
  650. 'type' => $txt['package_extract'] . ' ' . ($action_data['type'] == 'require-dir' ? $txt['package_tree'] : $txt['package_file']),
  651. 'action' => strtr($real_path, array('\\' => '/', BOARDDIR => '.')),
  652. 'description' => '',
  653. 'value' => base64_encode(serialize(array('type' => $action_data['type'], 'orig' => $action_data['destination'], 'future' => $real_path, 'id' => $id))),
  654. 'not_mod' => true,
  655. );
  656. }
  657. }
  658. }
  659. }
  660. }
  661. // Trash the cache... which will also check permissions for us!
  662. package_flush_cache(true);
  663. if (file_exists(BOARDDIR . '/packages/temp'))
  664. deltree(BOARDDIR . '/packages/temp');
  665. if (!empty($chmod_files))
  666. {
  667. $ftp_status = create_chmod_control($chmod_files);
  668. $context['ftp_needed'] = !empty($ftp_status['files']['notwritable']) && !empty($context['package_ftp']);
  669. }
  670. $context['post_url'] = $scripturl .'?action=admin;area=packages;sa=' . ($context['uninstalling'] ? 'uninstall' : 'install') . ($context['ftp_needed'] ? '' : '2') . ';package=' . $context['filename'] . ';pid=' . $context['install_id'];
  671. checkSubmitOnce('register');
  672. }
  673. /**
  674. * Apply another type of (avatar, language, etc.) package.
  675. */
  676. function PackageInstall()
  677. {
  678. global $txt, $context, $boardurl, $scripturl, $modSettings;
  679. global $user_info, $smcFunc;
  680. // Make sure we don't install this mod twice.
  681. checkSubmitOnce('check');
  682. checkSession();
  683. // If there's no file, what are we installing?
  684. if (!isset($_REQUEST['package']) || $_REQUEST['package'] == '')
  685. redirectexit('action=admin;area=packages');
  686. $context['filename'] = $_REQUEST['package'];
  687. // If this is an uninstall, we'll have an id.
  688. $context['install_id'] = isset($_REQUEST['pid']) ? (int) $_REQUEST['pid'] : 0;
  689. require_once(SUBSDIR . '/Package.subs.php');
  690. // @todo Perhaps do it in steps, if necessary?
  691. $context['uninstalling'] = $_REQUEST['sa'] == 'uninstall2';
  692. // Set up the linktree for other.
  693. $context['linktree'][count($context['linktree']) - 1] = array(
  694. 'url' => $scripturl . '?action=admin;area=packages;sa=browse',
  695. 'name' => $context['uninstalling'] ? $txt['uninstall'] : $txt['extracting']
  696. );
  697. $context['page_title'] .= ' - ' . ($context['uninstalling'] ? $txt['uninstall'] : $txt['extracting']);
  698. $context['sub_template'] = 'extract_package';
  699. if (!file_exists(BOARDDIR . '/packages/' . $context['filename']))
  700. fatal_lang_error('package_no_file', false);
  701. // Load up the package FTP information?
  702. create_chmod_control(array(), array('destination_url' => $scripturl . '?action=admin;area=packages;sa=' . $_REQUEST['sa'] . ';package=' . $_REQUEST['package']));
  703. // Make sure temp directory exists and is empty!
  704. if (file_exists(BOARDDIR . '/packages/temp'))
  705. deltree(BOARDDIR . '/packages/temp', false);
  706. else
  707. mktree(BOARDDIR . '/packages/temp', 0777);
  708. // Let the unpacker do the work.
  709. if (is_file(BOARDDIR . '/packages/' . $context['filename']))
  710. {
  711. $context['extracted_files'] = read_tgz_file(BOARDDIR . '/packages/' . $context['filename'], BOARDDIR . '/packages/temp');
  712. if (!file_exists(BOARDDIR . '/packages/temp/package-info.xml'))
  713. foreach ($context['extracted_files'] as $file)
  714. if (basename($file['filename']) == 'package-info.xml')
  715. {
  716. $context['base_path'] = dirname($file['filename']) . '/';
  717. break;
  718. }
  719. if (!isset($context['base_path']))
  720. $context['base_path'] = '';
  721. }
  722. elseif (is_dir(BOARDDIR . '/packages/' . $context['filename']))
  723. {
  724. copytree(BOARDDIR . '/packages/' . $context['filename'], BOARDDIR . '/packages/temp');
  725. $context['extracted_files'] = listtree(BOARDDIR . '/packages/temp');
  726. $context['base_path'] = '';
  727. }
  728. else
  729. fatal_lang_error('no_access', false);
  730. // Are we installing this into any custom themes?
  731. $custom_themes = array(1);
  732. $known_themes = explode(',', $modSettings['knownThemes']);
  733. if (!empty($_POST['custom_theme']))
  734. {
  735. foreach ($_POST['custom_theme'] as $tid)
  736. if (in_array($tid, $known_themes))
  737. $custom_themes[] = (int) $tid;
  738. }
  739. // Now load up the paths of the themes that we need to know about.
  740. $request = $smcFunc['db_query']('', '
  741. SELECT id_theme, variable, value
  742. FROM {db_prefix}themes
  743. WHERE id_theme IN ({array_int:custom_themes})
  744. AND variable IN ({string:name}, {string:theme_dir})',
  745. array(
  746. 'custom_themes' => $custom_themes,
  747. 'name' => 'name',
  748. 'theme_dir' => 'theme_dir',
  749. )
  750. );
  751. $theme_paths = array();
  752. $themes_installed = array(1);
  753. while ($row = $smcFunc['db_fetch_assoc']($request))
  754. $theme_paths[$row['id_theme']][$row['variable']] = $row['value'];
  755. $smcFunc['db_free_result']($request);
  756. // Are there any theme copying that we want to take place?
  757. $context['theme_copies'] = array(
  758. 'require-file' => array(),
  759. 'require-dir' => array(),
  760. );
  761. if (!empty($_POST['theme_changes']))
  762. {
  763. foreach ($_POST['theme_changes'] as $change)
  764. {
  765. if (empty($change))
  766. continue;
  767. $theme_data = unserialize(base64_decode($change));
  768. if (empty($theme_data['type']))
  769. continue;
  770. $themes_installed[] = $theme_data['id'];
  771. $context['theme_copies'][$theme_data['type']][$theme_data['orig']][] = $theme_data['future'];
  772. }
  773. }
  774. // Get the package info...
  775. $packageInfo = getPackageInfo($context['filename']);
  776. if (!is_array($packageInfo))
  777. fatal_lang_error($packageInfo);
  778. $packageInfo['filename'] = $context['filename'];
  779. // Set the type of extraction...
  780. $context['extract_type'] = isset($packageInfo['type']) ? $packageInfo['type'] : 'modification';
  781. // Create a backup file to roll back to! (but if they do this more than once, don't run it a zillion times.)
  782. if (!empty($modSettings['package_make_full_backups']) && (!isset($_SESSION['last_backup_for']) || $_SESSION['last_backup_for'] != $context['filename'] . ($context['uninstalling'] ? '$$' : '$')))
  783. {
  784. $_SESSION['last_backup_for'] = $context['filename'] . ($context['uninstalling'] ? '$$' : '$');
  785. // @todo Internationalize this?
  786. package_create_backup(($context['uninstalling'] ? 'backup_' : 'before_') . strtok($context['filename'], '.'));
  787. }
  788. // The mod isn't installed.... unless proven otherwise.
  789. $context['is_installed'] = false;
  790. // Is it actually installed?
  791. $request = $smcFunc['db_query']('', '
  792. SELECT version, themes_installed, db_changes
  793. FROM {db_prefix}log_packages
  794. WHERE package_id = {string:current_package}
  795. AND install_state != {int:not_installed}
  796. ORDER BY time_installed DESC
  797. LIMIT 1',
  798. array(
  799. 'not_installed' => 0,
  800. 'current_package' => $packageInfo['id'],
  801. )
  802. );
  803. while ($row = $smcFunc['db_fetch_assoc']($request))
  804. {
  805. $old_themes = explode(',', $row['themes_installed']);
  806. $old_version = $row['version'];
  807. $db_changes = empty($row['db_changes']) ? array() : unserialize($row['db_changes']);
  808. }
  809. $smcFunc['db_free_result']($request);
  810. // Wait, it's not installed yet!
  811. // @todo Replace with a better error message!
  812. if (!isset($old_version) && $context['uninstalling'])
  813. {
  814. deltree(BOARDDIR . '/packages/temp');
  815. fatal_error('Hacker?', false);
  816. }
  817. // Uninstalling?
  818. elseif ($context['uninstalling'])
  819. {
  820. $install_log = parsePackageInfo($packageInfo['xml'], false, 'uninstall');
  821. // Gadzooks! There's no uninstaller at all!?
  822. if (empty($install_log))
  823. fatal_lang_error('package_uninstall_cannot', false);
  824. // They can only uninstall from what it was originally installed into.
  825. foreach ($theme_paths as $id => $data)
  826. if ($id != 1 && !in_array($id, $old_themes))
  827. unset($theme_paths[$id]);
  828. }
  829. elseif (isset($old_version) && $old_version != $packageInfo['version'])
  830. {
  831. // Look for an upgrade...
  832. $install_log = parsePackageInfo($packageInfo['xml'], false, 'upgrade', $old_version);
  833. // There was no upgrade....
  834. if (empty($install_log))
  835. $context['is_installed'] = true;
  836. else
  837. {
  838. // Upgrade previous themes only!
  839. foreach ($theme_paths as $id => $data)
  840. if ($id != 1 && !in_array($id, $old_themes))
  841. unset($theme_paths[$id]);
  842. }
  843. }
  844. elseif (isset($old_version) && $old_version == $packageInfo['version'])
  845. $context['is_installed'] = true;
  846. if (!isset($old_version) || $context['is_installed'])
  847. $install_log = parsePackageInfo($packageInfo['xml'], false, 'install');
  848. $context['install_finished'] = false;
  849. // @todo Make a log of any errors that occurred and output them?
  850. if (!empty($install_log))
  851. {
  852. $failed_steps = array();
  853. $failed_count = 0;
  854. foreach ($install_log as $action)
  855. {
  856. $failed_count++;
  857. if ($action['type'] == 'modification' && !empty($action['filename']))
  858. {
  859. if ($action['boardmod'])
  860. $mod_actions = parseBoardMod(file_get_contents(BOARDDIR . '/packages/temp/' . $context['base_path'] . $action['filename']), false, $action['reverse'], $theme_paths);
  861. else
  862. $mod_actions = parseModification(file_get_contents(BOARDDIR . '/packages/temp/' . $context['base_path'] . $action['filename']), false, $action['reverse'], $theme_paths);
  863. // Any errors worth noting?
  864. foreach ($mod_actions as $key => $action)
  865. {
  866. if ($action['type'] == 'failure')
  867. $failed_steps[] = array(
  868. 'file' => $action['filename'],
  869. 'large_step' => $failed_count,
  870. 'sub_step' => $key,
  871. 'theme' => 1,
  872. );
  873. // Gather the themes we installed into.
  874. if (!empty($action['is_custom']))
  875. $themes_installed[] = $action['is_custom'];
  876. }
  877. }
  878. elseif ($action['type'] == 'code' && !empty($action['filename']))
  879. {
  880. // This is just here as reference for what is available.
  881. global $txt, $modSettings, $context, $settings, $forum_version, $smcFunc;
  882. // Now include the file and be done with it ;).
  883. if (file_exists(BOARDDIR . '/packages/temp/' . $context['base_path'] . $action['filename']))
  884. require(BOARDDIR . '/packages/temp/' . $context['base_path'] . $action['filename']);
  885. }
  886. elseif ($action['type'] == 'credits')
  887. {
  888. // Time to build the billboard
  889. $credits_tag = array(
  890. 'url' => $action['url'],
  891. 'license' => $action['license'],
  892. 'copyright' => $action['copyright'],
  893. 'title' => $action['title'],
  894. );
  895. }
  896. elseif ($action['type'] == 'hook' && isset($action['hook'], $action['function']))
  897. {
  898. if ($action['reverse'])
  899. remove_integration_function($action['hook'], $action['function'], $action['include_file']);
  900. else
  901. add_integration_function($action['hook'], $action['function'], $action['include_file']);
  902. }
  903. // Only do the database changes on uninstall if requested.
  904. elseif ($action['type'] == 'database' && !empty($action['filename']) && (!$context['uninstalling'] || !empty($_POST['do_db_changes'])))
  905. {
  906. // These can also be there for database changes.
  907. global $txt, $modSettings, $context, $settings, $forum_version, $smcFunc;
  908. global $db_package_log;
  909. // We'll likely want the package specific database functionality!
  910. db_extend('packages');
  911. // Let the file work its magic ;)
  912. if (file_exists(BOARDDIR . '/packages/temp/' . $context['base_path'] . $action['filename']))
  913. require(BOARDDIR . '/packages/temp/' . $context['base_path'] . $action['filename']);
  914. }
  915. // Handle a redirect...
  916. elseif ($action['type'] == 'redirect' && !empty($action['redirect_url']))
  917. {
  918. $context['redirect_url'] = $action['redirect_url'];
  919. $context['redirect_text'] = !empty($action['filename']) && file_exists(BOARDDIR . '/packages/temp/' . $context['base_path'] . $action['filename']) ? file_get_contents(BOARDDIR . '/packages/temp/' . $context['base_path'] . $action['filename']) : ($context['uninstalling'] ? $txt['package_uninstall_done'] : $txt['package_installed_done']);
  920. $context['redirect_timeout'] = $action['redirect_timeout'];
  921. // Parse out a couple of common urls.
  922. $urls = array(
  923. '$boardurl' => $boardurl,
  924. '$scripturl' => $scripturl,
  925. '$session_var' => $context['session_var'],
  926. '$session_id' => $context['session_id'],
  927. );
  928. $context['redirect_url'] = strtr($context['redirect_url'], $urls);
  929. }
  930. }
  931. package_flush_cache();
  932. // First, ensure this change doesn't get removed by putting a stake in the ground (So to speak).
  933. package_put_contents(BOARDDIR . '/packages/installed.list', time());
  934. // See if this is already installed, and change it's state as required.
  935. $request = $smcFunc['db_query']('', '
  936. SELECT package_id, install_state, db_changes
  937. FROM {db_prefix}log_packages
  938. WHERE install_state != {int:not_installed}
  939. AND package_id = {string:current_package}
  940. ' . ($context['install_id'] ? ' AND id_install = {int:install_id} ' : '') . '
  941. ORDER BY time_installed DESC
  942. LIMIT 1',
  943. array(
  944. 'not_installed' => 0,
  945. 'install_id' => $context['install_id'],
  946. 'current_package' => $packageInfo['id'],
  947. )
  948. );
  949. $is_upgrade = false;
  950. while ($row = $smcFunc['db_fetch_assoc']($request))
  951. {
  952. // Uninstalling?
  953. if ($context['uninstalling'])
  954. {
  955. $smcFunc['db_query']('', '
  956. UPDATE {db_prefix}log_packages
  957. SET install_state = {int:not_installed}, member_removed = {string:member_name}, id_member_removed = {int:current_member},
  958. time_removed = {int:current_time}
  959. WHERE package_id = {string:package_id}
  960. AND id_install = {int:install_id}',
  961. array(
  962. 'current_member' => $user_info['id'],
  963. 'not_installed' => 0,
  964. 'current_time' => time(),
  965. 'package_id' => $row['package_id'],
  966. 'member_name' => $user_info['name'],
  967. 'install_id' => $context['install_id'],
  968. )
  969. );
  970. }
  971. // Otherwise must be an upgrade.
  972. else
  973. {
  974. $is_upgrade = true;
  975. $old_db_changes = empty($row['db_changes']) ? array() : unserialize($row['db_changes']);
  976. }
  977. }
  978. // Assuming we're not uninstalling, add the entry.
  979. if (!$context['uninstalling'])
  980. {
  981. // Any db changes from older version?
  982. if (!empty($old_db_changes))
  983. $db_package_log = empty($db_package_log) ? $old_db_changes : array_merge($old_db_changes, $db_package_log);
  984. // If there are some database changes we might want to remove then filter them out.
  985. if (!empty($db_package_log))
  986. {
  987. // We're really just checking for entries which are create table AND add columns (etc).
  988. $tables = array();
  989. /**
  990. * Table sorting function used in usort
  991. *
  992. * @param type $a
  993. * @param type $b
  994. * @return int
  995. */
  996. function sort_table_first($a, $b)
  997. {
  998. if ($a[0] == $b[0])
  999. return 0;
  1000. return $a[0] == 'remove_table' ? -1 : 1;
  1001. }
  1002. usort($db_package_log, 'sort_table_first');
  1003. foreach ($db_package_log as $k => $log)
  1004. {
  1005. if ($log[0] == 'remove_table')
  1006. $tables[] = $log[1];
  1007. elseif (in_array($log[1], $tables))
  1008. unset($db_package_log[$k]);
  1009. }
  1010. $db_changes = serialize($db_package_log);
  1011. }
  1012. else
  1013. $db_changes = '';
  1014. // What themes did we actually install?
  1015. $themes_installed = array_unique($themes_installed);
  1016. $themes_installed = implode(',', $themes_installed);
  1017. // What failed steps?
  1018. $failed_step_insert = serialize($failed_steps);
  1019. // Credits tag?
  1020. $credits_tag = (empty($credits_tag)) ? '' : serialize($credits_tag);
  1021. $smcFunc['db_insert']('',
  1022. '{db_prefix}log_packages',
  1023. array(
  1024. 'filename' => 'string', 'name' => 'string', 'package_id' => 'string', 'version' => 'string',
  1025. 'id_member_installed' => 'int', 'member_installed' => 'string','time_installed' => 'int',
  1026. 'install_state' => 'int', 'failed_steps' => 'string', 'themes_installed' => 'string',
  1027. 'member_removed' => 'int', 'db_changes' => 'string', 'credits' => 'string',
  1028. ),
  1029. array(
  1030. $packageInfo['filename'], $packageInfo['name'], $packageInfo['id'], $packageInfo['version'],
  1031. $user_info['id'], $user_info['name'], time(),
  1032. $is_upgrade ? 2 : 1, $failed_step_insert, $themes_installed,
  1033. 0, $db_changes, $credits_tag,
  1034. ),
  1035. array('id_install')
  1036. );
  1037. }
  1038. $smcFunc['db_free_result']($request);
  1039. $context['install_finished'] = true;
  1040. }
  1041. // If there's database changes - and they want them removed - let's do it last!
  1042. if (!empty($db_changes) && !empty($_POST['do_db_changes']))
  1043. {
  1044. // We're gonna be needing the package db functions!
  1045. db_extend('packages');
  1046. foreach ($db_changes as $change)
  1047. {
  1048. if ($change[0] == 'remove_table' && isset($change[1]))
  1049. $smcFunc['db_drop_table']($change[1]);
  1050. elseif ($change[0] == 'remove_column' && isset($change[2]))
  1051. $smcFunc['db_remove_column']($change[1], $change[2]);
  1052. elseif ($change[0] == 'remove_index' && isset($change[2]))
  1053. $smcFunc['db_remove_index']($change[1], $change[2]);
  1054. }
  1055. }
  1056. // Clean house... get rid of the evidence ;).
  1057. if (file_exists(BOARDDIR . '/packages/temp'))
  1058. deltree(BOARDDIR . '/packages/temp');
  1059. // Log what we just did.
  1060. logAction($context['uninstalling'] ? 'uninstall_package' : (!empty($is_upgrade) ? 'upgrade_package' : 'install_package'), array('package' => $smcFunc['htmlspecialchars']($packageInfo['name']), 'version' => $smcFunc['htmlspecialchars']($packageInfo['version'])), 'admin');
  1061. // Just in case, let's clear the whole cache to avoid anything going up the swanny.
  1062. clean_cache();
  1063. // Restore file permissions?
  1064. create_chmod_control(array(), array(), true);
  1065. }
  1066. /**
  1067. * List the files in a package.
  1068. */
  1069. function PackageList()
  1070. {
  1071. global $txt, $scripturl, $context;
  1072. require_once(SUBSDIR . '/Package.subs.php');
  1073. // No package? Show him or her the door.
  1074. if (!isset($_REQUEST['package']) || $_REQUEST['package'] == '')
  1075. redirectexit('action=admin;area=packages');
  1076. $context['linktree'][] = array(
  1077. 'url' => $scripturl . '?action=admin;area=packages;sa=list;package=' . $_REQUEST['package'],
  1078. 'name' => $txt['list_file']
  1079. );
  1080. $context['page_title'] .= ' - ' . $txt['list_file'];
  1081. $context['sub_template'] = 'list';
  1082. // The filename...
  1083. $context['filename'] = $_REQUEST['package'];
  1084. // Let the unpacker do the work.
  1085. if (is_file(BOARDDIR . '/packages/' . $context['filename']))
  1086. $context['files'] = read_tgz_file(BOARDDIR . '/packages/' . $context['filename'], null);
  1087. elseif (is_dir(BOARDDIR . '/packages/' . $context['filename']))
  1088. $context['files'] = listtree(BOARDDIR . '/packages/' . $context['filename']);
  1089. }
  1090. /**
  1091. * Display one of the files in a package.
  1092. */
  1093. function ExamineFile()
  1094. {
  1095. global $txt, $scripturl, $context;
  1096. require_once(SUBSDIR . '/Package.subs.php');
  1097. // No package? Show him or her the door.
  1098. if (!isset($_REQUEST['package']) || $_REQUEST['package'] == '')
  1099. redirectexit('action=admin;area=packages');
  1100. // No file? Show him or her the door.
  1101. if (!isset($_REQUEST['file']) || $_REQUEST['file'] == '')
  1102. redirectexit('action=admin;area=packages');
  1103. $_REQUEST['package'] = preg_replace('~[\.]+~', '.', strtr($_REQUEST['package'], array('/' => '_', '\\' => '_')));
  1104. $_REQUEST['file'] = preg_replace('~[\.]+~', '.', $_REQUEST['file']);
  1105. if (isset($_REQUEST['raw']))
  1106. {
  1107. if (is_file(BOARDDIR . '/packages/' . $_REQUEST['package']))
  1108. echo read_tgz_file(BOARDDIR . '/packages/' . $_REQUEST['package'], $_REQUEST['file'], true);
  1109. elseif (is_dir(BOARDDIR . '/packages/' . $_REQUEST['package']))
  1110. echo file_get_contents(BOARDDIR . '/packages/' . $_REQUEST['package'] . '/' . $_REQUEST['file']);
  1111. obExit(false);
  1112. }
  1113. $context['linktree'][count($context['linktree']) - 1] = array(
  1114. 'url' => $scripturl . '?action=admin;area=packages;sa=list;package=' . $_REQUEST['package'],
  1115. 'name' => $txt['package_examine_file']
  1116. );
  1117. $context['page_title'] .= ' - ' . $txt['package_examine_file'];
  1118. $context['sub_template'] = 'examine';
  1119. // The filename...
  1120. $context['package'] = $_REQUEST['package'];
  1121. $context['filename'] = $_REQUEST['file'];
  1122. // Let the unpacker do the work.... but make sure we handle images properly.
  1123. if (in_array(strtolower(strrchr($_REQUEST['file'], '.')), array('.bmp', '.gif', '.jpeg', '.jpg', '.png')))
  1124. $context['filedata'] = '<img src="' . $scripturl . '?action=admin;area=packages;sa=examine;package=' . $_REQUEST['package'] . ';file=' . $_REQUEST['file'] . ';raw" alt="' . $_REQUEST['file'] . '" />';
  1125. else
  1126. {
  1127. if (is_file(BOARDDIR . '/packages/' . $_REQUEST['package']))
  1128. $context['filedata'] = htmlspecialchars(read_tgz_file(BOARDDIR . '/packages/' . $_REQUEST['package'], $_REQUEST['file'], true));
  1129. elseif (is_dir(BOARDDIR . '/packages/' . $_REQUEST['package']))
  1130. $context['filedata'] = htmlspecialchars(file_get_contents(BOARDDIR . '/packages/' . $_REQUEST['package'] . '/' . $_REQUEST['file']));
  1131. if (strtolower(strrchr($_REQUEST['file'], '.')) == '.php')
  1132. $context['filedata'] = highlight_php_code($context['filedata']);
  1133. }
  1134. }
  1135. /**
  1136. * List the installed packages.
  1137. */
  1138. function InstalledList()
  1139. {
  1140. global $txt, $scripturl, $context;
  1141. $context['page_title'] .= ' - ' . $txt['installed_packages'];
  1142. $context['sub_template'] = 'view_installed';
  1143. // Load the installed mods and send them to the template.
  1144. $context['installed_mods'] = loadInstalledPackages();
  1145. }
  1146. /**
  1147. * Empty out the installed list.
  1148. */
  1149. function FlushInstall()
  1150. {
  1151. global $smcFunc;
  1152. // Always check the session.
  1153. checkSession('get');
  1154. include_once(SUBSDIR . '/Package.subs.php');
  1155. // Record when we last did this.
  1156. package_put_contents(BOARDDIR . '/packages/installed.list', time());
  1157. // Set everything as uninstalled.
  1158. $smcFunc['db_query']('', '
  1159. UPDATE {db_prefix}log_packages
  1160. SET install_state = {int:not_installed}',
  1161. array(
  1162. 'not_installed' => 0,
  1163. )
  1164. );
  1165. redirectexit('action=admin;area=packages;sa=installed');
  1166. }
  1167. /**
  1168. * Delete a package.
  1169. */
  1170. function PackageRemove()
  1171. {
  1172. global $scripturl;
  1173. // Check it.
  1174. checkSession('get');
  1175. // Ack, don't allow deletion of arbitrary files here, could become a security hole somehow!
  1176. if (!isset($_GET['package']) || $_GET['package'] == 'index.php' || $_GET['package'] == 'installed.list' || $_GET['package'] == 'backups')
  1177. redirectexit('action=admin;area=packages;sa=browse');
  1178. $_GET['package'] = preg_replace('~[\.]+~', '.', strtr($_GET['package'], array('/' => '_', '\\' => '_')));
  1179. // Can't delete what's not there.
  1180. if (file_exists(BOARDDIR . '/packages/' . $_GET['package']) && (substr($_GET['package'], -4) == '.zip' || substr($_GET['package'], -4) == '.tgz' || substr($_GET['package'], -7) == '.tar.gz' || is_dir(BOARDDIR . '/packages/' . $_GET['package'])) && $_GET['package'] != 'backups' && substr($_GET['package'], 0, 1) != '.')
  1181. {
  1182. create_chmod_control(array(BOARDDIR . '/packages/' . $_GET['package']), array('destination_url' => $scripturl . '?action=admin;area=packages;sa=remove;package=' . $_GET['package'], 'crash_on_error' => true));
  1183. if (is_dir(BOARDDIR . '/packages/' . $_GET['package']))
  1184. deltree(BOARDDIR . '/packages/' . $_GET['package']);
  1185. else
  1186. {
  1187. @chmod(BOARDDIR . '/packages/' . $_GET['package'], 0777);
  1188. unlink(BOARDDIR . '/packages/' . $_GET['package']);
  1189. }
  1190. }
  1191. redirectexit('action=admin;area=packages;sa=browse');
  1192. }
  1193. /**
  1194. * Browse a list of installed packages.
  1195. */
  1196. function PackageBrowse()
  1197. {
  1198. global $txt, $scripturl, $context, $forum_version, $settings;
  1199. require_once(SUBSDIR . '/List.subs.php');
  1200. $context['page_title'] .= ' - ' . $txt['browse_packages'];
  1201. $context['forum_version'] = $forum_version;
  1202. $installed = $context['sub_action'] == 'installed' ? true : false;
  1203. $context['modification_types'] = $installed ? array('modification') : array('modification', 'avatar', 'language', 'unknown');
  1204. foreach ($context['modification_types'] as $type)
  1205. {
  1206. // Use the standard templates for showing this.
  1207. $listOptions = array(
  1208. 'id' => 'packages_lists_' . $type,
  1209. 'title' => $installed ? $txt['view_and_remove'] : $txt[$type . '_package'],
  1210. 'no_items_label' => $txt['no_packages'],
  1211. 'get_items' => array(
  1212. 'function' => 'list_getPackages',
  1213. 'params' => array('type' => $type, 'installed' => $installed),
  1214. ),
  1215. 'base_href' => $scripturl . '?action=admin;area=packages;sa=' . $context['sub_action'] . ';type=' . $type,
  1216. 'default_sort_col' => 'id' . $type,
  1217. 'columns' => array(
  1218. 'id' . $type => array(
  1219. 'header' => array(
  1220. 'value' => $txt['package_id'],
  1221. 'style' => 'width: 40px;',
  1222. ),
  1223. 'data' => array(
  1224. 'function' => create_function('$package_md5', '
  1225. global $context;
  1226. if (isset($context[\'available_' . $type . '\'][$package_md5]))
  1227. return $context[\'available_' . $type . '\'][$package_md5][\'sort_id\'];
  1228. '),
  1229. ),
  1230. 'sort' => array(
  1231. 'default' => 'sort_id',
  1232. 'reverse' => 'sort_id'
  1233. ),
  1234. ),
  1235. 'mod_name' . $type => array(
  1236. 'header' => array(
  1237. 'value' => $txt['mod_name'],
  1238. 'style' => 'width: 25%;',
  1239. ),
  1240. 'data' => array(
  1241. 'function' => create_function('$package_md5', '
  1242. global $context;
  1243. if (isset($context[\'available_' . $type . '\'][$package_md5]))
  1244. return $context[\'available_' . $type . '\'][$package_md5][\'name\'];
  1245. '),
  1246. ),
  1247. 'sort' => array(
  1248. 'default' => 'name',
  1249. 'reverse' => 'name',
  1250. ),
  1251. ),
  1252. 'version' . $type => array(
  1253. 'header' => array(
  1254. 'value' => $txt['mod_version'],
  1255. 'style' => 'width: 25%;',
  1256. ),
  1257. 'data' => array(
  1258. 'function' => create_function('$package_md5', '
  1259. global $context;
  1260. if (isset($context[\'available_' . $type . '\'][$package_md5]))
  1261. return $context[\'available_' . $type . '\'][$package_md5][\'version\'];
  1262. '),
  1263. ),
  1264. 'sort' => array(
  1265. 'default' => 'version',
  1266. 'reverse' => 'version',
  1267. ),
  1268. ),
  1269. 'operations' . $type => array(
  1270. 'header' => array(
  1271. 'value' => '',
  1272. ),
  1273. 'data' => array(
  1274. 'function' => create_function('$package_md5', '
  1275. global $context, $scripturl, $txt;
  1276. if (!isset($context[\'available_' . $type . '\'][$package_md5]))
  1277. return \'\';
  1278. // Rewrite shortcut
  1279. $package = $context[\'available_' . $type . '\'][$package_md5];
  1280. $return = \'\';
  1281. if ($package[\'can_uninstall\'])
  1282. $return = \'
  1283. <a href="\' . $scripturl . \'?action=admin;area=packages;sa=uninstall;package=\' . $package[\'filename\'] . \';pid=\' . $package[\'installed_id\'] . \'">[ \' . $txt[\'uninstall\'] . \' ]</a>\';
  1284. elseif ($package[\'can_emulate_uninstall\'])
  1285. $return = \'
  1286. <a href="\' . $scripturl . \'?action=admin;area=packages;sa=uninstall;ve=\' . $package[\'can_emulate_uninstall\'] . \';package=\' . $package[\'filename\'] . \';pid=\' . $package[\'installed_id\'] . \'">[ \' . $txt[\'package_emulate_uninstall\'] . \' \' . $package[\'can_emulate_uninstall\'] . \' ]</a>\';
  1287. elseif ($package[\'can_upgrade\'])
  1288. $return = \'
  1289. <a href="\' . $scripturl . \'?action=admin;area=packages;sa=install;package=\' . $package[\'filename\'] . \'">[ \' . $txt[\'package_upgrade\'] . \' ]</a>\';
  1290. elseif ($package[\'can_install\'])
  1291. $return = \'
  1292. <a href="\' . $scripturl . \'?action=admin;area=packages;sa=install;package=\' . $package[\'filename\'] . \'">[ \' . $txt[\'install_mod\'] . \' ]</a>\';
  1293. elseif ($package[\'can_emulate_install\'])
  1294. $return = \'
  1295. <a href="\' . $scripturl . \'?action=admin;area=packages;sa=install;ve=\' . $package[\'can_emulate_install\'] . \';package=\' . $package[\'filename\'] . \'">[ \' . $txt[\'package_emulate_install\'] . \' \' . $package[\'can_emulate_install\'] . \' ]</a>\';
  1296. return $return . \'
  1297. <a href="\' . $scripturl . \'?action=admin;area=packages;sa=list;package=\' . $package[\'filename\'] . \'">[ \' . $txt[\'list_files\'] . \' ]</a>
  1298. <a href="\' . $scripturl . \'?action=admin;area=packages;sa=remove;package=\' . $package[\'filename\'] . \';\' . $context[\'session_var\'] . \'=\' . $context[\'session_id\'] . \'"\' . ($package[\'is_installed\'] && $package[\'is_current\'] ? \' onclick="return confirm(\\\'\' . $txt[\'package_delete_bad\'] . \'\\\');"\' : \'\') . \'>[ \' . $txt[\'package_delete\'] . \' ]</a>\';
  1299. '),
  1300. 'class' => 'righttext',
  1301. ),
  1302. ),
  1303. ),
  1304. 'additional_rows' => array(
  1305. array(
  1306. 'position' => 'bottom_of_list',
  1307. 'value' => ($context['sub_action'] == 'browse' ? '<div class="padding smalltext">' . $txt['package_installed_key'] . '<img src="' . $settings['images_url'] . '/icons/package_installed.png" alt="" class="centericon" style="margin-left: 1ex;" /> ' . $txt['package_installed_current'] . '<img src="' . $settings['images_url'] . '/icons/package_old.png" alt="" class="centericon" style="margin-left: 2ex;" /> ' . $txt['package_installed_old'] . '</div>' :
  1308. '<a class="button_link" href="' . $scripturl . '?action=admin;area=packages;sa=flush;' . $context['session_var'] . '=' . $context['session_id'] . '" onclick="return confirm(\'' . $txt['package_delete_list_warning'] . '\');">' . $txt['delete_list'] . '</a>'),
  1309. ),
  1310. ),
  1311. );
  1312. createList($listOptions);
  1313. }
  1314. $context['sub_template'] = 'browse';
  1315. $context['default_list'] = 'packages_lists';
  1316. // Empty lists for now.
  1317. $context['available_mods'] = array();
  1318. $context['available_avatars'] = array();
  1319. $context['available_languages'] = array();
  1320. $context['available_other'] = array();
  1321. $context['available_all'] = array();
  1322. }
  1323. /**
  1324. * Get a listing of all the packages
  1325. * Determines if the package is a mod, avatar, language package
  1326. * Determines if the package has been installed or not
  1327. *
  1328. * @param type $start
  1329. * @param type $items_per_page
  1330. * @param type $sort
  1331. * @param type $params
  1332. * @param type $installed
  1333. * @return type
  1334. */
  1335. function list_getPackages($start, $items_per_page, $sort, $params, $installed)
  1336. {
  1337. global $scripturl, $context, $forum_version;
  1338. static $instmods, $packages;
  1339. // Start things up
  1340. if (!isset($packages[$params]))
  1341. $packages[$params] = array();
  1342. // We need the packages directory to be writable for this.
  1343. if (!@is_writable(BOARDDIR . '/packages'))
  1344. create_chmod_control(array(BOARDDIR . '/packages'), array('destination_url' => $scripturl . '?action=admin;area=packages', 'crash_on_error' => true));
  1345. list($the_brand, $the_version) = explode(' ', $forum_version, 2);
  1346. // Here we have a little code to help those who class themselves as something of gods, version emulation ;)
  1347. if (isset($_GET['version_emulate']) && strtr($_GET['version_emulate'], array($the_brand => '')) == $the_version)
  1348. {
  1349. unset($_SESSION['version_emulate']);
  1350. }
  1351. elseif (isset($_GET['version_emulate']))
  1352. {
  1353. if (($_GET['version_emulate'] === 0 || $_GET['version_emulate'] === $forum_version) && isset($_SESSION['version_emulate']))
  1354. unset($_SESSION['version_emulate']);
  1355. elseif ($_GET['version_emulate'] !== 0)
  1356. $_SESSION['version_emulate'] = strtr($_GET['version_emulate'], array('-' => ' ', '+' => ' ', $the_brand . ' ' => ''));
  1357. }
  1358. if (!empty($_SESSION['version_emulate']))
  1359. {
  1360. $context['forum_version'] = $the_brand . ' ' . $_SESSION['version_emulate'];
  1361. $the_version = $_SESSION['version_emulate'];
  1362. }
  1363. if (isset($_SESSION['single_version_emulate']))
  1364. unset($_SESSION['single_version_emulate']);
  1365. if (empty($instmods))
  1366. {
  1367. $instmods = loadInstalledPackages();
  1368. $installed_mods = array();
  1369. // Look through the list of installed mods...
  1370. foreach ($instmods as $installed_mod)
  1371. $installed_mods[$installed_mod['package_id']] = array(
  1372. 'id' => $installed_mod['id'],
  1373. 'version' => $installed_mod['version'],
  1374. );
  1375. // Get a list of all the ids installed, so the latest packages won't include already installed ones.
  1376. $context['installed_mods'] = array_keys($installed_mods);
  1377. }
  1378. if ($installed)
  1379. {
  1380. $sort_id = 1;
  1381. foreach ($instmods as $installed_mod)
  1382. {
  1383. $context['available_modification'][$installed_mod['package_id']] = array(
  1384. 'sort_id' => $sort_id++,
  1385. 'can_uninstall' => true,
  1386. 'name' => $installed_mod['name'],
  1387. 'filename' => $installed_mod['filename'],
  1388. 'installed_id' => $installed_mod['id'],
  1389. 'version' => $installed_mod['version'],
  1390. 'is_installed' => true,
  1391. 'is_current' => true,
  1392. );
  1393. }
  1394. }
  1395. if (empty($packages))
  1396. foreach ($context['modification_types'] as $type)
  1397. $packages[$type] = array();
  1398. if ($dir = @opendir(BOARDDIR . '/packages'))
  1399. {
  1400. $dirs = array();
  1401. $sort_id = array(
  1402. 'mod' => 1,
  1403. 'modification' => 1,
  1404. 'avatar' => 1,
  1405. 'language' => 1,
  1406. 'unknown' => 1,
  1407. );
  1408. while ($package = readdir($dir))
  1409. {
  1410. if ($package == '.' || $package == '..' || $package == 'temp' || (!(is_dir(BOARDDIR . '/packages/' . $package) && file_exists(BOARDDIR . '/packages/' . $package . '/package-info.xml')) && substr(strtolower($package), -7) != '.tar.gz' && substr(strtolower($package), -4) != '.tgz' && substr(strtolower($package), -4) != '.zip'))
  1411. continue;
  1412. $skip = false;
  1413. foreach ($context['modification_types'] as $type)
  1414. if (isset($context['available_' . $type][md5($package)]))
  1415. $skip = true;
  1416. if ($skip)
  1417. continue;
  1418. // Skip directories or files that are named the same.
  1419. if (is_dir(BOARDDIR . '/packages/' . $package))
  1420. {
  1421. if (in_array($package, $dirs))
  1422. continue;
  1423. $dirs[] = $package;
  1424. }
  1425. elseif (substr(strtolower($package), -7) == '.tar.gz')
  1426. {
  1427. if (in_array(substr($package, 0, -7), $dirs))
  1428. continue;
  1429. $dirs[] = substr($package, 0, -7);
  1430. }
  1431. elseif (substr(strtolower($package), -4) == '.zip' || substr(strtolower($package), -4) == '.tgz')
  1432. {
  1433. if (in_array(substr($package, 0, -4), $dirs))
  1434. continue;
  1435. $dirs[] = substr($package, 0, -4);
  1436. }
  1437. $packageInfo = getPackageInfo($package);
  1438. if (!is_array($packageInfo))
  1439. continue;
  1440. if (!empty($packageInfo))
  1441. {
  1442. $packageInfo['installed_id'] = isset($installed_mods[$packageInfo['id']]) ? $installed_mods[$packageInfo['id']]['id'] : 0;
  1443. $packageInfo['sort_id'] = $sort_id[$packageInfo['type']];
  1444. $packageInfo['is_installed'] = isset($installed_mods[$packageInfo['id']]);
  1445. $packageInfo['is_current'] = $packageInfo['is_installed'] && ($installed_mods[$packageInfo['id']]['version'] == $packageInfo['version']);
  1446. $packageInfo['is_newer'] = $packageInfo['is_installed'] && ($installed_mods[$packageInfo['id']]['version'] > $packageInfo['version']);
  1447. $packageInfo['can_install'] = false;
  1448. $packageInfo['can_uninstall'] = false;
  1449. $packageInfo['can_upgrade'] = false;
  1450. $packageInfo['can_emulate_install'] = false;
  1451. $packageInfo['can_emulate_uninstall'] = false;
  1452. // This package is currently NOT installed. Check if it can be.
  1453. if (!$packageInfo['is_installed'] && $packageInfo['xml']->exists('install'))
  1454. {
  1455. // Check if there's an install for *THIS* version
  1456. $installs = $packageInfo['xml']->set('install');
  1457. foreach ($installs as $install)
  1458. {
  1459. if (!$install->exists('@for') || matchPackageVersion($the_version, $install->fetch('@for')))
  1460. {
  1461. // Okay, this one is good to go.
  1462. $packageInfo['can_install'] = true;
  1463. break;
  1464. }
  1465. }
  1466. // no install found for our version, lets see if one exists for another
  1467. if ($packageInfo['can_install'] === false && $install->exists('@for') && empty($_SESSION['version_emulate']))
  1468. {
  1469. $reset = true;
  1470. // Get the highest install version that is available from the package
  1471. foreach ($installs as $install)
  1472. {
  1473. $packageInfo['can_emulate_install'] = matchHighestPackageVersion($install->fetch('@for'), $reset, $the_version);
  1474. $reset = false;
  1475. }
  1476. }
  1477. }
  1478. // An already installed, but old, package. Can we upgrade it?
  1479. elseif ($packageInfo['is_installed'] && !$packageInfo['is_current'] && $packageInfo['xml']->exists('upgrade'))
  1480. {
  1481. $upgrades = $packageInfo['xml']->set('upgrade');
  1482. // First go through, and check against the current version of ELKARTE.
  1483. foreach ($upgrades as $upgrade)
  1484. {
  1485. // Even if it is for this ELKARTE, is it for the installed version of the mod?
  1486. if (!$upgrade->exists('@for') || matchPackageVersion($the_version, $upgrade->fetch('@for')))
  1487. if (!$upgrade->exists('@from') || matchPackageVersion($installed_mods[$packageInfo['id']]['version'], $upgrade->fetch('@from')))
  1488. {
  1489. $packageInfo['can_upgrade'] = true;
  1490. break;
  1491. }
  1492. }
  1493. }
  1494. // Note that it has to be the current version to be uninstallable. Shucks.
  1495. elseif ($packageInfo['is_installed'] && $packageInfo['is_current'] && $packageInfo['xml']->exists('uninstall'))
  1496. {
  1497. $uninstalls = $packageInfo['xml']->set('uninstall');
  1498. // Can we find any uninstallation methods that work for this ELKARTE version?
  1499. foreach ($uninstalls as $uninstall)
  1500. {
  1501. if (!$uninstall->exists('@for') || matchPackageVersion($the_version, $uninstall->fetch('@for')))
  1502. {
  1503. $packageInfo['can_uninstall'] = true;
  1504. break;
  1505. }
  1506. }
  1507. // no uninstall found for this version, lets see if one exists for another
  1508. if ($packageInfo['can_uninstall'] === false && $uninstall->exists('@for') && empty($_SESSION['version_emulate']))
  1509. {
  1510. $reset = true;
  1511. // Get the highest install version that is available from the package
  1512. foreach ($uninstalls as $uninstall)
  1513. {
  1514. $packageInfo['can_emulate_uninstall'] = matchHighestPackageVersion($uninstall->fetch('@for'), $reset, $the_version);
  1515. $reset = false;
  1516. }
  1517. }
  1518. }
  1519. // Modification.
  1520. if ($packageInfo['type'] == 'modification' || $packageInfo['type'] == 'mod')
  1521. {
  1522. $sort_id['modification']++;
  1523. $sort_id['mod']++;
  1524. if ($installed)
  1525. {
  1526. if (!empty($context['available_modification'][$packageInfo['id']]))
  1527. {
  1528. $packages['modification'][strtolower($packageInfo[$sort]) . '_' . $sort_id['mod']] = $packageInfo['id'];
  1529. $context['available_modification'][$packageInfo['id']] = array_merge($context['available_modification'][$packageInfo['id']], $packageInfo);
  1530. }
  1531. }
  1532. else
  1533. {
  1534. $packages['modification'][strtolower($packageInfo[$sort]) . '_' . $sort_id['mod']] = md5($package);
  1535. $context['available_modification'][md5($package)] = $packageInfo;
  1536. }
  1537. }
  1538. // Avatar package.
  1539. elseif ($packageInfo['type'] == 'avatar')
  1540. {
  1541. $sort_id[$packageInfo['type']]++;
  1542. $packages['avatar'][strtolower($packageInfo[$sort])] = md5($package);
  1543. $context['available_avatar'][md5($package)] = $packageInfo;
  1544. }
  1545. // Language package.
  1546. elseif ($packageInfo['type'] == 'language')
  1547. {
  1548. $sort_id[$packageInfo['type']]++;
  1549. $packages['language'][strtolower($packageInfo[$sort])] = md5($package);
  1550. $context['available_language'][md5($package)] = $packageInfo;
  1551. }
  1552. // Other stuff.
  1553. else
  1554. {
  1555. $sort_id['unknown']++;
  1556. $packages['unknown'][strtolower($packageInfo[$sort])] = md5($package);
  1557. $context['available_unknown'][md5($package)] = $packageInfo;
  1558. }
  1559. }
  1560. }
  1561. closedir($dir);
  1562. }
  1563. if (isset($_GET['type']) && $_GET['type'] == $params)
  1564. {
  1565. if (isset($_GET['desc']))
  1566. krsort($packages[$params]);
  1567. else
  1568. ksort($packages[$params]);
  1569. }
  1570. return $packages[$params];
  1571. }
  1572. /**
  1573. * Used when a temp FTP access is needed to package functions
  1574. */
  1575. function PackageOptions()
  1576. {
  1577. global $txt, $scripturl, $context, $modSettings, $smcFunc;
  1578. if (isset($_POST['save']))
  1579. {
  1580. checkSession('post');
  1581. updateSettings(array(
  1582. 'package_server' => trim($smcFunc['htmlspecialchars']($_POST['pack_server'])),
  1583. 'package_port' => trim($smcFunc['htmlspecialchars']($_POST['pack_port'])),
  1584. 'package_username' => trim($smcFunc['htmlspecialchars']($_POST['pack_user'])),
  1585. 'package_make_backups' => !empty($_POST['package_make_backups']),
  1586. 'package_make_full_backups' => !empty($_POST['package_make_full_backups'])
  1587. ));
  1588. redirectexit('action=admin;area=packages;sa=options');
  1589. }
  1590. if (preg_match('~^/home\d*/([^/]+?)/public_html~', $_SERVER['DOCUMENT_ROOT'], $match))
  1591. $default_username = $match[1];
  1592. else
  1593. $default_username = '';
  1594. $context['page_title'] = $txt['package_settings'];
  1595. $context['sub_template'] = 'install_options';
  1596. $context['package_ftp_server'] = isset($modSettings['package_server']) ? $modSettings['package_server'] : 'localhost';
  1597. $context['package_ftp_port'] = isset($modSettings['package_port']) ? $modSettings['package_port'] : '21';
  1598. $context['package_ftp_username'] = isset($modSettings['package_username']) ? $modSettings['package_username'] : $default_username;
  1599. $context['package_make_backups'] = !empty($modSettings['package_make_backups']);
  1600. $context['package_make_full_backups'] = !empty($modSettings['package_make_full_backups']);
  1601. }
  1602. /**
  1603. * List operations
  1604. */
  1605. function ViewOperations()
  1606. {
  1607. global $context, $txt, $smcFunc, $modSettings;
  1608. // Can't be in here buddy.
  1609. isAllowedTo('admin_forum');
  1610. // We need to know the operation key for the search and replace, mod file looking at, is it a board mod?
  1611. if (!isset($_REQUEST['operation_key'], $_REQUEST['filename']) && !is_numeric($_REQUEST['operation_key']))
  1612. fatal_lang_error('operation_invalid', 'general');
  1613. // Load the required file.
  1614. require_once(SUBSDIR . '/Package.subs.php');
  1615. // Uninstalling the mod?
  1616. $reverse = isset($_REQUEST['reverse']) ? true : false;
  1617. // Get the base name.
  1618. $context['filename'] = preg_replace('~[\.]+~', '.', $_REQUEST['package']);
  1619. // We need to extract this again.
  1620. if (is_file(BOARDDIR . '/packages/' . $context['filename']))
  1621. {
  1622. $context['extracted_files'] = read_tgz_file(BOARDDIR . '/packages/' . $context['filename'], BOARDDIR . '/packages/temp');
  1623. if ($context['extracted_files'] && !file_exists(BOARDDIR . '/packages/temp/package-info.xml'))
  1624. foreach ($context['extracted_files'] as $file)
  1625. if (basename($file['filename']) == 'package-info.xml')
  1626. {
  1627. $context['base_path'] = dirname($file['filename']) . '/';
  1628. break;
  1629. }
  1630. if (!isset($context['base_path']))
  1631. $context['base_path'] = '';
  1632. }
  1633. elseif (is_dir(BOARDDIR . '/packages/' . $context['filename']))
  1634. {
  1635. copytree(BOARDDIR . '/packages/' . $context['filename'], BOARDDIR . '/packages/temp');
  1636. $context['extracted_files'] = listtree(BOARDDIR . '/packages/temp');
  1637. $context['base_path'] = '';
  1638. }
  1639. // Load up any custom themes we may want to install into...
  1640. $request = $smcFunc['db_query']('', '
  1641. SELECT id_theme, variable, value
  1642. FROM {db_prefix}themes
  1643. WHERE (id_theme = {int:default_theme} OR id_theme IN ({array_int:known_theme_list}))
  1644. AND variable IN ({string:name}, {string:theme_dir})',
  1645. array(
  1646. 'known_theme_list' => explode(',', $modSettings['knownThemes']),
  1647. 'default_theme' => 1,
  1648. 'name' => 'name',
  1649. 'theme_dir' => 'theme_dir',
  1650. )
  1651. );
  1652. $theme_paths = array();
  1653. while ($row = $smcFunc['db_fetch_assoc']($request))
  1654. $theme_paths[$row['id_theme']][$row['variable']] = $row['value'];
  1655. $smcFunc['db_free_result']($request);
  1656. // Boardmod?
  1657. if (isset($_REQUEST['boardmod']))
  1658. $mod_actions = parseBoardMod(@file_get_contents(BOARDDIR . '/packages/temp/' . $context['base_path'] . $_REQUEST['filename']), true, $reverse, $theme_paths);
  1659. else
  1660. $mod_actions = parseModification(@file_get_contents(BOARDDIR . '/packages/temp/' . $context['base_path'] . $_REQUEST['filename']), true, $reverse, $theme_paths);
  1661. // Ok lets get the content of the file.
  1662. $context['operations'] = array(
  1663. 'search' => strtr(htmlspecialchars($mod_actions[$_REQUEST['operation_key']]['search_original']), array('[' => '&#91;', ']' => '&#93;')),
  1664. 'replace' => strtr(htmlspecialchars($mod_actions[$_REQUEST['operation_key']]['replace_original']), array('[' => '&#91;', ']' => '&#93;')),
  1665. 'position' => $mod_actions[$_REQUEST['operation_key']]['position'],
  1666. );
  1667. // Let's do some formatting...
  1668. $operation_text = $context['operations']['position'] == 'replace' ? 'operation_replace' : ($context['operations']['position'] == 'before' ? 'operation_after' : 'operation_before');
  1669. $context['operations']['search'] = parse_bbc('[code=' . $txt['operation_find'] . ']' . ($context['operations']['position'] == 'end' ? '?&gt;' : $context['operations']['search']) . '[/code]');
  1670. $context['operations']['replace'] = parse_bbc('[code=' . $txt[$operation_text] . ']' . $context['operations']['replace'] . '[/code]');
  1671. // No layers
  1672. $context['template_layers'] = array();
  1673. $context['sub_template'] = 'view_operations';
  1674. }
  1675. /**
  1676. * Allow the admin to reset permissions on files.
  1677. */
  1678. function PackagePermissions()
  1679. {
  1680. global $context, $txt, $modSettings, $smcFunc, $package_ftp;
  1681. // Let's try and be good, yes?
  1682. checkSession('get');
  1683. // If we're restoring permissions this is just a pass through really.
  1684. if (isset($_GET['restore']))
  1685. {
  1686. create_chmod_control(array(), array(), true);
  1687. fatal_lang_error('no_access', false);
  1688. }
  1689. // This is a memory eat.
  1690. setMemoryLimit('128M');
  1691. @set_time_limit(600);
  1692. // Load up some FTP stuff.
  1693. create_chmod_control();
  1694. if (empty($package_ftp) && !isset($_POST['skip_ftp']))
  1695. {
  1696. require_once(SUBSDIR . '/FTPConnection.class.php');
  1697. $ftp = new Ftp_Connection(null);
  1698. list ($username, $detect_path, $found_path) = $ftp->detect_path(BOARDDIR);
  1699. $context['package_ftp'] = array(
  1700. 'server' => isset($modSettings['package_server']) ? $modSettings['package_server'] : 'localhost',
  1701. 'port' => isset($modSettings['package_port']) ? $modSettings['package_port'] : '21',
  1702. 'username' => empty($username) ? (isset($modSettings['package_username']) ? $modSettings['package_username'] : '') : $username,
  1703. 'path' => $detect_path,
  1704. 'form_elements_only' => true,
  1705. );
  1706. }
  1707. else
  1708. $context['ftp_connected'] = true;
  1709. // Define the template.
  1710. $context['page_title'] = $txt['package_file_perms'];
  1711. $context['sub_template'] = 'file_permissions';
  1712. // Define what files we're interested in, as a tree.
  1713. $context['file_tree'] = array(
  1714. strtr(BOARDDIR, array('\\' => '/')) => array(
  1715. 'type' => 'dir',
  1716. 'contents' => array(
  1717. 'agreement.txt' => array(
  1718. 'type' => 'file',
  1719. 'writable_on' => 'standard',
  1720. ),
  1721. 'Settings.php' => array(
  1722. 'type' => 'file',
  1723. 'writable_on' => 'restrictive',
  1724. ),
  1725. 'Settings_bak.php' => array(
  1726. 'type' => 'file',
  1727. 'writable_on' => 'restrictive',
  1728. ),
  1729. 'attachments' => array(
  1730. 'type' => 'dir',
  1731. 'writable_on' => 'restrictive',
  1732. ),
  1733. 'avatars' => array(
  1734. 'type' => 'dir',
  1735. 'writable_on' => 'standard',
  1736. ),
  1737. 'cache' => array(
  1738. 'type' => 'dir',
  1739. 'writable_on' => 'restrictive',
  1740. ),
  1741. 'custom_avatar_dir' => array(
  1742. 'type' => 'dir',
  1743. 'writable_on' => 'restrictive',
  1744. ),
  1745. 'Smileys' => array(
  1746. 'type' => 'dir_recursive',
  1747. 'writable_on' => 'standard',
  1748. ),
  1749. 'Sources' => array(
  1750. 'type' => 'dir',
  1751. 'list_contents' => true,
  1752. 'writable_on' => 'standard',
  1753. ),
  1754. 'Themes' => array(
  1755. 'type' => 'dir_recursive',
  1756. 'writable_on' => 'standard',
  1757. 'contents' => array(
  1758. 'default' => array(
  1759. 'type' => 'dir_recursive',
  1760. 'list_contents' => true,
  1761. 'contents' => array(
  1762. 'languages' => array(
  1763. 'type' => 'dir',
  1764. 'list_contents' => true,
  1765. ),
  1766. ),
  1767. ),
  1768. ),
  1769. ),
  1770. 'Packages' => array(
  1771. 'type' => 'dir',
  1772. 'writable_on' => 'standard',
  1773. 'contents' => array(
  1774. 'temp' => array(
  1775. 'type' => 'dir',
  1776. ),
  1777. 'backup' => array(
  1778. 'type' => 'dir',
  1779. ),
  1780. 'installed.list' => array(
  1781. 'type' => 'file',
  1782. 'writable_on' => 'standard',
  1783. ),
  1784. ),
  1785. ),
  1786. ),
  1787. ),
  1788. );
  1789. // Directories that can move.
  1790. if (substr(SOURCEDIR, 0, strlen(BOARDDIR)) != BOARDDIR)
  1791. {
  1792. unset($context['file_tree'][strtr(BOARDDIR, array('\\' => '/'))]['contents']['Sources']);
  1793. $context['file_tree'][strtr(SOURCEDIR, array('\\' => '/'))] = array(
  1794. 'type' => 'dir',
  1795. 'list_contents' => true,
  1796. 'writable_on' => 'standard',
  1797. );
  1798. }
  1799. // Moved the cache?
  1800. if (substr(CACHEDIR, 0, strlen(BOARDDIR)) != BOARDDIR)
  1801. {
  1802. unset($context['file_tree'][strtr(BOARDDIR, array('\\' => '/'))]['contents']['cache']);
  1803. $context['file_tree'][strtr(CACHEDIR, array('\\' => '/'))] = array(
  1804. 'type' => 'dir',
  1805. 'list_contents' => false,
  1806. 'writable_on' => 'restrictive',
  1807. );
  1808. }
  1809. // Are we using multiple attachment directories?
  1810. if (!empty($modSettings['currentAttachmentUploadDir']))
  1811. {
  1812. unset($context['file_tree'][strtr(BOARDDIR, array('\\' => '/'))]['contents']['attachments']);
  1813. if (!is_array($modSettings['attachmentUploadDir']))
  1814. $modSettings['attachmentUploadDir'] = unserialize($modSettings['attachmentUploadDir']);
  1815. // @todo Should we suggest non-current directories be read only?
  1816. foreach ($modSettings['attachmentUploadDir'] as $dir)
  1817. $context['file_tree'][strtr($dir, array('\\' => '/'))] = array(
  1818. 'type' => 'dir',
  1819. 'writable_on' => 'restrictive',
  1820. );
  1821. }
  1822. elseif (substr($modSettings['attachmentUploadDir'], 0, strlen(BOARDDIR)) != BOARDDIR)
  1823. {
  1824. unset($context['file_tree'][strtr(BOARDDIR, array('\\' => '/'))]['contents']['attachments']);
  1825. $context['file_tree'][strtr($modSettings['attachmentUploadDir'], array('\\' => '/'))] = array(
  1826. 'type' => 'dir',
  1827. 'writable_on' => 'restrictive',
  1828. );
  1829. }
  1830. if (substr($modSettings['smileys_dir'], 0, strlen(BOARDDIR)) != BOARDDIR)
  1831. {
  1832. unset($context['file_tree'][strtr(BOARDDIR, array('\\' => '/'))]['contents']['smileys']);
  1833. $context['file_tree'][strtr($modSettings['smileys_dir'], array('\\' => '/'))] = array(
  1834. 'type' => 'dir_recursive',
  1835. 'writable_on' => 'standard',
  1836. );
  1837. }
  1838. if (substr($modSettings['avatar_directory'], 0, strlen(BOARDDIR)) != BOARDDIR)
  1839. {
  1840. unset($context['file_tree'][strtr(BOARDDIR, array('\\' => '/'))]['contents']['avatars']);
  1841. $context['file_tree'][strtr($modSettings['avatar_directory'], array('\\' => '/'))] = array(
  1842. 'type' => 'dir',
  1843. 'writable_on' => 'standard',
  1844. );
  1845. }
  1846. if (isset($modSettings['custom_avatar_dir']) && substr($modSettings['custom_avatar_dir'], 0, strlen(BOARDDIR)) != BOARDDIR)
  1847. {
  1848. unset($context['file_tree'][strtr(BOARDDIR, array('\\' => '/'))]['contents']['custom_avatar_dir']);
  1849. $context['file_tree'][strtr($modSettings['custom_avatar_dir'], array('\\' => '/'))] = array(
  1850. 'type' => 'dir',
  1851. 'writable_on' => 'restrictive',
  1852. );
  1853. }
  1854. // Load up any custom themes.
  1855. $request = $smcFunc['db_query']('', '
  1856. SELECT value
  1857. FROM {db_prefix}themes
  1858. WHERE id_theme > {int:default_theme_id}
  1859. AND id_member = {int:guest_id}
  1860. AND variable = {string:theme_dir}
  1861. ORDER BY value ASC',
  1862. array(
  1863. 'default_theme_id' => 1,
  1864. 'guest_id' => 0,
  1865. 'theme_dir' => 'theme_dir',
  1866. )
  1867. );
  1868. while ($row = $smcFunc['db_fetch_assoc']($request))
  1869. {
  1870. if (substr(strtolower(strtr($row['value'], array('\\' => '/'))), 0, strlen(BOARDDIR) + 7) == strtolower(strtr(BOARDDIR, array('\\' => '/')) . '/Themes'))
  1871. $context['file_tree'][strtr(BOARDDIR, array('\\' => '/'))]['contents']['Themes']['contents'][substr($row['value'], strlen(BOARDDIR) + 8)] = array(
  1872. 'type' => 'dir_recursive',
  1873. 'list_contents' => true,
  1874. 'contents' => array(
  1875. 'languages' => array(
  1876. 'type' => 'dir',
  1877. 'list_contents' => true,
  1878. ),
  1879. ),
  1880. );
  1881. else
  1882. {
  1883. $context['file_tree'][strtr($row['value'], array('\\' => '/'))] = array(
  1884. 'type' => 'dir_recursive',
  1885. 'list_contents' => true,
  1886. 'contents' => array(
  1887. 'languages' => array(
  1888. 'type' => 'dir',
  1889. 'list_contents' => true,
  1890. ),
  1891. ),
  1892. );
  1893. }
  1894. }
  1895. $smcFunc['db_free_result']($request);
  1896. // If we're submitting then let's move on to another function to keep things cleaner..
  1897. if (isset($_POST['action_changes']))
  1898. return PackagePermissionsAction();
  1899. $context['look_for'] = array();
  1900. // Are we looking for a particular tree - normally an expansion?
  1901. if (!empty($_REQUEST['find']))
  1902. $context['look_for'][] = base64_decode($_REQUEST['find']);
  1903. // Only that tree?
  1904. $context['only_find'] = isset($_GET['xml']) && !empty($_REQUEST['onlyfind']) ? $_REQUEST['onlyfind'] : '';
  1905. if ($context['only_find'])
  1906. $context['look_for'][] = $context['only_find'];
  1907. // Have we got a load of back-catalogue trees to expand from a submit etc?
  1908. if (!empty($_GET['back_look']))
  1909. {
  1910. $potententialTrees = unserialize(base64_decode($_GET['back_look']));
  1911. foreach ($potententialTrees as $tree)
  1912. $context['look_for'][] = $tree;
  1913. }
  1914. // ... maybe posted?
  1915. if (!empty($_POST['back_look']))
  1916. $context['only_find'] = array_merge($context['only_find'], $_POST['back_look']);
  1917. $context['back_look_data'] = base64_encode(serialize(array_slice($context['look_for'], 0, 15)));
  1918. // Are we finding more files than first thought?
  1919. $context['file_offset'] = !empty($_REQUEST['fileoffset']) ? (int) $_REQUEST['fileoffset'] : 0;
  1920. // Don't list more than this many files in a directory.
  1921. $context['file_limit'] = 150;
  1922. // How many levels shall we show?
  1923. $context['default_level'] = empty($context['only_find']) ? 2 : 25;
  1924. // This will be used if we end up catching XML data.
  1925. $context['xml_data'] = array(
  1926. 'roots' => array(
  1927. 'identifier' => 'root',
  1928. 'children' => array(
  1929. array(
  1930. 'value' => preg_replace('~[^A-Za-z0-9_\-=:]~', ':-:', $context['only_find']),
  1931. ),
  1932. ),
  1933. ),
  1934. 'folders' => array(
  1935. 'identifier' => 'folder',
  1936. 'children' => array(),
  1937. ),
  1938. );
  1939. foreach ($context['file_tree'] as $path => $data)
  1940. {
  1941. // Run this directory.
  1942. if (file_exists($path) && (empty($context['only_find']) || substr($context['only_find'], 0, strlen($path)) == $path))
  1943. {
  1944. // Get the first level down only.
  1945. fetchPerms__recursive($path, $context['file_tree'][$path], 1);
  1946. $context['file_tree'][$path]['perms'] = array(
  1947. 'chmod' => @is_writable($path),
  1948. 'perms' => @fileperms($path),
  1949. );
  1950. }
  1951. else
  1952. unset($context['file_tree'][$path]);
  1953. }
  1954. // Is this actually xml?
  1955. if (isset($_GET['xml']))
  1956. {
  1957. loadTemplate('Xml');
  1958. $context['sub_template'] = 'generic_xml';
  1959. $context['template_layers'] = array();
  1960. }
  1961. }
  1962. /**
  1963. * Checkes the permissions of all the areas that will be affected by the package
  1964. *
  1965. * @param type $path
  1966. * @param type $data
  1967. * @param type $level
  1968. * @return type
  1969. */
  1970. function fetchPerms__recursive($path, &$data, $level)
  1971. {
  1972. global $context;
  1973. $isLikelyPath = false;
  1974. foreach ($context['look_for'] as $possiblePath)
  1975. if (substr($possiblePath, 0, strlen($path)) == $path)
  1976. $isLikelyPath = true;
  1977. // Is this where we stop?
  1978. if (isset($_GET['xml']) && !empty($context['look_for']) && !$isLikelyPath)
  1979. return;
  1980. elseif ($level > $context['default_level'] && !$isLikelyPath)
  1981. return;
  1982. // Are we actually interested in saving this data?
  1983. $save_data = empty($context['only_find']) || $context['only_find'] == $path;
  1984. // @todo Shouldn't happen - but better error message?
  1985. if (!is_dir($path))
  1986. fatal_lang_error('no_access', false);
  1987. // This is where we put stuff we've found for sorting.
  1988. $foundData = array(
  1989. 'files' => array(),
  1990. 'folders' => array(),
  1991. );
  1992. $dh = opendir($path);
  1993. while ($entry = readdir($dh))
  1994. {
  1995. // Some kind of file?
  1996. if (is_file($path . '/' . $entry))
  1997. {
  1998. // Are we listing PHP files in this directory?
  1999. if ($save_data && !empty($data['list_contents']) && substr($entry, -4) == '.php')
  2000. $foundData['files'][$entry] = true;
  2001. // A file we were looking for.
  2002. elseif ($save_data && isset($data['contents'][$entry]))
  2003. $foundData['files'][$entry] = true;
  2004. }
  2005. // It's a directory - we're interested one way or another, probably...
  2006. elseif ($entry != '.' && $entry != '..')
  2007. {
  2008. // Going further?
  2009. if ((!empty($data['type']) && $data['type'] == 'dir_recursive') || (isset($data['contents'][$entry]) && (!empty($data['contents'][$entry]['list_contents']) || (!empty($data['contents'][$entry]['type']) && $data['contents'][$entry]['type'] == 'dir_recursive'))))
  2010. {
  2011. if (!isset($data['contents'][$entry]))
  2012. $foundData['folders'][$entry] = 'dir_recursive';
  2013. else
  2014. $foundData['folders'][$entry] = true;
  2015. // If this wasn't expected inherit the recusiveness...
  2016. if (!isset($data['contents'][$entry]))
  2017. // We need to do this as we will be going all recursive.
  2018. $data['contents'][$entry] = array(
  2019. 'type' => 'dir_recursive',
  2020. );
  2021. // Actually do the recursive stuff...
  2022. fetchPerms__recursive($path . '/' . $entry, $data['contents'][$entry], $level + 1);
  2023. }
  2024. // Maybe it is a folder we are not descending into.
  2025. elseif (isset($data['contents'][$entry]))
  2026. $foundData['folders'][$entry] = true;
  2027. // Otherwise we stop here.
  2028. }
  2029. }
  2030. closedir($dh);
  2031. // Nothing to see here?
  2032. if (!$save_data)
  2033. return;
  2034. // Now actually add the data, starting with the folders.
  2035. ksort($foundData['folders']);
  2036. foreach ($foundData['folders'] as $folder => $type)
  2037. {
  2038. $additional_data = array(
  2039. 'perms' => array(
  2040. 'chmod' => @is_writable($path . '/' . $folder),
  2041. 'perms' => @fileperms($path . '/' . $folder),
  2042. ),
  2043. );
  2044. if ($type !== true)
  2045. $additional_data['type'] = $type;
  2046. // If there's an offset ignore any folders in XML mode.
  2047. if (isset($_GET['xml']) && $context['file_offset'] == 0)
  2048. {
  2049. $context['xml_data']['folders']['children'][] = array(
  2050. 'attributes' => array(
  2051. 'writable' => $additional_data['perms']['chmod'] ? 1 : 0,
  2052. 'permissions' => substr(sprintf('%o', $additional_data['perms']['perms']), -4),
  2053. 'folder' => 1,
  2054. 'path' => $context['only_find'],
  2055. 'level' => $level,
  2056. 'more' => 0,
  2057. 'offset' => $context['file_offset'],
  2058. 'my_ident' => preg_replace('~[^A-Za-z0-9_\-=:]~', ':-:', $context['only_find'] . '/' . $folder),
  2059. 'ident' => preg_replace('~[^A-Za-z0-9_\-=:]~', ':-:', $context['only_find']),
  2060. ),
  2061. 'value' => $folder,
  2062. );
  2063. }
  2064. elseif (!isset($_GET['xml']))
  2065. {
  2066. if (isset($data['contents'][$folder]))
  2067. $data['contents'][$folder] = array_merge($data['contents'][$folder], $additional_data);
  2068. else
  2069. $data['contents'][$folder] = $additional_data;
  2070. }
  2071. }
  2072. // Now we want to do a similar thing with files.
  2073. ksort($foundData['files']);
  2074. $counter = -1;
  2075. foreach ($foundData['files'] as $file => $dummy)
  2076. {
  2077. $counter++;
  2078. // Have we reached our offset?
  2079. if ($context['file_offset'] > $counter)
  2080. continue;
  2081. // Gone too far?
  2082. if ($counter > ($context['file_offset'] + $context['file_limit']))
  2083. continue;
  2084. $additional_data = array(
  2085. 'perms' => array(
  2086. 'chmod' => @is_writable($path . '/' . $file),
  2087. 'perms' => @fileperms($path . '/' . $file),
  2088. ),
  2089. );
  2090. // XML?
  2091. if (isset($_GET['xml']))
  2092. {
  2093. $context['xml_data']['folders']['children'][] = array(
  2094. 'attributes' => array(
  2095. 'writable' => $additional_data['perms']['chmod'] ? 1 : 0,
  2096. 'permissions' => substr(sprintf('%o', $additional_data['perms']['perms']), -4),
  2097. 'folder' => 0,
  2098. 'path' => $context['only_find'],
  2099. 'level' => $level,
  2100. 'more' => $counter == ($context['file_offset'] + $context['file_limit']) ? 1 : 0,
  2101. 'offset' => $context['file_offset'],
  2102. 'my_ident' => preg_replace('~[^A-Za-z0-9_\-=:]~', ':-:', $context['only_find'] . '/' . $file),
  2103. 'ident' => preg_replace('~[^A-Za-z0-9_\-=:]~', ':-:', $context['only_find']),
  2104. ),
  2105. 'value' => $file,
  2106. );
  2107. }
  2108. elseif ($counter != ($context['file_offset'] + $context['file_limit']))
  2109. {
  2110. if (isset($data['contents'][$file]))
  2111. $data['contents'][$file] = array_merge($data['contents'][$file], $additional_data);
  2112. else
  2113. $data['contents'][$file] = $additional_data;
  2114. }
  2115. }
  2116. }
  2117. /**
  2118. * Actually action the permission changes they want.
  2119. */
  2120. function PackagePermissionsAction()
  2121. {
  2122. global $context, $txt, $time_start, $package_ftp;
  2123. umask(0);
  2124. $timeout_limit = 5;
  2125. $context['method'] = $_POST['method'] === 'individual' ? 'individual' : 'predefined';
  2126. $context['back_look_data'] = isset($_POST['back_look']) ? $_POST['back_look'] : array();
  2127. // Skipping use of FTP?
  2128. if (empty($package_ftp))
  2129. $context['skip_ftp'] = true;
  2130. // We'll start off in a good place, security. Make sure that if we're dealing with individual files that they seem in the right place.
  2131. if ($context['method'] === 'individual')
  2132. {
  2133. // Only these path roots are legal.
  2134. $legal_roots = array_keys($context['file_tree']);
  2135. $context['custom_value'] = (int) $_POST['custom_value'];
  2136. // Continuing?
  2137. if (isset($_POST['toProcess']))
  2138. $_POST['permStatus'] = unserialize(base64_decode($_POST['toProcess']));
  2139. if (isset($_POST['permStatus']))
  2140. {
  2141. $context['to_process'] = array();
  2142. $validate_custom = false;
  2143. foreach ($_POST['permStatus'] as $path => $status)
  2144. {
  2145. // Nothing to see here?
  2146. if ($status === 'no_change')
  2147. continue;
  2148. $legal = false;
  2149. foreach ($legal_roots as $root)
  2150. if (substr($path, 0, strlen($root)) == $root)
  2151. $legal = true;
  2152. if (!$legal)
  2153. continue;
  2154. // Check it exists.
  2155. if (!file_exists($path))
  2156. continue;
  2157. if ($status === 'custom')
  2158. $validate_custom = true;
  2159. // Now add it.
  2160. $context['to_process'][$path] = $status;
  2161. }
  2162. $context['total_items'] = isset($_POST['totalItems']) ? (int) $_POST['totalItems'] : count($context['to_process']);
  2163. // Make sure the chmod status is valid?
  2164. if ($validate_custom)
  2165. {
  2166. if (preg_match('~^[4567][4567][4567]$~', $context['custom_value']) == false)
  2167. fatal_error($txt['chmod_value_invalid']);
  2168. }
  2169. // Nothing to do?
  2170. if (empty($context['to_process']))
  2171. redirectexit('action=admin;area=packages;sa=perms' . (!empty($context['back_look_data']) ? ';back_look=' . base64_encode(serialize($context['back_look_data'])) : '') . ';' . $context['session_var'] . '=' . $context['session_id']);
  2172. }
  2173. // Should never get here,
  2174. else
  2175. fatal_lang_error('no_access', false);
  2176. // Setup the custom value.
  2177. $custom_value = octdec('0' . $context['custom_value']);
  2178. // Start processing items.
  2179. foreach ($context['to_process'] as $path => $status)
  2180. {
  2181. if (in_array($status, array('execute', 'writable', 'read')))
  2182. package_chmod($path, $status);
  2183. elseif ($status == 'custom' && !empty($custom_value))
  2184. {
  2185. // Use FTP if we have it.
  2186. if (!empty($package_ftp) && !empty($_SESSION['pack_ftp']))
  2187. {
  2188. $ftp_file = strtr($path, array($_SESSION['pack_ftp']['root'] => ''));
  2189. $package_ftp->chmod($ftp_file, $custom_value);
  2190. }
  2191. else
  2192. @chmod($path, $custom_value);
  2193. }
  2194. // This fish is fried...
  2195. unset($context['to_process'][$path]);
  2196. // See if we're out of time?
  2197. if (time() - array_sum(explode(' ', $time_start)) > $timeout_limit)
  2198. pausePackagePermissionsAction();
  2199. }
  2200. }
  2201. // If predefined this is a little different.
  2202. else
  2203. {
  2204. $context['predefined_type'] = isset($_POST['predefined']) ? $_POST['predefined'] : 'restricted';
  2205. $context['total_items'] = isset($_POST['totalItems']) ? (int) $_POST['totalItems'] : 0;
  2206. $context['directory_list'] = isset($_POST['dirList']) ? unserialize(base64_decode($_POST['dirList'])) : array();
  2207. $context['file_offset'] = isset($_POST['fileOffset']) ? (int) $_POST['fileOffset'] : 0;
  2208. // Haven't counted the items yet?
  2209. if (empty($context['total_items']))
  2210. {
  2211. /**
  2212. * Counts all the directorys under a given path
  2213. *
  2214. * @param type $dir
  2215. * @return integer
  2216. */
  2217. function count_directories__recursive($dir)
  2218. {
  2219. global $context;
  2220. $count = 0;
  2221. $dh = @opendir($dir);
  2222. while ($entry = readdir($dh))
  2223. {
  2224. if ($entry != '.' && $entry != '..' && is_dir($dir . '/' . $entry))
  2225. {
  2226. $context['directory_list'][$dir . '/' . $entry] = 1;
  2227. $count++;
  2228. $count += count_directories__recursive($dir . '/' . $entry);
  2229. }
  2230. }
  2231. closedir($dh);
  2232. return $count;
  2233. }
  2234. foreach ($context['file_tree'] as $path => $data)
  2235. {
  2236. if (is_dir($path))
  2237. {
  2238. $context['directory_list'][$path] = 1;
  2239. $context['total_items'] += count_directories__recursive($path);
  2240. $context['total_items']++;
  2241. }
  2242. }
  2243. }
  2244. // Have we built up our list of special files?
  2245. if (!isset($_POST['specialFiles']) && $context['predefined_type'] != 'free')
  2246. {
  2247. $context['special_files'] = array();
  2248. /**
  2249. * Builds a list of special files recusivly for a given path
  2250. *
  2251. * @param type $path
  2252. * @param type $data
  2253. */
  2254. function build_special_files__recursive($path, &$data)
  2255. {
  2256. global $context;
  2257. if (!empty($data['writable_on']))
  2258. if ($context['predefined_type'] === 'standard' || $data['writable_on'] === 'restrictive')
  2259. $context['special_files'][$path] = 1;
  2260. if (!empty($data['contents']))
  2261. foreach ($data['contents'] as $name => $contents)
  2262. build_special_files__recursive($path . '/' . $name, $contents);
  2263. }
  2264. foreach ($context['file_tree'] as $path => $data)
  2265. build_special_files__recursive($path, $data);
  2266. }
  2267. // Free doesn't need special files.
  2268. elseif ($context['predefined_type'] === 'free')
  2269. $context['special_files'] = array();
  2270. else
  2271. $context['special_files'] = unserialize(base64_decode($_POST['specialFiles']));
  2272. // Now we definitely know where we are, we need to go through again doing the chmod!
  2273. foreach ($context['directory_list'] as $path => $dummy)
  2274. {
  2275. // Do the contents of the directory first.
  2276. $dh = @opendir($path);
  2277. $file_count = 0;
  2278. $dont_chmod = false;
  2279. while ($entry = readdir($dh))
  2280. {
  2281. $file_count++;
  2282. // Actually process this file?
  2283. if (!$dont_chmod && !is_dir($path . '/' . $entry) && (empty($context['file_offset']) || $context['file_offset'] < $file_count))
  2284. {
  2285. $status = $context['predefined_type'] === 'free' || isset($context['special_files'][$path . '/' . $entry]) ? 'writable' : 'execute';
  2286. package_chmod($path . '/' . $entry, $status);
  2287. }
  2288. // See if we're out of time?
  2289. if (!$dont_chmod && time() - array_sum(explode(' ', $time_start)) > $timeout_limit)
  2290. {
  2291. $dont_chmod = true;
  2292. // Make note of how far we have come so we restart at the right point
  2293. $context['file_offset'] = $file_count;
  2294. break;
  2295. }
  2296. }
  2297. closedir($dh);
  2298. // If this is set it means we timed out half way through.
  2299. if ($dont_chmod)
  2300. {
  2301. $context['total_files'] = $file_count;
  2302. pausePackagePermissionsAction();
  2303. }
  2304. // Do the actual directory.
  2305. $status = $context['predefined_type'] === 'free' || isset($context['special_files'][$path]) ? 'writable' : 'execute';
  2306. package_chmod($path, $status);
  2307. // We've finished the directory so no file offset, and no record.
  2308. $context['file_offset'] = 0;
  2309. unset($context['directory_list'][$path]);
  2310. // See if we're out of time?
  2311. if (time() - array_sum(explode(' ', $time_start)) > $timeout_limit)
  2312. pausePackagePermissionsAction();
  2313. }
  2314. }
  2315. // If we're here we are done!
  2316. redirectexit('action=admin;area=packages;sa=perms' . (!empty($context['back_look_data']) ? ';back_look=' . base64_encode(serialize($context['back_look_data'])) : '') . ';' . $context['session_var'] . '=' . $context['session_id']);
  2317. }
  2318. /**
  2319. * Function called to briefly pause execution of directory/file chmod actions
  2320. * Called by PackagePermissionsAction().
  2321. *
  2322. */
  2323. function pausePackagePermissionsAction()
  2324. {
  2325. global $context, $txt;
  2326. // Try get more time...
  2327. @set_time_limit(600);
  2328. if (function_exists('apache_reset_timeout'))
  2329. @apache_reset_timeout();
  2330. // Set up the items for the pause form
  2331. $context['sub_template'] = 'pause_action_permissions';
  2332. $context['page_title'] = $txt['package_file_perms_applying'];
  2333. // And how are we progressing with our directories
  2334. $context['remaining_items'] = count($context['method'] == 'individual' ? $context['to_process'] : $context['directory_list']);
  2335. $context['progress_message'] = sprintf($context['method'] == 'individual' ? $txt['package_file_perms_items_done'] : $txt['package_file_perms_dirs_done'], $context['total_items'] - $context['remaining_items'], $context['total_items']);
  2336. $context['progress_percent'] = round(($context['total_items'] - $context['remaining_items']) / $context['total_items'] * 100, 1);
  2337. // Never more than 100%!
  2338. $context['progress_percent'] = min($context['progress_percent'], 100);
  2339. // And how are we progessing with files within a directory
  2340. if ($context['method'] != 'individual' && !empty($context['total_files']))
  2341. {
  2342. $context['file_progress_message'] = sprintf($txt['package_file_perms_files_done'], $context['file_offset'], $context['total_files']);
  2343. $context['file_progress_percent'] = round($context['file_offset'] / $context['total_files'] * 100, 1);
  2344. // Never more than 100%!
  2345. $context['file_progress_percent'] = min($context['file_progress_percent'], 100);
  2346. }
  2347. obExit();
  2348. }
  2349. /**
  2350. * Test an FTP connection.
  2351. */
  2352. function PackageFTPTest()
  2353. {
  2354. global $context, $txt, $package_ftp;
  2355. checkSession('get');
  2356. // Try to make the FTP connection.
  2357. create_chmod_control(array(), array('force_find_error' => true));
  2358. // Deal with the template stuff.
  2359. loadTemplate('Xml');
  2360. $context['sub_template'] = 'generic_xml';
  2361. $context['template_layers'] = array();
  2362. // Define the return data, this is simple.
  2363. $context['xml_data'] = array(
  2364. 'results' => array(
  2365. 'identifier' => 'result',
  2366. 'children' => array(
  2367. array(
  2368. 'attributes' => array(
  2369. 'success' => !empty($package_ftp) ? 1 : 0,
  2370. ),
  2371. 'value' => !empty($package_ftp) ? $txt['package_ftp_test_success'] : (isset($context['package_ftp'], $context['package_ftp']['error']) ? $context['package_ftp']['error'] : $txt['package_ftp_test_failed']),
  2372. ),
  2373. ),
  2374. ),
  2375. );
  2376. }