PageRenderTime 62ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

/sources/admin/Themes.php

https://github.com/Arantor/Elkarte
PHP | 2214 lines | 1682 code | 291 blank | 241 comment | 303 complexity | d32e679edfe046490fdab9eb8eb64c63 MD5 | raw file
Possible License(s): BSD-3-Clause, LGPL-3.0
  1. <?php
  2. /**
  3. * @name ElkArte Forum
  4. * @copyright ElkArte Forum contributors
  5. * @license BSD http://opensource.org/licenses/BSD-3-Clause
  6. *
  7. * This software is a derived product, based on:
  8. *
  9. * Simple Machines Forum (SMF)
  10. * copyright: 2011 Simple Machines (http://www.simplemachines.org)
  11. * license: BSD, See included LICENSE.TXT for terms and conditions.
  12. *
  13. * @version 1.0 Alpha
  14. *
  15. * This file concerns itself almost completely with theme administration.
  16. * Its tasks include changing theme settings, installing and removing
  17. * themes, choosing the current theme, and editing themes.
  18. *
  19. * @todo Update this for the new package manager?
  20. *
  21. * Creating and distributing theme packages:
  22. * There isn't that much required to package and distribute your own themes...
  23. * just do the following:
  24. * - create a theme_info.xml file, with the root element theme-info.
  25. * - its name should go in a name element, just like description.
  26. * - your name should go in author. (email in the email attribute.)
  27. * - any support website for the theme should be in website.
  28. * - layers and templates (non-default) should go in those elements ;).
  29. * - if the images dir isn't images, specify in the images element.
  30. * - any extra rows for themes should go in extra, serialized. (as in array(variable => value).)
  31. * - tar and gzip the directory - and you're done!
  32. * - please include any special license in a license.txt file.
  33. *
  34. */
  35. if (!defined('ELKARTE'))
  36. die('No access...');
  37. /**
  38. * Subaction handler - manages the action and delegates control to the proper
  39. * sub-action.
  40. * It loads both the Themes and Settings language files.
  41. * Checks the session by GET or POST to verify the sent data.
  42. * Requires the user not be a guest. (@todo what?)
  43. * Accessed via ?action=admin;area=theme.
  44. */
  45. function action_thememain()
  46. {
  47. global $txt, $context, $scripturl;
  48. // Load the important language files...
  49. loadLanguage('Themes');
  50. loadLanguage('Settings');
  51. // No funny business - guests only.
  52. is_not_guest();
  53. // Default the page title to Theme Administration by default.
  54. $context['page_title'] = $txt['themeadmin_title'];
  55. // Theme administration, removal, choice, or installation...
  56. $subActions = array(
  57. 'admin' => 'action_admintheme',
  58. 'list' => 'action_themelist',
  59. 'reset' => 'SetThemeOptions',
  60. 'options' => 'SetThemeOptions',
  61. 'install' => 'action_installtheme',
  62. 'remove' => 'action_removetheme',
  63. 'pick' => 'action_picktheme',
  64. 'edit' => 'action_edittheme',
  65. 'copy' => 'action_copytemplate',
  66. );
  67. // @todo Layout Settings?
  68. if (!empty($context['admin_menu_name']))
  69. {
  70. $context[$context['admin_menu_name']]['tab_data'] = array(
  71. 'title' => $txt['themeadmin_title'],
  72. 'help' => 'themes',
  73. 'description' => $txt['themeadmin_description'],
  74. 'tabs' => array(
  75. 'admin' => array(
  76. 'description' => $txt['themeadmin_admin_desc'],
  77. ),
  78. 'list' => array(
  79. 'description' => $txt['themeadmin_list_desc'],
  80. ),
  81. 'reset' => array(
  82. 'description' => $txt['themeadmin_reset_desc'],
  83. ),
  84. 'edit' => array(
  85. 'description' => $txt['themeadmin_edit_desc'],
  86. ),
  87. ),
  88. );
  89. }
  90. // Follow the sa or just go to administration.
  91. if (isset($_GET['sa']) && !empty($subActions[$_GET['sa']]))
  92. $subActions[$_GET['sa']]();
  93. else
  94. $subActions['admin']();
  95. }
  96. /**
  97. * This function allows administration of themes and their settings,
  98. * as well as global theme settings.
  99. * - sets the settings theme_allow, theme_guests, and knownThemes.
  100. * - requires the admin_forum permission.
  101. * - accessed with ?action=admin;area=theme;sa=admin.
  102. *
  103. * @uses Themes template
  104. * @uses Admin language file
  105. */
  106. function action_admintheme()
  107. {
  108. global $context, $modSettings, $smcFunc;
  109. loadLanguage('Admin');
  110. isAllowedTo('admin_forum');
  111. // If we aren't submitting - that is, if we are about to...
  112. if (!isset($_POST['save']))
  113. {
  114. loadTemplate('Themes');
  115. // Make our known themes a little easier to work with.
  116. $knownThemes = !empty($modSettings['knownThemes']) ? explode(',',$modSettings['knownThemes']) : array();
  117. // Load up all the themes.
  118. $request = $smcFunc['db_query']('', '
  119. SELECT id_theme, value AS name
  120. FROM {db_prefix}themes
  121. WHERE variable = {string:name}
  122. AND id_member = {int:no_member}
  123. ORDER BY id_theme',
  124. array(
  125. 'no_member' => 0,
  126. 'name' => 'name',
  127. )
  128. );
  129. $context['themes'] = array();
  130. while ($row = $smcFunc['db_fetch_assoc']($request))
  131. $context['themes'][] = array(
  132. 'id' => $row['id_theme'],
  133. 'name' => $row['name'],
  134. 'known' => in_array($row['id_theme'], $knownThemes),
  135. );
  136. $smcFunc['db_free_result']($request);
  137. // Can we create a new theme?
  138. $context['can_create_new'] = is_writable(BOARDDIR . '/Themes');
  139. $context['new_theme_dir'] = substr(realpath(BOARDDIR . '/Themes/default'), 0, -7);
  140. // Look for a non existent theme directory. (ie theme87.)
  141. $theme_dir = BOARDDIR . '/Themes/theme';
  142. $i = 1;
  143. while (file_exists($theme_dir . $i))
  144. $i++;
  145. $context['new_theme_name'] = 'theme' . $i;
  146. createToken('admin-tm');
  147. }
  148. else
  149. {
  150. checkSession();
  151. validateToken('admin-tm');
  152. if (isset($_POST['options']['known_themes']))
  153. foreach ($_POST['options']['known_themes'] as $key => $id)
  154. $_POST['options']['known_themes'][$key] = (int) $id;
  155. else
  156. fatal_lang_error('themes_none_selectable', false);
  157. if (!in_array($_POST['options']['theme_guests'], $_POST['options']['known_themes']))
  158. fatal_lang_error('themes_default_selectable', false);
  159. // Commit the new settings.
  160. updateSettings(array(
  161. 'theme_allow' => $_POST['options']['theme_allow'],
  162. 'theme_guests' => $_POST['options']['theme_guests'],
  163. 'knownThemes' => implode(',', $_POST['options']['known_themes']),
  164. ));
  165. if ((int) $_POST['theme_reset'] == 0 || in_array($_POST['theme_reset'], $_POST['options']['known_themes']))
  166. updateMemberData(null, array('id_theme' => (int) $_POST['theme_reset']));
  167. redirectexit('action=admin;area=theme;' . $context['session_var'] . '=' . $context['session_id'] . ';sa=admin');
  168. }
  169. }
  170. /**
  171. * This function lists the available themes and provides an interface to reset
  172. * the paths of all the installed themes.
  173. */
  174. function action_themelist()
  175. {
  176. global $context, $boardurl, $smcFunc;
  177. loadLanguage('Admin');
  178. isAllowedTo('admin_forum');
  179. if (isset($_REQUEST['th']))
  180. return SetThemeSettings();
  181. if (isset($_POST['save']))
  182. {
  183. checkSession();
  184. validateToken('admin-tl');
  185. $request = $smcFunc['db_query']('', '
  186. SELECT id_theme, variable, value
  187. FROM {db_prefix}themes
  188. WHERE variable IN ({string:theme_dir}, {string:theme_url}, {string:images_url}, {string:base_theme_dir}, {string:base_theme_url}, {string:base_images_url})
  189. AND id_member = {int:no_member}',
  190. array(
  191. 'no_member' => 0,
  192. 'theme_dir' => 'theme_dir',
  193. 'theme_url' => 'theme_url',
  194. 'images_url' => 'images_url',
  195. 'base_theme_dir' => 'base_theme_dir',
  196. 'base_theme_url' => 'base_theme_url',
  197. 'base_images_url' => 'base_images_url',
  198. )
  199. );
  200. $themes = array();
  201. while ($row = $smcFunc['db_fetch_assoc']($request))
  202. $themes[$row['id_theme']][$row['variable']] = $row['value'];
  203. $smcFunc['db_free_result']($request);
  204. $setValues = array();
  205. foreach ($themes as $id => $theme)
  206. {
  207. if (file_exists($_POST['reset_dir'] . '/' . basename($theme['theme_dir'])))
  208. {
  209. $setValues[] = array($id, 0, 'theme_dir', realpath($_POST['reset_dir'] . '/' . basename($theme['theme_dir'])));
  210. $setValues[] = array($id, 0, 'theme_url', $_POST['reset_url'] . '/' . basename($theme['theme_dir']));
  211. $setValues[] = array($id, 0, 'images_url', $_POST['reset_url'] . '/' . basename($theme['theme_dir']) . '/' . basename($theme['images_url']));
  212. }
  213. if (isset($theme['base_theme_dir']) && file_exists($_POST['reset_dir'] . '/' . basename($theme['base_theme_dir'])))
  214. {
  215. $setValues[] = array($id, 0, 'base_theme_dir', realpath($_POST['reset_dir'] . '/' . basename($theme['base_theme_dir'])));
  216. $setValues[] = array($id, 0, 'base_theme_url', $_POST['reset_url'] . '/' . basename($theme['base_theme_dir']));
  217. $setValues[] = array($id, 0, 'base_images_url', $_POST['reset_url'] . '/' . basename($theme['base_theme_dir']) . '/' . basename($theme['base_images_url']));
  218. }
  219. cache_put_data('theme_settings-' . $id, null, 90);
  220. }
  221. if (!empty($setValues))
  222. {
  223. $smcFunc['db_insert']('replace',
  224. '{db_prefix}themes',
  225. array('id_theme' => 'int', 'id_member' => 'int', 'variable' => 'string-255', 'value' => 'string-65534'),
  226. $setValues,
  227. array('id_theme', 'variable', 'id_member')
  228. );
  229. }
  230. redirectexit('action=admin;area=theme;sa=list;' . $context['session_var'] . '=' . $context['session_id']);
  231. }
  232. loadTemplate('Themes');
  233. $request = $smcFunc['db_query']('', '
  234. SELECT id_theme, variable, value
  235. FROM {db_prefix}themes
  236. WHERE variable IN ({string:name}, {string:theme_dir}, {string:theme_url}, {string:images_url})
  237. AND id_member = {int:no_member}',
  238. array(
  239. 'no_member' => 0,
  240. 'name' => 'name',
  241. 'theme_dir' => 'theme_dir',
  242. 'theme_url' => 'theme_url',
  243. 'images_url' => 'images_url',
  244. )
  245. );
  246. $context['themes'] = array();
  247. while ($row = $smcFunc['db_fetch_assoc']($request))
  248. {
  249. if (!isset($context['themes'][$row['id_theme']]))
  250. $context['themes'][$row['id_theme']] = array(
  251. 'id' => $row['id_theme'],
  252. );
  253. $context['themes'][$row['id_theme']][$row['variable']] = $row['value'];
  254. }
  255. $smcFunc['db_free_result']($request);
  256. foreach ($context['themes'] as $i => $theme)
  257. {
  258. $context['themes'][$i]['theme_dir'] = realpath($context['themes'][$i]['theme_dir']);
  259. if (file_exists($context['themes'][$i]['theme_dir'] . '/index.template.php'))
  260. {
  261. // Fetch the header... a good 256 bytes should be more than enough.
  262. $fp = fopen($context['themes'][$i]['theme_dir'] . '/index.template.php', 'rb');
  263. $header = fread($fp, 256);
  264. fclose($fp);
  265. // Can we find a version comment, at all?
  266. if (preg_match('~\*\s@version\s+(.+)[\s]{2}~i', $header, $match) == 1)
  267. $context['themes'][$i]['version'] = $match[1];
  268. }
  269. $context['themes'][$i]['valid_path'] = file_exists($context['themes'][$i]['theme_dir']) && is_dir($context['themes'][$i]['theme_dir']);
  270. }
  271. $context['reset_dir'] = realpath(BOARDDIR . '/Themes');
  272. $context['reset_url'] = $boardurl . '/Themes';
  273. $context['sub_template'] = 'list_themes';
  274. createToken('admin-tl');
  275. createToken('admin-tr', 'request');
  276. }
  277. /**
  278. * Administrative global settings.
  279. */
  280. function SetThemeOptions()
  281. {
  282. global $txt, $context, $settings, $modSettings, $smcFunc;
  283. $_GET['th'] = isset($_GET['th']) ? (int) $_GET['th'] : (isset($_GET['id']) ? (int) $_GET['id'] : 0);
  284. isAllowedTo('admin_forum');
  285. if (empty($_GET['th']) && empty($_GET['id']))
  286. {
  287. $request = $smcFunc['db_query']('', '
  288. SELECT id_theme, variable, value
  289. FROM {db_prefix}themes
  290. WHERE variable IN ({string:name}, {string:theme_dir})
  291. AND id_member = {int:no_member}',
  292. array(
  293. 'no_member' => 0,
  294. 'name' => 'name',
  295. 'theme_dir' => 'theme_dir',
  296. )
  297. );
  298. $context['themes'] = array();
  299. while ($row = $smcFunc['db_fetch_assoc']($request))
  300. {
  301. if (!isset($context['themes'][$row['id_theme']]))
  302. $context['themes'][$row['id_theme']] = array(
  303. 'id' => $row['id_theme'],
  304. 'num_default_options' => 0,
  305. 'num_members' => 0,
  306. );
  307. $context['themes'][$row['id_theme']][$row['variable']] = $row['value'];
  308. }
  309. $smcFunc['db_free_result']($request);
  310. $request = $smcFunc['db_query']('', '
  311. SELECT id_theme, COUNT(*) AS value
  312. FROM {db_prefix}themes
  313. WHERE id_member = {int:guest_member}
  314. GROUP BY id_theme',
  315. array(
  316. 'guest_member' => -1,
  317. )
  318. );
  319. while ($row = $smcFunc['db_fetch_assoc']($request))
  320. $context['themes'][$row['id_theme']]['num_default_options'] = $row['value'];
  321. $smcFunc['db_free_result']($request);
  322. // Need to make sure we don't do custom fields.
  323. $request = $smcFunc['db_query']('', '
  324. SELECT col_name
  325. FROM {db_prefix}custom_fields',
  326. array(
  327. )
  328. );
  329. $customFields = array();
  330. while ($row = $smcFunc['db_fetch_assoc']($request))
  331. $customFields[] = $row['col_name'];
  332. $smcFunc['db_free_result']($request);
  333. $customFieldsQuery = empty($customFields) ? '' : ('AND variable NOT IN ({array_string:custom_fields})');
  334. $request = $smcFunc['db_query']('themes_count', '
  335. SELECT COUNT(DISTINCT id_member) AS value, id_theme
  336. FROM {db_prefix}themes
  337. WHERE id_member > {int:no_member}
  338. ' . $customFieldsQuery . '
  339. GROUP BY id_theme',
  340. array(
  341. 'no_member' => 0,
  342. 'custom_fields' => empty($customFields) ? array() : $customFields,
  343. )
  344. );
  345. while ($row = $smcFunc['db_fetch_assoc']($request))
  346. $context['themes'][$row['id_theme']]['num_members'] = $row['value'];
  347. $smcFunc['db_free_result']($request);
  348. // There has to be a Settings template!
  349. foreach ($context['themes'] as $k => $v)
  350. if (empty($v['theme_dir']) || (!file_exists($v['theme_dir'] . '/Settings.template.php') && empty($v['num_members'])))
  351. unset($context['themes'][$k]);
  352. loadTemplate('Themes');
  353. $context['sub_template'] = 'reset_list';
  354. createToken('admin-stor', 'request');
  355. return;
  356. }
  357. // Submit?
  358. if (isset($_POST['submit']) && empty($_POST['who']))
  359. {
  360. checkSession();
  361. validateToken('admin-sto');
  362. if (empty($_POST['options']))
  363. $_POST['options'] = array();
  364. if (empty($_POST['default_options']))
  365. $_POST['default_options'] = array();
  366. // Set up the sql query.
  367. $setValues = array();
  368. foreach ($_POST['options'] as $opt => $val)
  369. $setValues[] = array(-1, $_GET['th'], $opt, is_array($val) ? implode(',', $val) : $val);
  370. $old_settings = array();
  371. foreach ($_POST['default_options'] as $opt => $val)
  372. {
  373. $old_settings[] = $opt;
  374. $setValues[] = array(-1, 1, $opt, is_array($val) ? implode(',', $val) : $val);
  375. }
  376. // If we're actually inserting something..
  377. if (!empty($setValues))
  378. {
  379. // Are there options in non-default themes set that should be cleared?
  380. if (!empty($old_settings))
  381. $smcFunc['db_query']('', '
  382. DELETE FROM {db_prefix}themes
  383. WHERE id_theme != {int:default_theme}
  384. AND id_member = {int:guest_member}
  385. AND variable IN ({array_string:old_settings})',
  386. array(
  387. 'default_theme' => 1,
  388. 'guest_member' => -1,
  389. 'old_settings' => $old_settings,
  390. )
  391. );
  392. $smcFunc['db_insert']('replace',
  393. '{db_prefix}themes',
  394. array('id_member' => 'int', 'id_theme' => 'int', 'variable' => 'string-255', 'value' => 'string-65534'),
  395. $setValues,
  396. array('id_theme', 'variable', 'id_member')
  397. );
  398. }
  399. cache_put_data('theme_settings-' . $_GET['th'], null, 90);
  400. cache_put_data('theme_settings-1', null, 90);
  401. redirectexit('action=admin;area=theme;' . $context['session_var'] . '=' . $context['session_id'] . ';sa=reset');
  402. }
  403. elseif (isset($_POST['submit']) && $_POST['who'] == 1)
  404. {
  405. checkSession();
  406. validateToken('admin-sto');
  407. $_POST['options'] = empty($_POST['options']) ? array() : $_POST['options'];
  408. $_POST['options_master'] = empty($_POST['options_master']) ? array() : $_POST['options_master'];
  409. $_POST['default_options'] = empty($_POST['default_options']) ? array() : $_POST['default_options'];
  410. $_POST['default_options_master'] = empty($_POST['default_options_master']) ? array() : $_POST['default_options_master'];
  411. $old_settings = array();
  412. foreach ($_POST['default_options'] as $opt => $val)
  413. {
  414. if ($_POST['default_options_master'][$opt] == 0)
  415. continue;
  416. elseif ($_POST['default_options_master'][$opt] == 1)
  417. {
  418. // Delete then insert for ease of database compatibility!
  419. $smcFunc['db_query']('substring', '
  420. DELETE FROM {db_prefix}themes
  421. WHERE id_theme = {int:default_theme}
  422. AND id_member != {int:no_member}
  423. AND variable = SUBSTRING({string:option}, 1, 255)',
  424. array(
  425. 'default_theme' => 1,
  426. 'no_member' => 0,
  427. 'option' => $opt,
  428. )
  429. );
  430. $smcFunc['db_query']('substring', '
  431. INSERT INTO {db_prefix}themes
  432. (id_member, id_theme, variable, value)
  433. SELECT id_member, 1, SUBSTRING({string:option}, 1, 255), SUBSTRING({string:value}, 1, 65534)
  434. FROM {db_prefix}members',
  435. array(
  436. 'option' => $opt,
  437. 'value' => (is_array($val) ? implode(',', $val) : $val),
  438. )
  439. );
  440. $old_settings[] = $opt;
  441. }
  442. elseif ($_POST['default_options_master'][$opt] == 2)
  443. {
  444. $smcFunc['db_query']('', '
  445. DELETE FROM {db_prefix}themes
  446. WHERE variable = {string:option_name}
  447. AND id_member > {int:no_member}',
  448. array(
  449. 'no_member' => 0,
  450. 'option_name' => $opt,
  451. )
  452. );
  453. }
  454. }
  455. // Delete options from other themes.
  456. if (!empty($old_settings))
  457. $smcFunc['db_query']('', '
  458. DELETE FROM {db_prefix}themes
  459. WHERE id_theme != {int:default_theme}
  460. AND id_member > {int:no_member}
  461. AND variable IN ({array_string:old_settings})',
  462. array(
  463. 'default_theme' => 1,
  464. 'no_member' => 0,
  465. 'old_settings' => $old_settings,
  466. )
  467. );
  468. foreach ($_POST['options'] as $opt => $val)
  469. {
  470. if ($_POST['options_master'][$opt] == 0)
  471. continue;
  472. elseif ($_POST['options_master'][$opt] == 1)
  473. {
  474. // Delete then insert for ease of database compatibility - again!
  475. $smcFunc['db_query']('substring', '
  476. DELETE FROM {db_prefix}themes
  477. WHERE id_theme = {int:current_theme}
  478. AND id_member != {int:no_member}
  479. AND variable = SUBSTRING({string:option}, 1, 255)',
  480. array(
  481. 'current_theme' => $_GET['th'],
  482. 'no_member' => 0,
  483. 'option' => $opt,
  484. )
  485. );
  486. $smcFunc['db_query']('substring', '
  487. INSERT INTO {db_prefix}themes
  488. (id_member, id_theme, variable, value)
  489. SELECT id_member, {int:current_theme}, SUBSTRING({string:option}, 1, 255), SUBSTRING({string:value}, 1, 65534)
  490. FROM {db_prefix}members',
  491. array(
  492. 'current_theme' => $_GET['th'],
  493. 'option' => $opt,
  494. 'value' => (is_array($val) ? implode(',', $val) : $val),
  495. )
  496. );
  497. }
  498. elseif ($_POST['options_master'][$opt] == 2)
  499. {
  500. $smcFunc['db_query']('', '
  501. DELETE FROM {db_prefix}themes
  502. WHERE variable = {string:option}
  503. AND id_member > {int:no_member}
  504. AND id_theme = {int:current_theme}',
  505. array(
  506. 'no_member' => 0,
  507. 'current_theme' => $_GET['th'],
  508. 'option' => $opt,
  509. )
  510. );
  511. }
  512. }
  513. redirectexit('action=admin;area=theme;' . $context['session_var'] . '=' . $context['session_id'] . ';sa=reset');
  514. }
  515. elseif (!empty($_GET['who']) && $_GET['who'] == 2)
  516. {
  517. checkSession('get');
  518. validateToken('admin-stor', 'request');
  519. // Don't delete custom fields!!
  520. if ($_GET['th'] == 1)
  521. {
  522. $request = $smcFunc['db_query']('', '
  523. SELECT col_name
  524. FROM {db_prefix}custom_fields',
  525. array(
  526. )
  527. );
  528. $customFields = array();
  529. while ($row = $smcFunc['db_fetch_assoc']($request))
  530. $customFields[] = $row['col_name'];
  531. $smcFunc['db_free_result']($request);
  532. }
  533. $customFieldsQuery = empty($customFields) ? '' : ('AND variable NOT IN ({array_string:custom_fields})');
  534. $smcFunc['db_query']('', '
  535. DELETE FROM {db_prefix}themes
  536. WHERE id_member > {int:no_member}
  537. AND id_theme = {int:current_theme}
  538. ' . $customFieldsQuery,
  539. array(
  540. 'no_member' => 0,
  541. 'current_theme' => $_GET['th'],
  542. 'custom_fields' => empty($customFields) ? array() : $customFields,
  543. )
  544. );
  545. redirectexit('action=admin;area=theme;' . $context['session_var'] . '=' . $context['session_id'] . ';sa=reset');
  546. }
  547. $old_id = $settings['theme_id'];
  548. $old_settings = $settings;
  549. loadTheme($_GET['th'], false);
  550. loadLanguage('Profile');
  551. // @todo Should we just move these options so they are no longer theme dependant?
  552. loadLanguage('PersonalMessage');
  553. // Let the theme take care of the settings.
  554. loadTemplate('Settings');
  555. loadSubTemplate('options');
  556. $context['sub_template'] = 'set_options';
  557. $context['page_title'] = $txt['theme_settings'];
  558. $context['options'] = $context['theme_options'];
  559. $context['theme_settings'] = $settings;
  560. if (empty($_REQUEST['who']))
  561. {
  562. $request = $smcFunc['db_query']('', '
  563. SELECT variable, value
  564. FROM {db_prefix}themes
  565. WHERE id_theme IN (1, {int:current_theme})
  566. AND id_member = {int:guest_member}',
  567. array(
  568. 'current_theme' => $_GET['th'],
  569. 'guest_member' => -1,
  570. )
  571. );
  572. $context['theme_options'] = array();
  573. while ($row = $smcFunc['db_fetch_assoc']($request))
  574. $context['theme_options'][$row['variable']] = $row['value'];
  575. $smcFunc['db_free_result']($request);
  576. $context['theme_options_reset'] = false;
  577. }
  578. else
  579. {
  580. $context['theme_options'] = array();
  581. $context['theme_options_reset'] = true;
  582. }
  583. foreach ($context['options'] as $i => $setting)
  584. {
  585. // Is this disabled?
  586. if ($setting['id'] == 'calendar_start_day' && empty($modSettings['cal_enabled']))
  587. {
  588. unset($context['options'][$i]);
  589. continue;
  590. }
  591. elseif (($setting['id'] == 'topics_per_page' || $setting['id'] == 'messages_per_page') && !empty($modSettings['disableCustomPerPage']))
  592. {
  593. unset($context['options'][$i]);
  594. continue;
  595. }
  596. if (!isset($setting['type']) || $setting['type'] == 'bool')
  597. $context['options'][$i]['type'] = 'checkbox';
  598. elseif ($setting['type'] == 'int' || $setting['type'] == 'integer')
  599. $context['options'][$i]['type'] = 'number';
  600. elseif ($setting['type'] == 'string')
  601. $context['options'][$i]['type'] = 'text';
  602. if (isset($setting['options']))
  603. $context['options'][$i]['type'] = 'list';
  604. $context['options'][$i]['value'] = !isset($context['theme_options'][$setting['id']]) ? '' : $context['theme_options'][$setting['id']];
  605. }
  606. // Restore the existing theme.
  607. loadTheme($old_id, false);
  608. $settings = $old_settings;
  609. loadTemplate('Themes');
  610. createToken('admin-sto');
  611. }
  612. /**
  613. * Administrative global settings.
  614. * - saves and requests global theme settings. ($settings)
  615. * - loads the Admin language file.
  616. * - calls action_admintheme() if no theme is specified. (the theme center.)
  617. * - requires admin_forum permission.
  618. * - accessed with ?action=admin;area=theme;sa=list&th=xx.
  619. */
  620. function SetThemeSettings()
  621. {
  622. global $txt, $context, $settings, $modSettings, $smcFunc;
  623. if (empty($_GET['th']) && empty($_GET['id']))
  624. return action_admintheme();
  625. $_GET['th'] = isset($_GET['th']) ? (int) $_GET['th'] : (int) $_GET['id'];
  626. // Select the best fitting tab.
  627. $context[$context['admin_menu_name']]['current_subsection'] = 'list';
  628. loadLanguage('Admin');
  629. isAllowedTo('admin_forum');
  630. // Validate inputs/user.
  631. if (empty($_GET['th']))
  632. fatal_lang_error('no_theme', false);
  633. // Fetch the smiley sets...
  634. $sets = explode(',', 'none,' . $modSettings['smiley_sets_known']);
  635. $set_names = explode("\n", $txt['smileys_none'] . "\n" . $modSettings['smiley_sets_names']);
  636. $context['smiley_sets'] = array(
  637. '' => $txt['smileys_no_default']
  638. );
  639. foreach ($sets as $i => $set)
  640. $context['smiley_sets'][$set] = htmlspecialchars($set_names[$i]);
  641. $old_id = $settings['theme_id'];
  642. $old_settings = $settings;
  643. loadTheme($_GET['th'], false);
  644. // Sadly we really do need to init the template.
  645. loadSubTemplate('init', 'ignore');
  646. // Also load the actual themes language file - in case of special settings.
  647. loadLanguage('Settings', '', true, true);
  648. // And the custom language strings...
  649. loadLanguage('ThemeStrings', '', false, true);
  650. // Let the theme take care of the settings.
  651. loadTemplate('Settings');
  652. loadSubTemplate('settings');
  653. // Load the variants separately...
  654. $settings['theme_variants'] = array();
  655. if (file_exists($settings['theme_dir'] . '/index.template.php'))
  656. {
  657. $file_contents = implode('', file($settings['theme_dir'] . '/index.template.php'));
  658. if (preg_match('~\$settings\[\'theme_variants\'\]\s*=(.+?);~', $file_contents, $matches))
  659. eval('global $settings;' . $matches[0]);
  660. }
  661. // Submitting!
  662. if (isset($_POST['save']))
  663. {
  664. checkSession();
  665. validateToken('admin-sts');
  666. if (empty($_POST['options']))
  667. $_POST['options'] = array();
  668. if (empty($_POST['default_options']))
  669. $_POST['default_options'] = array();
  670. // Make sure items are cast correctly.
  671. foreach ($context['theme_settings'] as $item)
  672. {
  673. // Disregard this item if this is just a separator.
  674. if (!is_array($item))
  675. continue;
  676. foreach (array('options', 'default_options') as $option)
  677. {
  678. if (!isset($_POST[$option][$item['id']]))
  679. continue;
  680. // Checkbox.
  681. elseif (empty($item['type']))
  682. $_POST[$option][$item['id']] = $_POST[$option][$item['id']] ? 1 : 0;
  683. // Number
  684. elseif ($item['type'] == 'number')
  685. $_POST[$option][$item['id']] = (int) $_POST[$option][$item['id']];
  686. }
  687. }
  688. // Set up the sql query.
  689. $inserts = array();
  690. foreach ($_POST['options'] as $opt => $val)
  691. $inserts[] = array(0, $_GET['th'], $opt, is_array($val) ? implode(',', $val) : $val);
  692. foreach ($_POST['default_options'] as $opt => $val)
  693. $inserts[] = array(0, 1, $opt, is_array($val) ? implode(',', $val) : $val);
  694. // If we're actually inserting something..
  695. if (!empty($inserts))
  696. {
  697. $smcFunc['db_insert']('replace',
  698. '{db_prefix}themes',
  699. array('id_member' => 'int', 'id_theme' => 'int', 'variable' => 'string-255', 'value' => 'string-65534'),
  700. $inserts,
  701. array('id_member', 'id_theme', 'variable')
  702. );
  703. }
  704. cache_put_data('theme_settings-' . $_GET['th'], null, 90);
  705. cache_put_data('theme_settings-1', null, 90);
  706. // Invalidate the cache.
  707. updateSettings(array('settings_updated' => time()));
  708. redirectexit('action=admin;area=theme;sa=list;th=' . $_GET['th'] . ';' . $context['session_var'] . '=' . $context['session_id']);
  709. }
  710. $context['sub_template'] = 'set_settings';
  711. $context['page_title'] = $txt['theme_settings'];
  712. foreach ($settings as $setting => $dummy)
  713. {
  714. if (!in_array($setting, array('theme_url', 'theme_dir', 'images_url', 'template_dirs')))
  715. $settings[$setting] = htmlspecialchars__recursive($settings[$setting]);
  716. }
  717. $context['settings'] = $context['theme_settings'];
  718. $context['theme_settings'] = $settings;
  719. foreach ($context['settings'] as $i => $setting)
  720. {
  721. // Separators are dummies, so leave them alone.
  722. if (!is_array($setting))
  723. continue;
  724. if (!isset($setting['type']) || $setting['type'] == 'bool')
  725. $context['settings'][$i]['type'] = 'checkbox';
  726. elseif ($setting['type'] == 'int' || $setting['type'] == 'integer')
  727. $context['settings'][$i]['type'] = 'number';
  728. elseif ($setting['type'] == 'string')
  729. $context['settings'][$i]['type'] = 'text';
  730. if (isset($setting['options']))
  731. $context['settings'][$i]['type'] = 'list';
  732. $context['settings'][$i]['value'] = !isset($settings[$setting['id']]) ? '' : $settings[$setting['id']];
  733. }
  734. // Do we support variants?
  735. if (!empty($settings['theme_variants']))
  736. {
  737. $context['theme_variants'] = array();
  738. foreach ($settings['theme_variants'] as $variant)
  739. {
  740. // Have any text, old chap?
  741. $context['theme_variants'][$variant] = array(
  742. 'label' => isset($txt['variant_' . $variant]) ? $txt['variant_' . $variant] : $variant,
  743. 'thumbnail' => !file_exists($settings['theme_dir'] . '/images/thumbnail.png') || file_exists($settings['theme_dir'] . '/images/thumbnail_' . $variant . '.png') ? $settings['images_url'] . '/thumbnail_' . $variant . '.png' : ($settings['images_url'] . '/thumbnail.png'),
  744. );
  745. }
  746. $context['default_variant'] = !empty($settings['default_variant']) && isset($context['theme_variants'][$settings['default_variant']]) ? $settings['default_variant'] : $settings['theme_variants'][0];
  747. }
  748. // Restore the current theme.
  749. loadTheme($old_id, false);
  750. // Reinit just incase.
  751. loadSubTemplate('init', 'ignore');
  752. $settings = $old_settings;
  753. loadTemplate('Themes');
  754. // We like Kenny better than Token.
  755. createToken('admin-sts');
  756. }
  757. /**
  758. * Remove a theme from the database.
  759. * - removes an installed theme.
  760. * - requires an administrator.
  761. * - accessed with ?action=admin;area=theme;sa=remove.
  762. */
  763. function action_removetheme()
  764. {
  765. global $modSettings, $context, $smcFunc;
  766. checkSession('get');
  767. isAllowedTo('admin_forum');
  768. validateToken('admin-tr', 'request');
  769. // The theme's ID must be an integer.
  770. $_GET['th'] = isset($_GET['th']) ? (int) $_GET['th'] : (int) $_GET['id'];
  771. // You can't delete the default theme!
  772. if ($_GET['th'] == 1)
  773. fatal_lang_error('no_access', false);
  774. $known = explode(',', $modSettings['knownThemes']);
  775. for ($i = 0, $n = count($known); $i < $n; $i++)
  776. {
  777. if ($known[$i] == $_GET['th'])
  778. unset($known[$i]);
  779. }
  780. $smcFunc['db_query']('', '
  781. DELETE FROM {db_prefix}themes
  782. WHERE id_theme = {int:current_theme}',
  783. array(
  784. 'current_theme' => $_GET['th'],
  785. )
  786. );
  787. $smcFunc['db_query']('', '
  788. UPDATE {db_prefix}members
  789. SET id_theme = {int:default_theme}
  790. WHERE id_theme = {int:current_theme}',
  791. array(
  792. 'default_theme' => 0,
  793. 'current_theme' => $_GET['th'],
  794. )
  795. );
  796. $smcFunc['db_query']('', '
  797. UPDATE {db_prefix}boards
  798. SET id_theme = {int:default_theme}
  799. WHERE id_theme = {int:current_theme}',
  800. array(
  801. 'default_theme' => 0,
  802. 'current_theme' => $_GET['th'],
  803. )
  804. );
  805. $known = strtr(implode(',', $known), array(',,' => ','));
  806. // Fix it if the theme was the overall default theme.
  807. if ($modSettings['theme_guests'] == $_GET['th'])
  808. updateSettings(array('theme_guests' => '1', 'knownThemes' => $known));
  809. else
  810. updateSettings(array('knownThemes' => $known));
  811. redirectexit('action=admin;area=theme;sa=list;' . $context['session_var'] . '=' . $context['session_id']);
  812. }
  813. /**
  814. * Choose a theme from a list.
  815. * allows an user or administrator to pick a new theme with an interface.
  816. * - can edit everyone's (u = 0), guests' (u = -1), or a specific user's.
  817. * - uses the Themes template. (pick sub template.)
  818. * - accessed with ?action=admin;area=theme;sa=pick.
  819. * @todo thought so... Might be better to split this file in ManageThemes and Themes,
  820. * with centralized admin permissions on ManageThemes.
  821. */
  822. function action_picktheme()
  823. {
  824. global $txt, $context, $modSettings, $user_info, $language, $smcFunc, $settings, $scripturl;
  825. loadLanguage('Profile');
  826. loadTemplate('Themes');
  827. // Build the link tree.
  828. $context['linktree'][] = array(
  829. 'url' => $scripturl . '?action=theme;sa=pick;u=' . (!empty($_REQUEST['u']) ? (int) $_REQUEST['u'] : 0),
  830. 'name' => $txt['theme_pick'],
  831. );
  832. $_SESSION['id_theme'] = 0;
  833. if (isset($_GET['id']))
  834. $_GET['th'] = $_GET['id'];
  835. // Saving a variant cause JS doesn't work - pretend it did ;)
  836. if (isset($_POST['save']))
  837. {
  838. // Which theme?
  839. foreach ($_POST['save'] as $k => $v)
  840. $_GET['th'] = (int) $k;
  841. if (isset($_POST['vrt'][$k]))
  842. $_GET['vrt'] = $_POST['vrt'][$k];
  843. }
  844. // Have we made a desicion, or are we just browsing?
  845. if (isset($_GET['th']))
  846. {
  847. checkSession('get');
  848. $_GET['th'] = (int) $_GET['th'];
  849. // Save for this user.
  850. if (!isset($_REQUEST['u']) || !allowedTo('admin_forum'))
  851. {
  852. updateMemberData($user_info['id'], array('id_theme' => (int) $_GET['th']));
  853. // A variants to save for the user?
  854. if (!empty($_GET['vrt']))
  855. {
  856. $smcFunc['db_insert']('replace',
  857. '{db_prefix}themes',
  858. array('id_theme' => 'int', 'id_member' => 'int', 'variable' => 'string-255', 'value' => 'string-65534'),
  859. array($_GET['th'], $user_info['id'], 'theme_variant', $_GET['vrt']),
  860. array('id_theme', 'id_member', 'variable')
  861. );
  862. cache_put_data('theme_settings-' . $_GET['th'] . ':' . $user_info['id'], null, 90);
  863. $_SESSION['id_variant'] = 0;
  864. }
  865. redirectexit('action=profile;area=theme');
  866. }
  867. // If changing members or guests - and there's a variant - assume changing default variant.
  868. if (!empty($_GET['vrt']) && ($_REQUEST['u'] == '0' || $_REQUEST['u'] == '-1'))
  869. {
  870. $smcFunc['db_insert']('replace',
  871. '{db_prefix}themes',
  872. array('id_theme' => 'int', 'id_member' => 'int', 'variable' => 'string-255', 'value' => 'string-65534'),
  873. array($_GET['th'], 0, 'default_variant', $_GET['vrt']),
  874. array('id_theme', 'id_member', 'variable')
  875. );
  876. // Make it obvious that it's changed
  877. cache_put_data('theme_settings-' . $_GET['th'], null, 90);
  878. }
  879. // For everyone.
  880. if ($_REQUEST['u'] == '0')
  881. {
  882. updateMemberData(null, array('id_theme' => (int) $_GET['th']));
  883. // Remove any custom variants.
  884. if (!empty($_GET['vrt']))
  885. {
  886. $smcFunc['db_query']('', '
  887. DELETE FROM {db_prefix}themes
  888. WHERE id_theme = {int:current_theme}
  889. AND variable = {string:theme_variant}',
  890. array(
  891. 'current_theme' => (int) $_GET['th'],
  892. 'theme_variant' => 'theme_variant',
  893. )
  894. );
  895. }
  896. redirectexit('action=admin;area=theme;sa=admin;' . $context['session_var'] . '=' . $context['session_id']);
  897. }
  898. // Change the default/guest theme.
  899. elseif ($_REQUEST['u'] == '-1')
  900. {
  901. updateSettings(array('theme_guests' => (int) $_GET['th']));
  902. redirectexit('action=admin;area=theme;sa=admin;' . $context['session_var'] . '=' . $context['session_id']);
  903. }
  904. // Change a specific member's theme.
  905. else
  906. {
  907. // The forum's default theme is always 0 and we
  908. if (isset($_GET['th']) && $_GET['th'] == 0)
  909. $_GET['th'] = $modSettings['theme_guests'];
  910. updateMemberData((int) $_REQUEST['u'], array('id_theme' => (int) $_GET['th']));
  911. if (!empty($_GET['vrt']))
  912. {
  913. $smcFunc['db_insert']('replace',
  914. '{db_prefix}themes',
  915. array('id_theme' => 'int', 'id_member' => 'int', 'variable' => 'string-255', 'value' => 'string-65534'),
  916. array($_GET['th'], (int) $_REQUEST['u'], 'theme_variant', $_GET['vrt']),
  917. array('id_theme', 'id_member', 'variable')
  918. );
  919. cache_put_data('theme_settings-' . $_GET['th'] . ':' . (int) $_REQUEST['u'], null, 90);
  920. if ($user_info['id'] == $_REQUEST['u'])
  921. $_SESSION['id_variant'] = 0;
  922. }
  923. redirectexit('action=profile;u=' . (int) $_REQUEST['u'] . ';area=theme');
  924. }
  925. }
  926. // Figure out who the member of the minute is, and what theme they've chosen.
  927. if (!isset($_REQUEST['u']) || !allowedTo('admin_forum'))
  928. {
  929. $context['current_member'] = $user_info['id'];
  930. $context['current_theme'] = $user_info['theme'];
  931. }
  932. // Everyone can't chose just one.
  933. elseif ($_REQUEST['u'] == '0')
  934. {
  935. $context['current_member'] = 0;
  936. $context['current_theme'] = 0;
  937. }
  938. // Guests and such...
  939. elseif ($_REQUEST['u'] == '-1')
  940. {
  941. $context['current_member'] = -1;
  942. $context['current_theme'] = $modSettings['theme_guests'];
  943. }
  944. // Someones else :P.
  945. else
  946. {
  947. $context['current_member'] = (int) $_REQUEST['u'];
  948. $request = $smcFunc['db_query']('', '
  949. SELECT id_theme
  950. FROM {db_prefix}members
  951. WHERE id_member = {int:current_member}
  952. LIMIT 1',
  953. array(
  954. 'current_member' => $context['current_member'],
  955. )
  956. );
  957. list ($context['current_theme']) = $smcFunc['db_fetch_row']($request);
  958. $smcFunc['db_free_result']($request);
  959. }
  960. // Get the theme name and descriptions.
  961. $context['available_themes'] = array();
  962. if (!empty($modSettings['knownThemes']))
  963. {
  964. $request = $smcFunc['db_query']('', '
  965. SELECT id_theme, variable, value
  966. FROM {db_prefix}themes
  967. WHERE variable IN ({string:name}, {string:theme_url}, {string:theme_dir}, {string:images_url}, {string:disable_user_variant})' . (!allowedTo('admin_forum') ? '
  968. AND id_theme IN ({array_string:known_themes})' : '') . '
  969. AND id_theme != {int:default_theme}
  970. AND id_member = {int:no_member}',
  971. array(
  972. 'default_theme' => 0,
  973. 'name' => 'name',
  974. 'no_member' => 0,
  975. 'theme_url' => 'theme_url',
  976. 'theme_dir' => 'theme_dir',
  977. 'images_url' => 'images_url',
  978. 'disable_user_variant' => 'disable_user_variant',
  979. 'known_themes' => explode(',', $modSettings['knownThemes']),
  980. )
  981. );
  982. while ($row = $smcFunc['db_fetch_assoc']($request))
  983. {
  984. if (!isset($context['available_themes'][$row['id_theme']]))
  985. $context['available_themes'][$row['id_theme']] = array(
  986. 'id' => $row['id_theme'],
  987. 'selected' => $context['current_theme'] == $row['id_theme'],
  988. 'num_users' => 0
  989. );
  990. $context['available_themes'][$row['id_theme']][$row['variable']] = $row['value'];
  991. }
  992. $smcFunc['db_free_result']($request);
  993. }
  994. // Okay, this is a complicated problem: the default theme is 1, but they aren't allowed to access 1!
  995. if (!isset($context['available_themes'][$modSettings['theme_guests']]))
  996. {
  997. $context['available_themes'][0] = array(
  998. 'num_users' => 0
  999. );
  1000. $guest_theme = 0;
  1001. }
  1002. else
  1003. $guest_theme = $modSettings['theme_guests'];
  1004. $request = $smcFunc['db_query']('', '
  1005. SELECT id_theme, COUNT(*) AS the_count
  1006. FROM {db_prefix}members
  1007. GROUP BY id_theme
  1008. ORDER BY id_theme DESC',
  1009. array(
  1010. )
  1011. );
  1012. while ($row = $smcFunc['db_fetch_assoc']($request))
  1013. {
  1014. // Figure out which theme it is they are REALLY using.
  1015. if (!empty($modSettings['knownThemes']) && !in_array($row['id_theme'], explode(',',$modSettings['knownThemes'])))
  1016. $row['id_theme'] = $guest_theme;
  1017. elseif (empty($modSettings['theme_allow']))
  1018. $row['id_theme'] = $guest_theme;
  1019. if (isset($context['available_themes'][$row['id_theme']]))
  1020. $context['available_themes'][$row['id_theme']]['num_users'] += $row['the_count'];
  1021. else
  1022. $context['available_themes'][$guest_theme]['num_users'] += $row['the_count'];
  1023. }
  1024. $smcFunc['db_free_result']($request);
  1025. // Get any member variant preferences.
  1026. $variant_preferences = array();
  1027. if ($context['current_member'] > 0)
  1028. {
  1029. $request = $smcFunc['db_query']('', '
  1030. SELECT id_theme, value
  1031. FROM {db_prefix}themes
  1032. WHERE variable = {string:theme_variant}
  1033. AND id_member IN ({array_int:id_member})
  1034. ORDER BY id_member ASC',
  1035. array(
  1036. 'theme_variant' => 'theme_variant',
  1037. 'id_member' => isset($_REQUEST['sa']) && $_REQUEST['sa'] == 'pick' ? array(-1, $context['current_member']) : array(-1),
  1038. )
  1039. );
  1040. while ($row = $smcFunc['db_fetch_assoc']($request))
  1041. $variant_preferences[$row['id_theme']] = $row['value'];
  1042. $smcFunc['db_free_result']($request);
  1043. }
  1044. // Save the setting first.
  1045. $current_images_url = $settings['images_url'];
  1046. $current_theme_variants = !empty($settings['theme_variants']) ? $settings['theme_variants'] : array();
  1047. foreach ($context['available_themes'] as $id_theme => $theme_data)
  1048. {
  1049. // Don't try to load the forum or board default theme's data... it doesn't have any!
  1050. if ($id_theme == 0)
  1051. continue;
  1052. // The thumbnail needs the correct path.
  1053. $settings['images_url'] = &$theme_data['images_url'];
  1054. if (file_exists($theme_data['theme_dir'] . '/languages/Settings.' . $user_info['language'] . '.php'))
  1055. include($theme_data['theme_dir'] . '/languages/Settings.' . $user_info['language'] . '.php');
  1056. elseif (file_exists($theme_data['theme_dir'] . '/languages/Settings.' . $language . '.php'))
  1057. include($theme_data['theme_dir'] . '/languages/Settings.' . $language . '.php');
  1058. else
  1059. {
  1060. $txt['theme_thumbnail_href'] = $theme_data['images_url'] . '/thumbnail.png';
  1061. $txt['theme_description'] = '';
  1062. }
  1063. $context['available_themes'][$id_theme]['thumbnail_href'] = $txt['theme_thumbnail_href'];
  1064. $context['available_themes'][$id_theme]['description'] = $txt['theme_description'];
  1065. // Are there any variants?
  1066. if (file_exists($theme_data['theme_dir'] . '/index.template.php') && empty($theme_data['disable_user_variant']))
  1067. {
  1068. $file_contents = implode('', file($theme_data['theme_dir'] . '/index.template.php'));
  1069. if (preg_match('~\$settings\[\'theme_variants\'\]\s*=(.+?);~', $file_contents, $matches))
  1070. {
  1071. $settings['theme_variants'] = array();
  1072. // Fill settings up.
  1073. eval('global $settings;' . $matches[0]);
  1074. if (!empty($settings['theme_variants']))
  1075. {
  1076. loadLanguage('Settings');
  1077. $context['available_themes'][$id_theme]['variants'] = array();
  1078. foreach ($settings['theme_variants'] as $variant)
  1079. $context['available_themes'][$id_theme]['variants'][$variant] = array(
  1080. 'label' => isset($txt['variant_' . $variant]) ? $txt['variant_' . $variant] : $variant,
  1081. 'thumbnail' => !file_exists($theme_data['theme_dir'] . '/images/thumbnail.png') || file_exists($theme_data['theme_dir'] . '/images/thumbnail_' . $variant . '.png') ? $theme_data['images_url'] . '/thumbnail_' . $variant . '.png' : ($theme_data['images_url'] . '/thumbnail.png'),
  1082. );
  1083. $context['available_themes'][$id_theme]['selected_variant'] = isset($_GET['vrt']) ? $_GET['vrt'] : (!empty($variant_preferences[$id_theme]) ? $variant_preferences[$id_theme] : (!empty($settings['default_variant']) ? $settings['default_variant'] : $settings['theme_variants'][0]));
  1084. if (!isset($context['available_themes'][$id_theme]['variants'][$context['available_themes'][$id_theme]['selected_variant']]['thumbnail']))
  1085. $context['available_themes'][$id_theme]['selected_variant'] = $settings['theme_variants'][0];
  1086. $context['available_themes'][$id_theme]['thumbnail_href'] = $context['available_themes'][$id_theme]['variants'][$context['available_themes'][$id_theme]['selected_variant']]['thumbnail'];
  1087. // Allow themes to override the text.
  1088. $context['available_themes'][$id_theme]['pick_label'] = isset($txt['variant_pick']) ? $txt['variant_pick'] : $txt['theme_pick_variant'];
  1089. }
  1090. }
  1091. }
  1092. }
  1093. // Then return it.
  1094. $settings['images_url'] = $current_images_url;
  1095. $settings['theme_variants'] = $current_theme_variants;
  1096. // As long as we're not doing the default theme...
  1097. if (!isset($_REQUEST['u']) || $_REQUEST['u'] >= 0)
  1098. {
  1099. if ($guest_theme != 0)
  1100. $context['available_themes'][0] = $context['available_themes'][$guest_theme];
  1101. $context['available_themes'][0]['id'] = 0;
  1102. $context['available_themes'][0]['name'] = $txt['theme_forum_default'];
  1103. $context['available_themes'][0]['selected'] = $context['current_theme'] == 0;
  1104. $context['available_themes'][0]['description'] = $txt['theme_global_description'];
  1105. }
  1106. ksort($context['available_themes']);
  1107. $context['page_title'] = $txt['theme_pick'];
  1108. $context['sub_template'] = 'pick';
  1109. }
  1110. /**
  1111. * Installs new themes, either from a gzip or copy of the default.
  1112. * - puts themes in $boardurl/Themes.
  1113. * - assumes the gzip has a root directory in it. (ie default.)
  1114. * Requires admin_forum.
  1115. * Accessed with ?action=admin;area=theme;sa=install.
  1116. */
  1117. function action_installtheme()
  1118. {
  1119. global $boardurl, $txt, $context, $settings, $modSettings, $smcFunc;
  1120. checkSession('request');
  1121. isAllowedTo('admin_forum');
  1122. checkSession('request');
  1123. require_once(SUBSDIR . '/Package.subs.php');
  1124. loadTemplate('Themes');
  1125. if (isset($_GET['theme_id']))
  1126. {
  1127. $result = $smcFunc['db_query']('', '
  1128. SELECT value
  1129. FROM {db_prefix}themes
  1130. WHERE id_theme = {int:current_theme}
  1131. AND id_member = {int:no_member}
  1132. AND variable = {string:name}
  1133. LIMIT 1',
  1134. array(
  1135. 'current_theme' => (int) $_GET['theme_id'],
  1136. 'no_member' => 0,
  1137. 'name' => 'name',
  1138. )
  1139. );
  1140. list ($theme_name) = $smcFunc['db_fetch_row']($result);
  1141. $smcFunc['db_free_result']($result);
  1142. $context['sub_template'] = 'installed';
  1143. $context['page_title'] = $txt['theme_installed'];
  1144. $context['installed_theme'] = array(
  1145. 'id' => (int) $_GET['theme_id'],
  1146. 'name' => $theme_name,
  1147. );
  1148. return;
  1149. }
  1150. if ((!empty($_FILES['theme_gz']) && (!isset($_FILES['theme_gz']['error']) || $_FILES['theme_gz']['error'] != 4)) || !empty($_REQUEST['theme_gz']))
  1151. $method = 'upload';
  1152. elseif (isset($_REQUEST['theme_dir']) && rtrim(realpath($_REQUEST['theme_dir']), '/\\') != realpath(BOARDDIR . '/Themes') && file_exists($_REQUEST['theme_dir']))
  1153. $method = 'path';
  1154. else
  1155. $method = 'copy';
  1156. if (!empty($_REQUEST['copy']) && $method == 'copy')
  1157. {
  1158. // Hopefully the themes directory is writable, or we might have a problem.
  1159. if (!is_writable(BOARDDIR . '/Themes'))
  1160. fatal_lang_error('theme_install_write_error', 'critical');
  1161. $theme_dir = BOARDDIR . '/Themes/' . preg_replace('~[^A-Za-z0-9_\- ]~', '', $_REQUEST['copy']);
  1162. umask(0);
  1163. mkdir($theme_dir, 0777);
  1164. @set_time_limit(600);
  1165. if (function_exists('apache_reset_timeout'))
  1166. @apache_reset_timeout();
  1167. // Create subdirectories for css and javascript files.
  1168. mkdir($theme_dir . '/css', 0777);
  1169. mkdir($theme_dir . '/scripts', 0777);
  1170. // Copy over the default non-theme files.
  1171. $to_copy = array('/index.php', '/index.template.php', '/css/index.css', '/css/rtl.css', '/scripts/theme.js');
  1172. foreach ($to_copy as $file)
  1173. {
  1174. copy($settings['default_theme_dir'] . $file, $theme_dir . $file);
  1175. @chmod($theme_dir . $file, 0777);
  1176. }
  1177. // And now the entire images directory!
  1178. copytree($settings['default_theme_dir'] . '/images', $theme_dir . '/images');
  1179. package_flush_cache();
  1180. $theme_name = $_REQUEST['copy'];
  1181. $images_url = $boardurl . '/Themes/' . basename($theme_dir) . '/images';
  1182. $theme_dir = realpath($theme_dir);
  1183. // Lets get some data for the new theme.
  1184. $request = $smcFunc['db_query']('', '
  1185. SELECT variable, value
  1186. FROM {db_prefix}themes
  1187. WHERE variable IN ({string:theme_templates}, {string:theme_layers})
  1188. AND id_member = {int:no_member}
  1189. AND id_theme = {int:default_theme}',
  1190. array(
  1191. 'no_member' => 0,
  1192. 'default_theme' => 1,
  1193. 'theme_templates' => 'theme_templates',
  1194. 'theme_layers' => 'theme_layers',
  1195. )
  1196. );
  1197. while ($row = $smcFunc['db_fetch_assoc']($request))
  1198. {
  1199. if ($row['variable'] == 'theme_templates')
  1200. $theme_templates = $row['value'];
  1201. elseif ($row['variable'] == 'theme_layers')
  1202. $theme_layers = $row['value'];
  1203. else
  1204. continue;
  1205. }
  1206. $smcFunc['db_free_result']($request);
  1207. // Lets add a theme_info.xml to this theme.
  1208. $xml_info = '<' . '?xml version="1.0"?' . '>
  1209. <theme-info xmlns="http://www.simplemachines.org/xml/theme-info" xmlns:smf="http://www.simplemachines.org/">
  1210. <!-- For the id, always use something unique - put your name, a colon, and then the package name. -->
  1211. <id>smf:' . $smcFunc['strtolower'](str_replace(array(' '), '_', $_REQUEST['copy'])) . '</id>
  1212. <version>' . $modSettings['elkVersion'] . '</version>
  1213. <!-- Theme name, used purely for aesthetics. -->
  1214. <name>' . $_REQUEST['copy'] . '</name>
  1215. <!-- Author: your email address or contact information. The name attribute is optional. -->
  1216. <author name="Your Name">info@youremailaddress.tld</author>
  1217. <!-- Website... where to get updates and more information. -->
  1218. <website>http://www.yourdomain.tld/</website>
  1219. <!-- Template layers to use, defaults to "html,body". -->
  1220. <layers>' . (empty($theme_layers) ? 'html,body' : $theme_layers) . '</layers>
  1221. <!-- Templates to load on startup. Default is "index". -->
  1222. <templates>' . (empty($theme_templates) ? 'index' : $theme_templates) . '</templates>
  1223. <!-- Base this theme off another? Default is blank, or no. It could be "default". -->
  1224. <based-on></based-on>
  1225. </theme-info>';
  1226. // Now write it.
  1227. $fp = @fopen($theme_dir . '/theme_info.xml', 'w+');
  1228. if ($fp)
  1229. {
  1230. fwrite($fp, $xml_info);
  1231. fclose($fp);
  1232. }
  1233. }
  1234. elseif (isset($_REQUEST['theme_dir']) && $method == 'path')
  1235. {
  1236. if (!is_dir($_REQUEST['theme_dir']) || !file_exists($_REQUEST['theme_dir'] . '/theme_info.xml'))
  1237. fatal_lang_error('theme_install_error', false);
  1238. $theme_name = basename($_REQUEST['theme_dir']);
  1239. $theme_dir = $_REQUEST['theme_dir'];
  1240. }
  1241. elseif ($method = 'upload')
  1242. {
  1243. // Hopefully the themes directory is writable, or we might have a problem.
  1244. if (!is_writable(BOARDDIR . '/Themes'))
  1245. fatal_lang_error('theme_install_write_error', 'critical');
  1246. // This happens when the admin session is gone and the user has to login again
  1247. if (empty($_FILES['theme_gz']) && empty($_REQUEST['theme_gz']))
  1248. redirectexit('action=admin;area=theme;sa=admin;' . $context['session_var'] . '=' . $context['session_id']);
  1249. // Set the default settings...
  1250. $theme_name = strtok(basename(isset($_FILES['theme_gz']) ? $_FILES['theme_gz']['name'] : $_REQUEST['theme_gz']), '.');
  1251. $theme_name = preg_replace(array('/\s/', '/\.[\.]+/', '/[^\w_\.\-]/'), array('_', '.', ''), $theme_name);
  1252. $theme_dir = BOARDDIR . '/Themes/' . $theme_name;
  1253. if (isset($_FILES['theme_gz']) && is_uploaded_file($_FILES['theme_gz']['tmp_name']) && (ini_get('open_basedir') != '' || file_exists($_FILES['theme_gz']['tmp_name'])))
  1254. $extracted = read_tgz_file($_FILES['theme_gz']['tmp_name'], BOARDDIR . '/Themes/' . $theme_name, false, true);
  1255. elseif (isset($_REQUEST['theme_gz']))
  1256. {
  1257. // Check that the theme is from simplemachines.org, for now... maybe add mirroring later.
  1258. if (preg_match('~^http://[\w_\-]+\.simplemachines\.org/~', $_REQUEST['theme_gz']) == 0 || strpos($_REQUEST['theme_gz'], 'dlattach') !== false)
  1259. fatal_lang_error('not_on_simplemachines');
  1260. $extracted = read_tgz_file($_REQUEST['theme_gz'], BOARDDIR . '/Themes/' . $theme_name, false, true);
  1261. }
  1262. else
  1263. redirectexit('action=admin;area=theme;sa=admin;' . $context['session_var'] . '=' . $context['session_id']);
  1264. }
  1265. // Something go wrong?
  1266. if ($theme_dir != '' && basename($theme_dir) != 'Themes')
  1267. {
  1268. // Defaults.
  1269. $install_info = array(
  1270. 'theme_url' => $boardurl . '/Themes/' . basename($theme_dir),
  1271. 'images_url' => isset($images_url) ? $images_url : $boardurl . '/Themes/' . basename($theme_dir) . '/images',
  1272. 'theme_dir' => $theme_dir,
  1273. 'name' => $theme_name
  1274. );
  1275. if (file_exists($theme_dir . '/theme_info.xml'))
  1276. {
  1277. $theme_info = file_get_contents($theme_dir . '/theme_info.xml');
  1278. // Parse theme-info.xml into an Xml_Array.
  1279. require_once(SUBSDIR . '/XmlArray.class.php');
  1280. $theme_info_xml = new Xml_Array($theme_info);
  1281. // @todo Error message of some sort?
  1282. if (!$theme_info_xml->exists('theme-info[0]'))
  1283. return 'package_get_error_packageinfo_corrupt';
  1284. $theme_info_xml = $theme_info_xml->path('theme-info[0]');
  1285. $theme_info_xml = $theme_info_xml->to_array();
  1286. $xml_elements = array(
  1287. 'name' => 'name',
  1288. 'theme_layers' => 'layers',
  1289. 'theme_templates' => 'templates',
  1290. 'based_on' => 'based-on',
  1291. );
  1292. foreach ($xml_elements as $var => $name)
  1293. {
  1294. if (!empty($theme_info_xml[$name]))
  1295. $install_info[$var] = $theme_info_xml[$name];
  1296. }
  1297. if (!empty($theme_info_xml['images']))
  1298. {
  1299. $install_info['images_url'] = $install_info['theme_url'] . '/' . $theme_info_xml['images'];
  1300. $explicit_images = true;
  1301. }
  1302. if (!empty($theme_info_xml['extra']))
  1303. $install_info += unserialize($theme_info_xml['extra']);
  1304. }
  1305. if (isset($install_info['based_on']))
  1306. {
  1307. if ($install_info['based_on'] == 'default')
  1308. {
  1309. $install_info['theme_url'] = $settings['default_theme_url'];
  1310. $install_info['images_url'] = $settings['default_images_url'];
  1311. }
  1312. elseif ($install_info['based_on'] != '')
  1313. {
  1314. $install_info['based_on'] = preg_replace('~[^A-Za-z0-9\-_ ]~', '', $install_info['based_on']);
  1315. $request = $smcFunc['db_query']('', '
  1316. SELECT th.value AS base_theme_dir, th2.value AS base_theme_url' . (!empty($explicit_images) ? '' : ', th3.value AS images_url') . '
  1317. FROM {db_prefix}themes AS th
  1318. INNER JOIN {db_prefix}themes AS th2 ON (th2.id_theme = th.id_theme
  1319. AND th2.id_member = {int:no_member}
  1320. AND th2.variable = {string:theme_url})' . (!empty($explicit_images) ? '' : '
  1321. INNER JOIN {db_prefix}themes AS th3 ON (th3.id_theme = th.id_theme
  1322. AND th3.id_member = {int:no_member}
  1323. AND th3.variable = {string:images_url})') . '
  1324. WHERE th.id_member = {int:no_member}
  1325. AND (th.value LIKE {string:based_on} OR th.value LIKE {string:based_on_path})
  1326. AND th.variable = {string:theme_dir}
  1327. LIMIT 1',
  1328. array(
  1329. 'no_member' => 0,
  1330. 'theme_url' => 'theme_url',
  1331. 'images_url' => 'images_url',
  1332. 'theme_dir' => 'theme_dir',
  1333. 'based_on' => '%/' . $install_info['based_on'],
  1334. 'based_on_path' => '%' . "\\" . $install_info['based_on'],
  1335. )
  1336. );
  1337. $temp = $smcFunc['db_fetch_assoc']($request);
  1338. $smcFunc['db_free_result']($request);
  1339. // @todo An error otherwise?
  1340. if (is_array($temp))
  1341. {
  1342. $install_info = $temp + $install_info;
  1343. if (empty($explicit_images) && !empty($install_info['base_theme_url']))
  1344. $install_info['theme_url'] = $install_info['base_theme_url'];
  1345. }
  1346. }
  1347. unset($install_info['based_on']);
  1348. }
  1349. // Find the newest id_theme.
  1350. $result = $smcFunc['db_query']('', '
  1351. SELECT MAX(id_theme)
  1352. FROM {db_prefix}themes',
  1353. array(
  1354. )
  1355. );
  1356. list ($id_theme) = $smcFunc['db_fetch_row']($result);
  1357. $smcFunc['db_free_result']($result);
  1358. // This will be theme number...
  1359. $id_theme++;
  1360. $inserts = array();
  1361. foreach ($install_info as $var => $val)
  1362. $inserts[] = array($id_theme, $var, $val);
  1363. if (!empty($inserts))
  1364. $smcFunc['db_insert']('insert',
  1365. '{db_prefix}themes',
  1366. array('id_theme' => 'int', 'variable' => 'string-255', 'value' => 'string-65534'),
  1367. $inserts,
  1368. array('id_theme', 'variable')
  1369. );
  1370. updateSettings(array('knownThemes' => strtr($modSettings['knownThemes'] . ',' . $id_theme, array(',,' => ','))));
  1371. }
  1372. redirectexit('action=admin;area=theme;sa=install;theme_id=' . $id_theme . ';' . $context['session_var'] . '=' . $context['session_id']);
  1373. }
  1374. /**
  1375. * Possibly the simplest and best example of how to use the template system.
  1376. * - allows the theme to take care of actions.
  1377. * - happens if $settings['catch_action'] is set and action isn't found
  1378. * in the action array.
  1379. * - can use a template, layers, sub_template, filename, and/or function.
  1380. * @todo look at this
  1381. */
  1382. function WrapAction()
  1383. {
  1384. global $context, $settings;
  1385. // Load any necessary template(s)?
  1386. if (isset($settings['catch_action']['template']))
  1387. {
  1388. // Load both the template and language file. (but don't fret if the language file isn't there...)
  1389. loadTemplate($settings['catch_action']['template']);
  1390. loadLanguage($settings['catch_action']['template'], '', false);
  1391. }
  1392. // Any special layers?
  1393. if (isset($settings['catch_action']['layers']))
  1394. $context['template_layers'] = $settings['catch_action']['layers'];
  1395. // Just call a function?
  1396. if (isset($settings['catch_action']['function']))
  1397. {
  1398. if (isset($settings['catch_action']['filename']))
  1399. template_include(SOURCEDIR . '/' . $settings['catch_action']['filename'], true);
  1400. $settings['catch_action']['function']();
  1401. }
  1402. // And finally, the main sub template ;).
  1403. elseif (isset($settings['catch_action']['sub_template']))
  1404. $context['sub_template'] = $settings['catch_action']['sub_template'];
  1405. }
  1406. /**
  1407. * Set an option via javascript.
  1408. * - sets a theme option without outputting anything.
  1409. * - can be used with javascript, via a dummy image... (which doesn't require
  1410. * the page to reload.)
  1411. * - requires someone who is logged in.
  1412. * - accessed via ?action=jsoption;var=variable;val=value;session_var=sess_id.
  1413. * - does not log access to the Who's Online log. (in index.php..)
  1414. */
  1415. function action_jsoption()
  1416. {
  1417. global $settings, $user_info, $smcFunc, $options;
  1418. // Check the session id.
  1419. checkSession('get');
  1420. // This good-for-nothing pixel is being used to keep the session alive.
  1421. if (empty($_GET['var']) || !isset($_GET['val']))
  1422. redirectexit($settings['images_url'] . '/blank.png');
  1423. // Sorry, guests can't go any further than this..
  1424. if ($user_info['is_guest'] || $user_info['id'] == 0)
  1425. obExit(false);
  1426. $reservedVars = array(
  1427. 'actual_theme_url',
  1428. 'actual_images_url',
  1429. 'base_theme_dir',
  1430. 'base_theme_url',
  1431. 'default_images_url',
  1432. 'default_theme_dir',
  1433. 'default_theme_url',
  1434. 'default_template',
  1435. 'images_url',
  1436. 'number_recent_posts',
  1437. 'smiley_sets_default',
  1438. 'theme_dir',
  1439. 'theme_id',
  1440. 'theme_layers',
  1441. 'theme_templates',
  1442. 'theme_url',
  1443. 'name',
  1444. );
  1445. // Can't change reserved vars.
  1446. if (in_array(strtolower($_GET['var']), $reservedVars))
  1447. redirectexit($settings['images_url'] . '/blank.png');
  1448. // Use a specific theme?
  1449. if (isset($_GET['th']) || isset($_GET['id']))
  1450. {
  1451. // Invalidate the current themes cache too.
  1452. cache_put_data('theme_settings-' . $settings['theme_id'] . ':' . $user_info['id'], null, 60);
  1453. $settings['theme_id'] = isset($_GET['th']) ? (int) $_GET['th'] : (int) $_GET['id'];
  1454. }
  1455. // If this is the admin preferences the passed value will just be an element of it.
  1456. if ($_GET['var'] == 'admin_preferences')
  1457. {
  1458. $options['admin_preferences'] = !empty($options['admin_preferences']) ? unserialize($options['admin_preferences']) : array();
  1459. // New thingy...
  1460. if (isset($_GET['admin_key']) && strlen($_GET['admin_key']) < 5)
  1461. $options['admin_preferences'][$_GET['admin_key']] = $_GET['val'];
  1462. // Change the value to be something nice,
  1463. $_GET['val'] = serialize($options['admin_preferences']);
  1464. }
  1465. // Update the option.
  1466. $smcFunc['db_insert']('replace',
  1467. '{db_prefix}themes',
  1468. array('id_theme' => 'int', 'id_member' => 'int', 'variable' => 'string-255', 'value' => 'string-65534'),
  1469. array($settings['theme_id'], $user_info['id'], $_GET['var'], is_array($_GET['val']) ? implode(',', $_GET['val']) : $_GET['val']),
  1470. array('id_theme', 'id_member', 'variable')
  1471. );
  1472. cache_put_data('theme_settings-' . $settings['theme_id'] . ':' . $user_info['id'], null, 60);
  1473. // Don't output anything...
  1474. redirectexit($settings['images_url'] . '/blank.png');
  1475. }
  1476. /**
  1477. * Shows an interface for editing the templates.
  1478. * - uses the Themes template and edit_template/edit_style sub template.
  1479. * - accessed via ?action=admin;area=theme;sa=edit
  1480. */
  1481. function action_edittheme()
  1482. {
  1483. global $context, $settings, $scripturl, $smcFunc;
  1484. // @todo Should this be removed?
  1485. if (isset($_REQUEST['preview']))
  1486. die('die() with fire');
  1487. isAllowedTo('admin_forum');
  1488. loadTemplate('Themes');
  1489. $_GET['th'] = isset($_GET['th']) ? (int) $_GET['th'] : (int) @$_GET['id'];
  1490. if (empty($_GET['th']))
  1491. {
  1492. $request = $smcFunc['db_query']('', '
  1493. SELECT id_theme, variable, value
  1494. FROM {db_prefix}themes
  1495. WHERE variable IN ({string:name}, {string:theme_dir}, {string:theme_templates}, {string:theme_layers})
  1496. AND id_member = {int:no_member}',
  1497. array(
  1498. 'name' => 'name',
  1499. 'theme_dir' => 'theme_dir',
  1500. 'theme_templates' => 'theme_templates',
  1501. 'theme_layers' => 'theme_layers',
  1502. 'no_member' => 0,
  1503. )
  1504. );
  1505. $context['themes'] = array();
  1506. while ($row = $smcFunc['db_fetch_assoc']($request))
  1507. {
  1508. if (!isset($context['themes'][$row['id_theme']]))
  1509. $context['themes'][$row['id_theme']] = array(
  1510. 'id' => $row['id_theme'],
  1511. 'num_default_options' => 0,
  1512. 'num_members' => 0,
  1513. );
  1514. $context['themes'][$row['id_theme']][$row['variable']] = $row['value'];
  1515. }
  1516. $smcFunc['db_free_result']($request);
  1517. foreach ($context['themes'] as $key => $theme)
  1518. {
  1519. // There has to be a Settings template!
  1520. if (!file_exists($theme['theme_dir'] . '/index.template.php') && !file_exists($theme['theme_dir'] . '/css/index.css'))
  1521. unset($context['themes'][$key]);
  1522. else
  1523. {
  1524. if (!isset($theme['theme_templates']))
  1525. $templates = array('index');
  1526. else
  1527. $templates = explode(',', $theme['theme_templates']);
  1528. foreach ($templates as $template)
  1529. if (file_exists($theme['theme_dir'] . '/' . $template . '.template.php'))
  1530. {
  1531. // Fetch the header... a good 256 bytes should be more than enough.
  1532. $fp = fopen($theme['theme_dir'] . '/' . $template . '.template.php', 'rb');
  1533. $header = fread($fp, 256);
  1534. fclose($fp);
  1535. // Can we find a version comment, at all?
  1536. if (preg_match('~\*\s@version\s+(.+)[\s]{2}~i', $header, $match) == 1)
  1537. {
  1538. $ver = $match[1];
  1539. if (!isset($context['themes'][$key]['version']) || $context['themes'][$key]['version'] > $ver)
  1540. $context['themes'][$key]['version'] = $ver;
  1541. }
  1542. }
  1543. $context['themes'][$key]['can_edit_style'] = file_exists($theme['theme_dir'] . '/css/index.css');
  1544. }
  1545. }
  1546. $context['sub_template'] = 'edit_list';
  1547. return 'no_themes';
  1548. }
  1549. $context['session_error'] = false;
  1550. // Get the directory of the theme we are editing.
  1551. $request = $smcFunc['db_query']('', '
  1552. SELECT value, id_theme
  1553. FROM {db_prefix}themes
  1554. WHERE variable = {string:theme_dir}
  1555. AND id_theme = {int:current_theme}
  1556. LIMIT 1',
  1557. array(
  1558. 'current_theme' => $_GET['th'],
  1559. 'theme_dir' => 'theme_dir',
  1560. )
  1561. );
  1562. list ($theme_dir, $context['theme_id']) = $smcFunc['db_fetch_row']($request);
  1563. $smcFunc['db_free_result']($request);
  1564. // Eh? not trying to sneak a peek outside the theme directory are we
  1565. if (!file_exists($theme_dir . '/index.template.php') && !file_exists($theme_dir . '/css/index.css'))
  1566. fatal_lang_error('theme_edit_missing', false);
  1567. if (!isset($_REQUEST['filename']))
  1568. {
  1569. if (isset($_GET['directory']))
  1570. {
  1571. if (substr($_GET['directory'], 0, 1) == '.')
  1572. $_GET['directory'] = '';
  1573. else
  1574. {
  1575. $_GET['directory'] = preg_replace(array('~^[\./\\:\0\n\r]+~', '~[\\\\]~', '~/[\./]+~'), array('', '/', '/'), $_GET['directory']);
  1576. $temp = realpath($theme_dir . '/' . $_GET['directory']);
  1577. if (empty($temp) || substr($temp, 0, strlen(realpath($theme_dir))) != realpath($theme_dir))
  1578. $_GET['directory'] = '';
  1579. }
  1580. }
  1581. if (isset($_GET['directory']) && $_GET['directory'] != '')
  1582. {
  1583. $context['theme_files'] = get_file_listing($theme_dir . '/' . $_GET['directory'], $_GET['directory'] . '/');
  1584. $temp = dirname($_GET['directory']);
  1585. array_unshift($context['theme_files'], array(
  1586. 'filename' => $temp == '.' || $temp == '' ? '/ (..)' : $temp . ' (..)',
  1587. 'is_writable' => is_writable($theme_dir . '/' . $temp),
  1588. 'is_directory' => true,
  1589. 'is_template' => false,
  1590. 'is_image' => false,
  1591. 'is_editable' => false,
  1592. 'href' => $scripturl . '?action=admin;area=theme;th=' . $_GET['th'] . ';' . $context['session_var'] . '=' . $context['session_id'] . ';sa=edit;directory=' . $temp,
  1593. 'size' => '',
  1594. ));
  1595. }
  1596. else
  1597. $context['theme_files'] = get_file_listing($theme_dir, '');
  1598. $context['sub_template'] = 'edit_browse';
  1599. return;
  1600. }
  1601. else
  1602. {
  1603. if (substr($_REQUEST['filename'], 0, 1) == '.')
  1604. $_REQUEST['filename'] = '';
  1605. else
  1606. {
  1607. $_REQUEST['filename'] = preg_replace(array('~^[\./\\:\0\n\r]+~', '~[\\\\]~', '~/[\./]+~'), array('', '/', '/'), $_REQUEST['filename']);
  1608. $temp = realpath($theme_dir . '/' . $_REQUEST['filename']);
  1609. if (empty($temp) || substr($temp, 0, strlen(realpath($theme_dir))) != realpath($theme_dir))
  1610. $_REQUEST['filename'] = '';
  1611. }
  1612. if (empty($_REQUEST['filename']))
  1613. fatal_lang_error('theme_edit_missing', false);
  1614. }
  1615. if (isset($_POST['save']))
  1616. {
  1617. if (checkSession('post', '', false) == '' && validateToken('admin-te-' . md5($_GET['th'] . '-' . $_REQUEST['filename']), 'post', false) == true)
  1618. {
  1619. if (is_array($_POST['entire_file']))
  1620. $_POST['entire_file'] = implode("\n", $_POST['entire_file']);
  1621. $_POST['entire_file'] = rtrim(strtr($_POST['entire_file'], array("\r" => '', ' ' => "\t")));
  1622. // Check for a parse error!
  1623. if (substr($_REQUEST['filename'], -13) == '.template.php' && is_writable($theme_dir) && ini_get('display_errors'))
  1624. {
  1625. $request = $smcFunc['db_query']('', '
  1626. SELECT value
  1627. FROM {db_prefix}themes
  1628. WHERE variable = {string:theme_url}
  1629. AND id_theme = {int:current_theme}
  1630. LIMIT 1',
  1631. array(
  1632. 'current_theme' => $_GET['th'],
  1633. 'theme_url' => 'theme_url',
  1634. )
  1635. );
  1636. list ($theme_url) = $smcFunc['db_fetch_row']($request);
  1637. $smcFunc['db_free_result']($request);
  1638. $fp = fopen($theme_dir . '/tmp_' . session_id() . '.php', 'w');
  1639. fwrite($fp, $_POST['entire_file']);
  1640. fclose($fp);
  1641. $error = @file_get_contents($theme_url . '/tmp_' . session_id() . '.php');
  1642. if (preg_match('~ <b>(\d+)</b><br( /)?' . '>$~i', $error) != 0)
  1643. $error_file = $theme_dir . '/tmp_' . session_id() . '.php';
  1644. else
  1645. unlink($theme_dir . '/tmp_' . session_id() . '.php');
  1646. }
  1647. if (!isset($error_file))
  1648. {
  1649. $fp = fopen($theme_dir . '/' . $_REQUEST['filename'], 'w');
  1650. fwrite($fp, $_POST['entire_file']);
  1651. fclose($fp);
  1652. redirectexit('action=admin;area=theme;th=' . $_GET['th'] . ';' . $context['session_var'] . '=' . $context['session_id'] . ';sa=edit;directory=' . dirname($_REQUEST['filename']));
  1653. }
  1654. }
  1655. // Session timed out.
  1656. else
  1657. {
  1658. loadLanguage('Errors');
  1659. $context['session_error'] = true;
  1660. $context['sub_template'] = 'edit_file';
  1661. // Recycle the submitted data.
  1662. if (is_array($_POST['entire_file']))
  1663. $context['entire_file'] = htmlspecialchars(implode("\n", $_POST['entire_file']));
  1664. else
  1665. $context['entire_file'] = htmlspecialchars($_POST['entire_file']);
  1666. $context['edit_filename'] = htmlspecialchars($_POST['filename']);
  1667. // You were able to submit it, so it's reasonable to assume you are allowed to save.
  1668. $context['allow_save'] = true;
  1669. // Re-create the token so that it can be used
  1670. createToken('admin-te-' . md5($_GET['th'] . '-' . $_REQUEST['filename']));
  1671. return;
  1672. }
  1673. }
  1674. $context['allow_save'] = is_writable($theme_dir . '/' . $_REQUEST['filename']);
  1675. $context['allow_save_filename'] = strtr($theme_dir . '/' . $_REQUEST['filename'], array(BOARDDIR => '...'));
  1676. $context['edit_filename'] = htmlspecialchars($_REQUEST['filename']);
  1677. if (substr($_REQUEST['filename'], -4) == '.css')
  1678. {
  1679. $context['sub_template'] = 'edit_style';
  1680. $context['entire_file'] = htmlspecialchars(strtr(file_get_contents($theme_dir . '/' . $_REQUEST['filename']), array("\t" => ' ')));
  1681. }
  1682. elseif (substr($_REQUEST['filename'], -13) == '.template.php')
  1683. {
  1684. $context['sub_template'] = 'edit_template';
  1685. if (!isset($error_file))
  1686. $file_data = file($theme_dir . '/' . $_REQUEST['filename']);
  1687. else
  1688. {
  1689. if (preg_match('~(<b>.+?</b>:.+?<b>).+?(</b>.+?<b>\d+</b>)<br( /)?' . '>$~i', $error, $match) != 0)
  1690. $context['parse_error'] = $match[1] . $_REQUEST['filename'] . $match[2];
  1691. $file_data = file($error_file);
  1692. unlink($error_file);
  1693. }
  1694. $j = 0;
  1695. $context['file_parts'] = array(array('lines' => 0, 'line' => 1, 'data' => ''));
  1696. for ($i = 0, $n = count($file_data); $i < $n; $i++)
  1697. {
  1698. if (isset($file_data[$i + 1]) && substr($file_data[$i + 1], 0, 9) == 'function ')
  1699. {
  1700. // Try to format the functions a little nicer...
  1701. $context['file_parts'][$j]['data'] = trim($context['file_parts'][$j]['data']) . "\n";
  1702. if (empty($context['file_parts'][$j]['lines']))
  1703. unset($context['file_parts'][$j]);
  1704. $context['file_parts'][++$j] = array('lines' => 0, 'line' => $i + 1, 'data' => '');
  1705. }
  1706. $context['file_parts'][$j]['lines']++;
  1707. $context['file_parts'][$j]['data'] .= htmlspecialchars(strtr($file_data[$i], array("\t" => ' ')));
  1708. }
  1709. $context['entire_file'] = htmlspecialchars(strtr(implode('', $file_data), array("\t" => ' ')));
  1710. }
  1711. else
  1712. {
  1713. $context['sub_template'] = 'edit_file';
  1714. $context['entire_file'] = htmlspecialchars(strtr(file_get_contents($theme_dir . '/' . $_REQUEST['filename']), array("\t" => ' ')));
  1715. }
  1716. // Create a special token to allow editing of multiple files.
  1717. createToken('admin-te-' . md5($_GET['th'] . '-' . $_REQUEST['filename']));
  1718. }
  1719. /**
  1720. * Generates a file listing for a given directory
  1721. *
  1722. * @param type $path
  1723. * @param type $relative
  1724. * @return type
  1725. */
  1726. function get_file_listing($path, $relative)
  1727. {
  1728. global $scripturl, $txt, $context;
  1729. // Is it even a directory?
  1730. if (!is_dir($path))
  1731. fatal_lang_error('error_invalid_dir', 'critical');
  1732. $dir = dir($path);
  1733. $entries = array();
  1734. while ($entry = $dir->read())
  1735. $entries[] = $entry;
  1736. $dir->close();
  1737. natcasesort($entries);
  1738. $listing1 = array();
  1739. $listing2 = array();
  1740. foreach ($entries as $entry)
  1741. {
  1742. // Skip all dot files, including .htaccess.
  1743. if (substr($entry, 0, 1) == '.' || $entry == 'CVS')
  1744. continue;
  1745. if (is_dir($path . '/' . $entry))
  1746. $listing1[] = array(
  1747. 'filename' => $entry,
  1748. 'is_writable' => is_writable($path . '/' . $entry),
  1749. 'is_directory' => true,
  1750. 'is_template' => false,
  1751. 'is_image' => false,
  1752. 'is_editable' => false,
  1753. 'href' => $scripturl . '?action=admin;area=theme;th=' . $_GET['th'] . ';' . $context['session_var'] . '=' . $context['session_id'] . ';sa=edit;directory=' . $relative . $entry,
  1754. 'size' => '',
  1755. );
  1756. else
  1757. {
  1758. $size = filesize($path . '/' . $entry);
  1759. if ($size > 2048 || $size == 1024)
  1760. $size = comma_format($size / 1024) . ' ' . $txt['themeadmin_edit_kilobytes'];
  1761. else
  1762. $size = comma_format($size) . ' ' . $txt['themeadmin_edit_bytes'];
  1763. $listing2[] = array(
  1764. 'filename' => $entry,
  1765. 'is_writable' => is_writable($path . '/' . $entry),
  1766. 'is_directory' => false,
  1767. 'is_template' => preg_match('~\.template\.php$~', $entry) != 0,
  1768. 'is_image' => preg_match('~\.(jpg|jpeg|gif|bmp|png)$~', $entry) != 0,
  1769. 'is_editable' => is_writable($path . '/' . $entry) && preg_match('~\.(php|pl|css|js|vbs|xml|xslt|txt|xsl|html|htm|shtm|shtml|asp|aspx|cgi|py)$~', $entry) != 0,
  1770. 'href' => $scripturl . '?action=admin;area=theme;th=' . $_GET['th'] . ';' . $context['session_var'] . '=' . $context['session_id'] . ';sa=edit;filename=' . $relative . $entry,
  1771. 'size' => $size,
  1772. 'last_modified' => timeformat(filemtime($path . '/' . $entry)),
  1773. );
  1774. }
  1775. }
  1776. return array_merge($listing1, $listing2);
  1777. }
  1778. /**
  1779. * Makes a copy of a template file in a new location
  1780. * @uses Themes template, copy_template sub-template.
  1781. */
  1782. function action_copytemplate()
  1783. {
  1784. global $context, $settings, $smcFunc;
  1785. isAllowedTo('admin_forum');
  1786. loadTemplate('Themes');
  1787. $context[$context['admin_menu_name']]['current_subsection'] = 'edit';
  1788. $_GET['th'] = isset($_GET['th']) ? (int) $_GET['th'] : (int) $_GET['id'];
  1789. $request = $smcFunc['db_query']('', '
  1790. SELECT th1.value, th1.id_theme, th2.value
  1791. FROM {db_prefix}themes AS th1
  1792. LEFT JOIN {db_prefix}themes AS th2 ON (th2.variable = {string:base_theme_dir} AND th2.id_theme = {int:current_theme})
  1793. WHERE th1.variable = {string:theme_dir}
  1794. AND th1.id_theme = {int:current_theme}
  1795. LIMIT 1',
  1796. array(
  1797. 'current_theme' => $_GET['th'],
  1798. 'base_theme_dir' => 'base_theme_dir',
  1799. 'theme_dir' => 'theme_dir',
  1800. )
  1801. );
  1802. list ($theme_dir, $context['theme_id'], $base_theme_dir) = $smcFunc['db_fetch_row']($request);
  1803. $smcFunc['db_free_result']($request);
  1804. if (isset($_REQUEST['template']) && preg_match('~[\./\\\\:\0]~', $_REQUEST['template']) == 0)
  1805. {
  1806. if (!empty($base_theme_dir) && file_exists($base_theme_dir . '/' . $_REQUEST['template'] . '.template.php'))
  1807. $filename = $base_theme_dir . '/' . $_REQUEST['template'] . '.template.php';
  1808. elseif (file_exists($settings['default_theme_dir'] . '/' . $_REQUEST['template'] . '.template.php'))
  1809. $filename = $settings['default_theme_dir'] . '/' . $_REQUEST['template'] . '.template.php';
  1810. else
  1811. fatal_lang_error('no_access', false);
  1812. $fp = fopen($theme_dir . '/' . $_REQUEST['template'] . '.template.php', 'w');
  1813. fwrite($fp, file_get_contents($filename));
  1814. fclose($fp);
  1815. redirectexit('action=admin;area=theme;th=' . $context['theme_id'] . ';' . $context['session_var'] . '=' . $context['session_id'] . ';sa=copy');
  1816. }
  1817. elseif (isset($_REQUEST['lang_file']) && preg_match('~^[^\./\\\\:\0]\.[^\./\\\\:\0]$~', $_REQUEST['lang_file']) != 0)
  1818. {
  1819. if (!empty($base_theme_dir) && file_exists($base_theme_dir . '/languages/' . $_REQUEST['lang_file'] . '.php'))
  1820. $filename = $base_theme_dir . '/languages/' . $_REQUEST['template'] . '.php';
  1821. elseif (file_exists($settings['default_theme_dir'] . '/languages/' . $_REQUEST['template'] . '.php'))
  1822. $filename = $settings['default_theme_dir'] . '/languages/' . $_REQUEST['template'] . '.php';
  1823. else
  1824. fatal_lang_error('no_access', false);
  1825. $fp = fopen($theme_dir . '/languages/' . $_REQUEST['lang_file'] . '.php', 'w');
  1826. fwrite($fp, file_get_contents($filename));
  1827. fclose($fp);
  1828. redirectexit('action=admin;area=theme;th=' . $context['theme_id'] . ';' . $context['session_var'] . '=' . $context['session_id'] . ';sa=copy');
  1829. }
  1830. $templates = array();
  1831. $lang_files = array();
  1832. $dir = dir($settings['default_theme_dir']);
  1833. while ($entry = $dir->read())
  1834. {
  1835. if (substr($entry, -13) == '.template.php')
  1836. $templates[] = substr($entry, 0, -13);
  1837. }
  1838. $dir->close();
  1839. $dir = dir($settings['default_theme_dir'] . '/languages');
  1840. while ($entry = $dir->read())
  1841. {
  1842. if (preg_match('~^([^\.]+\.[^\.]+)\.php$~', $entry, $matches))
  1843. $lang_files[] = $matches[1];
  1844. }
  1845. $dir->close();
  1846. if (!empty($base_theme_dir))
  1847. {
  1848. $dir = dir($base_theme_dir);
  1849. while ($entry = $dir->read())
  1850. {
  1851. if (substr($entry, -13) == '.template.php' && !in_array(substr($entry, 0, -13), $templates))
  1852. $templates[] = substr($entry, 0, -13);
  1853. }
  1854. $dir->close();
  1855. if (file_exists($base_theme_dir . '/languages'))
  1856. {
  1857. $dir = dir($base_theme_dir . '/languages');
  1858. while ($entry = $dir->read())
  1859. {
  1860. if (preg_match('~^([^\.]+\.[^\.]+)\.php$~', $entry, $matches) && !in_array($matches[1], $lang_files))
  1861. $lang_files[] = $matches[1];
  1862. }
  1863. $dir->close();
  1864. }
  1865. }
  1866. natcasesort($templates);
  1867. natcasesort($lang_files);
  1868. $context['available_templates'] = array();
  1869. foreach ($templates as $template)
  1870. $context['available_templates'][$template] = array(
  1871. 'filename' => $template . '.template.php',
  1872. 'value' => $template,
  1873. 'already_exists' => false,
  1874. 'can_copy' => is_writable($theme_dir),
  1875. );
  1876. $context['available_language_files'] = array();
  1877. foreach ($lang_files as $file)
  1878. $context['available_language_files'][$file] = array(
  1879. 'filename' => $file . '.php',
  1880. 'value' => $file,
  1881. 'already_exists' => false,
  1882. 'can_copy' => file_exists($theme_dir . '/languages') ? is_writable($theme_dir . '/languages') : is_writable($theme_dir),
  1883. );
  1884. $dir = dir($theme_dir);
  1885. while ($entry = $dir->read())
  1886. {
  1887. if (substr($entry, -13) == '.template.php' && isset($context['available_templates'][substr($entry, 0, -13)]))
  1888. {
  1889. $context['available_templates'][substr($entry, 0, -13)]['already_exists'] = true;
  1890. $context['available_templates'][substr($entry, 0, -13)]['can_copy'] = is_writable($theme_dir . '/' . $entry);
  1891. }
  1892. }
  1893. $dir->close();
  1894. if (file_exists($theme_dir . '/languages'))
  1895. {
  1896. $dir = dir($theme_dir . '/languages');
  1897. while ($entry = $dir->read())
  1898. {
  1899. if (preg_match('~^([^\.]+\.[^\.]+)\.php$~', $entry, $matches) && isset($context['available_language_files'][$matches[1]]))
  1900. {
  1901. $context['available_language_files'][$matches[1]]['already_exists'] = true;
  1902. $context['available_language_files'][$matches[1]]['can_copy'] = is_writable($theme_dir . '/languages/' . $entry);
  1903. }
  1904. }
  1905. $dir->close();
  1906. }
  1907. $context['sub_template'] = 'copy_template';
  1908. }