PageRenderTime 49ms CodeModel.GetById 9ms RepoModel.GetById 0ms app.codeStats 0ms

/forum/Sources/Packages.php

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