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

/php/Sources/Packages.php

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