Subs-Admin.php 18 KB

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