PageRenderTime 48ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/Sources/Subs-Admin.php

https://github.com/smf-portal/SMF2.1
PHP | 526 lines | 315 code | 73 blank | 138 comment | 94 complexity | f2feed695a66afa53d199b7e838c1088 MD5 | raw file
  1. <?php
  2. /**
  3. * This file contains functions that are specifically done by administrators.
  4. *
  5. * Simple Machines Forum (SMF)
  6. *
  7. * @package SMF
  8. * @author Simple Machines http://www.simplemachines.org
  9. * @copyright 2012 Simple Machines
  10. * @license http://www.simplemachines.org/about/smf/license.php BSD
  11. *
  12. * @version 2.1 Alpha 1
  13. */
  14. if (!defined('SMF'))
  15. die('Hacking attempt...');
  16. /**
  17. * Get a list of versions that are currently installed on the server.
  18. * @param array $checkFor
  19. */
  20. function getServerVersions($checkFor)
  21. {
  22. global $txt, $db_connection, $_PHPA, $smcFunc, $memcached, $modSettings;
  23. loadLanguage('Admin');
  24. $versions = array();
  25. // Is GD available? If it is, we should show version information for it too.
  26. if (in_array('gd', $checkFor) && function_exists('gd_info'))
  27. {
  28. $temp = gd_info();
  29. $versions['gd'] = array('title' => $txt['support_versions_gd'], 'version' => $temp['GD Version']);
  30. }
  31. // Why not have a look at ImageMagick? If it is, we should show version information for it too.
  32. if (in_array('imagick', $checkFor) && class_exists('Imagick'))
  33. {
  34. $temp = New Imagick;
  35. $temp2 = $temp->getVersion();
  36. $versions['imagick'] = array('title' => $txt['support_versions_imagick'], 'version' => $temp2['versionString']);
  37. }
  38. // Now lets check for the Database.
  39. if (in_array('db_server', $checkFor))
  40. {
  41. db_extend();
  42. if (!isset($db_connection) || $db_connection === false)
  43. trigger_error('getServerVersions(): you need to be connected to the database in order to get its server version', E_USER_NOTICE);
  44. else
  45. {
  46. $versions['db_server'] = array('title' => sprintf($txt['support_versions_db'], $smcFunc['db_title']), 'version' => '');
  47. $versions['db_server']['version'] = $smcFunc['db_get_version']();
  48. }
  49. }
  50. // If we're using memcache we need the server info.
  51. if (empty($memcached) && function_exists('memcache_get') && isset($modSettings['cache_memcached']) && trim($modSettings['cache_memcached']) != '')
  52. get_memcached_server();
  53. // Check to see if we have any accelerators installed...
  54. if (in_array('mmcache', $checkFor) && defined('MMCACHE_VERSION'))
  55. $versions['mmcache'] = array('title' => 'Turck MMCache', 'version' => MMCACHE_VERSION);
  56. if (in_array('eaccelerator', $checkFor) && defined('EACCELERATOR_VERSION'))
  57. $versions['eaccelerator'] = array('title' => 'eAccelerator', 'version' => EACCELERATOR_VERSION);
  58. if (in_array('phpa', $checkFor) && isset($_PHPA))
  59. $versions['phpa'] = array('title' => 'ionCube PHP-Accelerator', 'version' => $_PHPA['VERSION']);
  60. if (in_array('apc', $checkFor) && extension_loaded('apc'))
  61. $versions['apc'] = array('title' => 'Alternative PHP Cache', 'version' => phpversion('apc'));
  62. if (in_array('memcache', $checkFor) && function_exists('memcache_set'))
  63. $versions['memcache'] = array('title' => 'Memcached', 'version' => empty($memcached) ? '???' : memcache_get_version($memcached));
  64. if (in_array('xcache', $checkFor) && function_exists('xcache_set'))
  65. $versions['xcache'] = array('title' => 'XCache', 'version' => XCACHE_VERSION);
  66. if (in_array('php', $checkFor))
  67. $versions['php'] = array('title' => 'PHP', 'version' => PHP_VERSION, 'more' => '?action=admin;area=serversettings;sa=phpinfo');
  68. if (in_array('server', $checkFor))
  69. $versions['server'] = array('title' => $txt['support_versions_server'], 'version' => $_SERVER['SERVER_SOFTWARE']);
  70. return $versions;
  71. }
  72. /**
  73. * Search through source, theme and language files to determine their version.
  74. * Get detailed version information about the physical SMF files on the server.
  75. *
  76. * - the input parameter allows to set whether to include SSI.php and whether
  77. * the results should be sorted.
  78. * - returns an array containing information on source files, templates and
  79. * language files found in the default theme directory (grouped by language).
  80. *
  81. * @param array &$versionOptions
  82. */
  83. function getFileVersions(&$versionOptions)
  84. {
  85. global $boarddir, $sourcedir, $settings;
  86. // Default place to find the languages would be the default theme dir.
  87. $lang_dir = $settings['default_theme_dir'] . '/languages';
  88. $version_info = array(
  89. 'file_versions' => array(),
  90. 'default_template_versions' => array(),
  91. 'template_versions' => array(),
  92. 'default_language_versions' => array(),
  93. );
  94. // Find the version in SSI.php's file header.
  95. if (!empty($versionOptions['include_ssi']) && file_exists($boarddir . '/SSI.php'))
  96. {
  97. $fp = fopen($boarddir . '/SSI.php', 'rb');
  98. $header = fread($fp, 4096);
  99. fclose($fp);
  100. // The comment looks rougly like... that.
  101. if (preg_match('~\*\s@version\s+(.+)[\s]{2}~i', $header, $match) == 1)
  102. $version_info['file_versions']['SSI.php'] = $match[1];
  103. // Not found! This is bad.
  104. else
  105. $version_info['file_versions']['SSI.php'] = '??';
  106. }
  107. // Do the paid subscriptions handler?
  108. if (!empty($versionOptions['include_subscriptions']) && file_exists($boarddir . '/subscriptions.php'))
  109. {
  110. $fp = fopen($boarddir . '/subscriptions.php', 'rb');
  111. $header = fread($fp, 4096);
  112. fclose($fp);
  113. // Found it?
  114. if (preg_match('~\*\s@version\s+(.+)[\s]{2}~i', $header, $match) == 1)
  115. $version_info['file_versions']['subscriptions.php'] = $match[1];
  116. // If we haven't how do we all get paid?
  117. else
  118. $version_info['file_versions']['subscriptions.php'] = '??';
  119. }
  120. // Load all the files in the Sources directory, except this file and the redirect.
  121. $sources_dir = dir($sourcedir);
  122. while ($entry = $sources_dir->read())
  123. {
  124. if (substr($entry, -4) === '.php' && !is_dir($sourcedir . '/' . $entry) && $entry !== 'index.php')
  125. {
  126. // Read the first 4k from the file.... enough for the header.
  127. $fp = fopen($sourcedir . '/' . $entry, 'rb');
  128. $header = fread($fp, 4096);
  129. fclose($fp);
  130. // Look for the version comment in the file header.
  131. if (preg_match('~\*\s@version\s+(.+)[\s]{2}~i', $header, $match) == 1)
  132. $version_info['file_versions'][$entry] = $match[1];
  133. // It wasn't found, but the file was... show a '??'.
  134. else
  135. $version_info['file_versions'][$entry] = '??';
  136. }
  137. }
  138. $sources_dir->close();
  139. // Load all the files in the default template directory - and the current theme if applicable.
  140. $directories = array('default_template_versions' => $settings['default_theme_dir']);
  141. if ($settings['theme_id'] != 1)
  142. $directories += array('template_versions' => $settings['theme_dir']);
  143. foreach ($directories as $type => $dirname)
  144. {
  145. $this_dir = dir($dirname);
  146. while ($entry = $this_dir->read())
  147. {
  148. if (substr($entry, -12) == 'template.php' && !is_dir($dirname . '/' . $entry))
  149. {
  150. // Read the first 768 bytes from the file.... enough for the header.
  151. $fp = fopen($dirname . '/' . $entry, 'rb');
  152. $header = fread($fp, 768);
  153. fclose($fp);
  154. // Look for the version comment in the file header.
  155. if (preg_match('~\*\s@version\s+(.+)[\s]{2}~i', $header, $match) == 1)
  156. $version_info[$type][$entry] = $match[1];
  157. // It wasn't found, but the file was... show a '??'.
  158. else
  159. $version_info[$type][$entry] = '??';
  160. }
  161. }
  162. $this_dir->close();
  163. }
  164. // Load up all the files in the default language directory and sort by language.
  165. $this_dir = dir($lang_dir);
  166. while ($entry = $this_dir->read())
  167. {
  168. if (substr($entry, -4) == '.php' && $entry != 'index.php' && !is_dir($lang_dir . '/' . $entry))
  169. {
  170. // Read the first 768 bytes from the file.... enough for the header.
  171. $fp = fopen($lang_dir . '/' . $entry, 'rb');
  172. $header = fread($fp, 768);
  173. fclose($fp);
  174. // Split the file name off into useful bits.
  175. list ($name, $language) = explode('.', $entry);
  176. // Look for the version comment in the file header.
  177. if (preg_match('~(?://|/\*)\s*Version:\s+(.+?);\s*' . preg_quote($name, '~') . '(?:[\s]{2}|\*/)~i', $header, $match) == 1)
  178. $version_info['default_language_versions'][$language][$name] = $match[1];
  179. // It wasn't found, but the file was... show a '??'.
  180. else
  181. $version_info['default_language_versions'][$language][$name] = '??';
  182. }
  183. }
  184. $this_dir->close();
  185. // Sort the file versions by filename.
  186. if (!empty($versionOptions['sort_results']))
  187. {
  188. ksort($version_info['file_versions']);
  189. ksort($version_info['default_template_versions']);
  190. ksort($version_info['template_versions']);
  191. ksort($version_info['default_language_versions']);
  192. // For languages sort each language too.
  193. foreach ($version_info['default_language_versions'] as $language => $dummy)
  194. ksort($version_info['default_language_versions'][$language]);
  195. }
  196. return $version_info;
  197. }
  198. /**
  199. * Update the Settings.php file.
  200. *
  201. * The most important function in this file for mod makers happens to be the
  202. * updateSettingsFile() function, but it shouldn't be used often anyway.
  203. *
  204. * - updates the Settings.php file with the changes supplied in config_vars.
  205. * - expects config_vars to be an associative array, with the keys as the
  206. * variable names in Settings.php, and the values the variable values.
  207. * - does not escape or quote values.
  208. * - preserves case, formatting, and additional options in file.
  209. * - writes nothing if the resulting file would be less than 10 lines
  210. * in length (sanity check for read lock.)
  211. * - check for changes to db_last_error and passes those off to a separate handler
  212. * - attempts to create a backup file and will use it should the writing of the
  213. * new settings file fail
  214. *
  215. * @param array $config_vars
  216. */
  217. function updateSettingsFile($config_vars)
  218. {
  219. global $boarddir, $cachedir, $context;
  220. // Updating the db_last_error, then don't mess around with Settings.php
  221. if (count($config_vars) === 1 && isset($config_vars['db_last_error']))
  222. {
  223. updateDbLastError($config_vars['db_last_error']);
  224. return;
  225. }
  226. // When was Settings.php last changed?
  227. $last_settings_change = filemtime($boarddir . '/Settings.php');
  228. // Load the settings file.
  229. $settingsArray = trim(file_get_contents($boarddir . '/Settings.php'));
  230. // Break it up based on \r or \n, and then clean out extra characters.
  231. if (strpos($settingsArray, "\n") !== false)
  232. $settingsArray = explode("\n", $settingsArray);
  233. elseif (strpos($settingsArray, "\r") !== false)
  234. $settingsArray = explode("\r", $settingsArray);
  235. else
  236. return;
  237. // Presumably, the file has to have stuff in it for this function to be called :P.
  238. if (count($settingsArray) < 10)
  239. return;
  240. // remove any /r's that made there way in here
  241. foreach ($settingsArray as $k => $dummy)
  242. $settingsArray[$k] = strtr($dummy, array("\r" => '')) . "\n";
  243. // go line by line and see whats changing
  244. for ($i = 0, $n = count($settingsArray); $i < $n; $i++)
  245. {
  246. // Don't trim or bother with it if it's not a variable.
  247. if (substr($settingsArray[$i], 0, 1) != '$')
  248. continue;
  249. $settingsArray[$i] = trim($settingsArray[$i]) . "\n";
  250. // Look through the variables to set....
  251. foreach ($config_vars as $var => $val)
  252. {
  253. // be sure someone is not updating db_last_error this with a group
  254. if ($var === 'db_last_error')
  255. {
  256. updateDbLastError($val);
  257. unset($config_vars[$var]);
  258. }
  259. elseif (strncasecmp($settingsArray[$i], '$' . $var, 1 + strlen($var)) == 0)
  260. {
  261. $comment = strstr(substr($settingsArray[$i], strpos($settingsArray[$i], ';')), '#');
  262. $settingsArray[$i] = '$' . $var . ' = ' . $val . ';' . ($comment == '' ? '' : "\t\t" . rtrim($comment)) . "\n";
  263. // This one's been 'used', so to speak.
  264. unset($config_vars[$var]);
  265. }
  266. }
  267. // End of the file ... maybe
  268. if (substr(trim($settingsArray[$i]), 0, 2) == '?' . '>')
  269. $end = $i;
  270. }
  271. // This should never happen, but apparently it is happening.
  272. if (empty($end) || $end < 10)
  273. $end = count($settingsArray) - 1;
  274. // Still more variables to go? Then lets add them at the end.
  275. if (!empty($config_vars))
  276. {
  277. if (trim($settingsArray[$end]) == '?' . '>')
  278. $settingsArray[$end++] = '';
  279. else
  280. $end++;
  281. // Add in any newly defined vars that were passed
  282. foreach ($config_vars as $var => $val)
  283. $settingsArray[$end++] = '$' . $var . ' = ' . $val . ';' . "\n";
  284. $settingsArray[$end] = '?' . '>';
  285. }
  286. else
  287. $settingsArray[$end] = trim($settingsArray[$end]);
  288. // Sanity error checking: the file needs to be at least 12 lines.
  289. if (count($settingsArray) < 12)
  290. return;
  291. // Try to avoid a few pitfalls:
  292. // - like a possible race condition,
  293. // - or a failure to write at low diskspace
  294. //
  295. // Check before you act: if cache is enabled, we can do a simple write test
  296. // to validate that we even write things on this filesystem.
  297. if ((empty($cachedir) || !file_exists($cachedir)) && file_exists($boarddir . '/cache'))
  298. $cachedir = $boarddir . '/cache';
  299. $test_fp = @fopen($cachedir . '/settings_update.tmp', "w+");
  300. if ($test_fp)
  301. {
  302. fclose($test_fp);
  303. $written_bytes = file_put_contents($cachedir . '/settings_update.tmp', 'test', LOCK_EX);
  304. @unlink($cachedir . '/settings_update.tmp');
  305. if ($written_bytes !== 4)
  306. {
  307. // Oops. Low disk space, perhaps. Don't mess with Settings.php then.
  308. // No means no. :P
  309. return;
  310. }
  311. }
  312. // Protect me from what I want! :P
  313. clearstatcache();
  314. if (filemtime($boarddir . '/Settings.php') === $last_settings_change)
  315. {
  316. // save the old before we do anything
  317. $file = $boarddir . '/Settings.php';
  318. $settings_backup_fail = !@is_writable($boarddir . '/Settings_bak.php') || !@copy($boarddir . '/Settings.php', $boarddir . '/Settings_bak.php');
  319. $settings_backup_fail = !$settings_backup_fail ? (!file_exists($boarddir . '/Settings_bak.php') || filesize($boarddir . '/Settings_bak.php') === 0) : $settings_backup_fail;
  320. // write out the new
  321. $write_settings = implode('', $settingsArray);
  322. $written_bytes = file_put_contents($boarddir . '/Settings.php', $write_settings, LOCK_EX);
  323. // survey says ...
  324. if ($written_bytes !== strlen($write_settings) && !$settings_backup_fail)
  325. {
  326. // Well this is not good at all, lets see if we can save this
  327. $context['settings_message'] = 'settings_error';
  328. if (file_exists($boarddir . '/Settings_bak.php'))
  329. @copy($boarddir . '/Settings_bak.php', $boarddir . '/Settings.php');
  330. }
  331. }
  332. }
  333. /**
  334. * Saves the time of the last db error for the error log
  335. * - Done separately from updateSettingsFile to avoid race conditions
  336. * which can occur during a db error
  337. * - If it fails Settings.php will assume 0
  338. *
  339. * @param type $time
  340. */
  341. function updateDbLastError($time)
  342. {
  343. global $boarddir;
  344. // Write out the db_last_error file with the error timestamp
  345. file_put_contents($boarddir . '/db_last_error.php', '<' . '?' . "php\n" . '$db_last_error = ' . $time . ';' . "\n" . '?' . '>', LOCK_EX);
  346. @touch($boarddir . '/' . 'Settings.php');
  347. }
  348. /**
  349. * Saves the admins current preferences to the database.
  350. */
  351. function updateAdminPreferences()
  352. {
  353. global $options, $context, $smcFunc, $settings, $user_info;
  354. // This must exist!
  355. if (!isset($context['admin_preferences']))
  356. return false;
  357. // This is what we'll be saving.
  358. $options['admin_preferences'] = serialize($context['admin_preferences']);
  359. // Just check we haven't ended up with something theme exclusive somehow.
  360. $smcFunc['db_query']('', '
  361. DELETE FROM {db_prefix}themes
  362. WHERE id_theme != {int:default_theme}
  363. AND variable = {string:admin_preferences}',
  364. array(
  365. 'default_theme' => 1,
  366. 'admin_preferences' => 'admin_preferences',
  367. )
  368. );
  369. // Update the themes table.
  370. $smcFunc['db_insert']('replace',
  371. '{db_prefix}themes',
  372. array('id_member' => 'int', 'id_theme' => 'int', 'variable' => 'string-255', 'value' => 'string-65534'),
  373. array($user_info['id'], 1, 'admin_preferences', $options['admin_preferences']),
  374. array('id_member', 'id_theme', 'variable')
  375. );
  376. // Make sure we invalidate any cache.
  377. cache_put_data('theme_settings-' . $settings['theme_id'] . ':' . $user_info['id'], null, 0);
  378. }
  379. /**
  380. * Send all the administrators a lovely email.
  381. * - loads all users who are admins or have the admin forum permission.
  382. * - uses the email template and replacements passed in the parameters.
  383. * - sends them an email.
  384. *
  385. * @param string $template
  386. * @param array $replacements
  387. * @param array $additional_recipients
  388. */
  389. function emailAdmins($template, $replacements = array(), $additional_recipients = array())
  390. {
  391. global $smcFunc, $sourcedir, $language, $modSettings;
  392. // We certainly want this.
  393. require_once($sourcedir . '/Subs-Post.php');
  394. // Load all groups which are effectively admins.
  395. $request = $smcFunc['db_query']('', '
  396. SELECT id_group
  397. FROM {db_prefix}permissions
  398. WHERE permission = {string:admin_forum}
  399. AND add_deny = {int:add_deny}
  400. AND id_group != {int:id_group}',
  401. array(
  402. 'add_deny' => 1,
  403. 'id_group' => 0,
  404. 'admin_forum' => 'admin_forum',
  405. )
  406. );
  407. $groups = array(1);
  408. while ($row = $smcFunc['db_fetch_assoc']($request))
  409. $groups[] = $row['id_group'];
  410. $smcFunc['db_free_result']($request);
  411. $request = $smcFunc['db_query']('', '
  412. SELECT id_member, member_name, real_name, lngfile, email_address
  413. FROM {db_prefix}members
  414. WHERE (id_group IN ({array_int:group_list}) OR FIND_IN_SET({raw:group_array_implode}, additional_groups) != 0)
  415. AND notify_types != {int:notify_types}
  416. ORDER BY lngfile',
  417. array(
  418. 'group_list' => $groups,
  419. 'notify_types' => 4,
  420. 'group_array_implode' => implode(', additional_groups) != 0 OR FIND_IN_SET(', $groups),
  421. )
  422. );
  423. $emails_sent = array();
  424. while ($row = $smcFunc['db_fetch_assoc']($request))
  425. {
  426. // Stick their particulars in the replacement data.
  427. $replacements['IDMEMBER'] = $row['id_member'];
  428. $replacements['REALNAME'] = $row['member_name'];
  429. $replacements['USERNAME'] = $row['real_name'];
  430. // Load the data from the template.
  431. $emaildata = loadEmailTemplate($template, $replacements, empty($row['lngfile']) || empty($modSettings['userLanguage']) ? $language : $row['lngfile']);
  432. // Then send the actual email.
  433. sendmail($row['email_address'], $emaildata['subject'], $emaildata['body'], null, null, false, 1);
  434. // Track who we emailed so we don't do it twice.
  435. $emails_sent[] = $row['email_address'];
  436. }
  437. $smcFunc['db_free_result']($request);
  438. // Any additional users we must email this to?
  439. if (!empty($additional_recipients))
  440. foreach ($additional_recipients as $recipient)
  441. {
  442. if (in_array($recipient['email'], $emails_sent))
  443. continue;
  444. $replacements['IDMEMBER'] = $recipient['id'];
  445. $replacements['REALNAME'] = $recipient['name'];
  446. $replacements['USERNAME'] = $recipient['name'];
  447. // Load the template again.
  448. $emaildata = loadEmailTemplate($template, $replacements, empty($recipient['lang']) || empty($modSettings['userLanguage']) ? $language : $recipient['lang']);
  449. // Send off the email.
  450. sendmail($recipient['email'], $emaildata['subject'], $emaildata['body'], null, null, false, 1);
  451. }
  452. }
  453. ?>