Browse Source

! Refactoring and adding code documentation. (many files.)
! Small tweaks in coding style and commenting in ManageLanguages template for Antechinus to see. :P
! One more little refactoring step. Move writeLog() from Subs.php to Errors.php.
! NB: found a bug/incomplete feature in Search.php related to this, documented it a bit.

Spuds 12 years ago
parent
commit
a36b389a3e

+ 2 - 1
Sources/Display.php

@@ -1229,7 +1229,7 @@ function Download()
 		isAllowedTo('view_attachments');
 
 		// Make sure this attachment is on this board.
-		// NOTE: We must verify that $topic is the attachment's topic, or else the permission check above is broken.
+		// @todo: We must verify that $topic is the attachment's topic, or else the permission check above is broken.
 		$request = $smcFunc['db_query']('', '
 			SELECT a.id_folder, a.filename, a.file_hash, a.fileext, a.id_attach, a.attachment_type, a.mime_type, a.approved, m.id_member
 			FROM {db_prefix}attachments AS a
@@ -1429,6 +1429,7 @@ function Download()
  * This loads an attachment's contextual data including, most importantly, its size
  *  if it is an image.
  *  Pre-condition: $attachments array to have been filled with the proper attachment data, as Display() does.
+ *  (@todo change this pre-condition, too fragile and error-prone.)
  *  It requires the view_attachments permission to calculate image size.
  *  It attempts to keep the "aspect ratio" of the posted image in line, even if it has to be resized by
  *  the max_image_width and max_image_height settings.

+ 138 - 0
Sources/Errors.php

@@ -719,4 +719,142 @@ function show_db_error($loadavg = false)
 	die;
 }
 
+/**
+ * Put this user in the online log.
+ *
+ * @param bool $force = false
+ */
+function writeLog($force = false)
+{
+	global $user_info, $user_settings, $context, $modSettings, $settings, $topic, $board, $smcFunc, $sourcedir;
+
+	// If we are showing who is viewing a topic, let's see if we are, and force an update if so - to make it accurate.
+	if (!empty($settings['display_who_viewing']) && ($topic || $board))
+	{
+		// Take the opposite approach!
+		$force = true;
+		// Don't update for every page - this isn't wholly accurate but who cares.
+		if ($topic)
+		{
+			if (isset($_SESSION['last_topic_id']) && $_SESSION['last_topic_id'] == $topic)
+				$force = false;
+			$_SESSION['last_topic_id'] = $topic;
+		}
+	}
+
+	// Are they a spider we should be tracking? Mode = 1 gets tracked on its spider check...
+	if (!empty($user_info['possibly_robot']) && !empty($modSettings['spider_mode']) && $modSettings['spider_mode'] > 1)
+	{
+		require_once($sourcedir . '/ManageSearchEngines.php');
+		logSpider();
+	}
+
+	// Don't mark them as online more than every so often.
+	if (!empty($_SESSION['log_time']) && $_SESSION['log_time'] >= (time() - 8) && !$force)
+		return;
+
+	if (!empty($modSettings['who_enabled']))
+	{
+		$serialized = $_GET + array('USER_AGENT' => $_SERVER['HTTP_USER_AGENT']);
+
+		// In the case of a dlattach action, session_var may not be set.
+		if (!isset($context['session_var']))
+			$context['session_var'] = $_SESSION['session_var'];
+
+		unset($serialized['sesc'], $serialized[$context['session_var']]);
+		$serialized = serialize($serialized);
+	}
+	else
+		$serialized = '';
+
+	// Guests use 0, members use their session ID.
+	$session_id = $user_info['is_guest'] ? 'ip' . $user_info['ip'] : session_id();
+
+	// Grab the last all-of-SMF-specific log_online deletion time.
+	$do_delete = cache_get_data('log_online-update', 30) < time() - 30;
+
+	// If the last click wasn't a long time ago, and there was a last click...
+	if (!empty($_SESSION['log_time']) && $_SESSION['log_time'] >= time() - $modSettings['lastActive'] * 20)
+	{
+		if ($do_delete)
+		{
+			$smcFunc['db_query']('delete_log_online_interval', '
+				DELETE FROM {db_prefix}log_online
+				WHERE log_time < {int:log_time}
+					AND session != {string:session}',
+				array(
+					'log_time' => time() - $modSettings['lastActive'] * 60,
+					'session' => $session_id,
+				)
+			);
+
+			// Cache when we did it last.
+			cache_put_data('log_online-update', time(), 30);
+		}
+
+		$smcFunc['db_query']('', '
+			UPDATE {db_prefix}log_online
+			SET log_time = {int:log_time}, ip = IFNULL(INET_ATON({string:ip}), 0), url = {string:url}
+			WHERE session = {string:session}',
+			array(
+				'log_time' => time(),
+				'ip' => $user_info['ip'],
+				'url' => $serialized,
+				'session' => $session_id,
+			)
+		);
+
+		// Guess it got deleted.
+		if ($smcFunc['db_affected_rows']() == 0)
+			$_SESSION['log_time'] = 0;
+	}
+	else
+		$_SESSION['log_time'] = 0;
+
+	// Otherwise, we have to delete and insert.
+	if (empty($_SESSION['log_time']))
+	{
+		if ($do_delete || !empty($user_info['id']))
+			$smcFunc['db_query']('', '
+				DELETE FROM {db_prefix}log_online
+				WHERE ' . ($do_delete ? 'log_time < {int:log_time}' : '') . ($do_delete && !empty($user_info['id']) ? ' OR ' : '') . (empty($user_info['id']) ? '' : 'id_member = {int:current_member}'),
+				array(
+					'current_member' => $user_info['id'],
+					'log_time' => time() - $modSettings['lastActive'] * 60,
+				)
+			);
+
+		$smcFunc['db_insert']($do_delete ? 'ignore' : 'replace',
+			'{db_prefix}log_online',
+			array('session' => 'string', 'id_member' => 'int', 'id_spider' => 'int', 'log_time' => 'int', 'ip' => 'raw', 'url' => 'string'),
+			array($session_id, $user_info['id'], empty($_SESSION['id_robot']) ? 0 : $_SESSION['id_robot'], time(), 'IFNULL(INET_ATON(\'' . $user_info['ip'] . '\'), 0)', $serialized),
+			array('session')
+		);
+	}
+
+	// Mark your session as being logged.
+	$_SESSION['log_time'] = time();
+
+	// Well, they are online now.
+	if (empty($_SESSION['timeOnlineUpdated']))
+		$_SESSION['timeOnlineUpdated'] = time();
+
+	// Set their login time, if not already done within the last minute.
+	if (SMF != 'SSI' && !empty($user_info['last_login']) && $user_info['last_login'] < time() - 60)
+	{
+		// Don't count longer than 15 minutes.
+		if (time() - $_SESSION['timeOnlineUpdated'] > 60 * 15)
+			$_SESSION['timeOnlineUpdated'] = time();
+
+		$user_settings['total_time_logged_in'] += time() - $_SESSION['timeOnlineUpdated'];
+		updateMemberData($user_info['id'], array('last_login' => time(), 'member_ip' => $user_info['ip'], 'member_ip2' => $_SERVER['BAN_CHECK_IP'], 'total_time_logged_in' => $user_settings['total_time_logged_in']));
+
+		if (!empty($modSettings['cache_enable']) && $modSettings['cache_enable'] >= 2)
+			cache_put_data('user_settings-' . $user_info['id'], $user_settings, 60);
+
+		$user_info['total_time_logged_in'] += time() - $_SESSION['timeOnlineUpdated'];
+		$_SESSION['timeOnlineUpdated'] = time();
+	}
+}
+
 ?>

+ 1363 - 0
Sources/ManageLanguages.php

@@ -0,0 +1,1363 @@
+<?php
+
+/**
+ * This file handles the administration of languages tasks.
+ *
+ * Simple Machines Forum (SMF)
+ *
+ * @package SMF
+ * @author Simple Machines
+ *
+ * @copyright 2011 Simple Machines
+ * @license http://www.simplemachines.org/about/smf/license.php BSD
+ *
+ * @version 2.0
+ */
+
+if (!defined('SMF'))
+	die('Hacking attempt...');
+
+/**
+ * This is the main function for the languages area.
+ * It dispatches the requests.
+ * Loads the ManageLanguages template. (sub-actions will use it)
+ * @todo lazy loading.
+ *
+ * @uses ManageSettings language file
+ */
+function ManageLanguages()
+{
+	global $context, $txt, $scripturl, $modSettings;
+
+	loadTemplate('ManageLanguages');
+	loadLanguage('ManageSettings');
+
+	$context['page_title'] = $txt['edit_languages'];
+	$context['sub_template'] = 'show_settings';
+
+	$subActions = array(
+		'edit' => 'ModifyLanguages',
+		'add' => 'AddLanguage',
+		'settings' => 'ModifyLanguageSettings',
+		'downloadlang' => 'DownloadLanguage',
+		'editlang' => 'ModifyLanguage',
+	);
+
+	// By default we're managing languages.
+	$_REQUEST['sa'] = isset($_REQUEST['sa']) && isset($subActions[$_REQUEST['sa']]) ? $_REQUEST['sa'] : 'edit';
+	$context['sub_action'] = $_REQUEST['sa'];
+
+	// Load up all the tabs...
+	$context[$context['admin_menu_name']]['tab_data'] = array(
+		'title' => $txt['language_configuration'],
+		'description' => $txt['language_description'],
+	);
+
+	// Call the right function for this sub-acton.
+	$subActions[$_REQUEST['sa']]();
+}
+
+/**
+ * Interface for adding a new language
+ *
+ * @uses ManageLanguages template, add_language sub-template.
+ */
+function AddLanguage()
+{
+	global $context, $sourcedir, $forum_version, $boarddir, $txt, $smcFunc, $scripturl;
+
+	// Are we searching for new languages courtesy of Simple Machines?
+	if (!empty($_POST['smf_add_sub']))
+	{
+		// Need fetch_web_data.
+		require_once($sourcedir . '/Subs-Package.php');
+
+		$context['smf_search_term'] = htmlspecialchars(trim($_POST['smf_add']));
+
+		// We're going to use this URL.
+		$url = 'http://download.simplemachines.org/fetch_language.php?version=' . urlencode(strtr($forum_version, array('SMF ' => '')));
+
+		// Load the class file and stick it into an array.
+		loadClassFile('Class-Package.php');
+		$language_list = new xmlArray(fetch_web_data($url), true);
+
+		// Check it exists.
+		if (!$language_list->exists('languages'))
+			$context['smf_error'] = 'no_response';
+		else
+		{
+			$language_list = $language_list->path('languages[0]');
+			$lang_files = $language_list->set('language');
+			$context['smf_languages'] = array();
+			foreach ($lang_files as $file)
+			{
+				// Were we searching?
+				if (!empty($context['smf_search_term']) && strpos($file->fetch('name'), $smcFunc['strtolower']($context['smf_search_term'])) === false)
+					continue;
+
+				$context['smf_languages'][] = array(
+					'id' => $file->fetch('id'),
+					'name' => $smcFunc['ucwords']($file->fetch('name')),
+					'version' => $file->fetch('version'),
+					'utf8' => $file->fetch('utf8'),
+					'description' => $file->fetch('description'),
+					'link' => $scripturl . '?action=admin;area=languages;sa=downloadlang;did=' . $file->fetch('id') . ';' . $context['session_var'] . '=' . $context['session_id'],
+				);
+			}
+			if (empty($context['smf_languages']))
+				$context['smf_error'] = 'no_files';
+		}
+	}
+
+	$context['sub_template'] = 'add_language';
+}
+
+/**
+ * Download a language file from the Simple Machines website.
+ * Requires a valid download ID ("did") in the URL.
+ * Also handles installing language files.
+ * Attempts to chmod things as needed.
+ * Uses a standard list to display information about all the files and where they'll be put.
+ *
+ * @uses ManageLanguages template, download_language sub-template.
+ * @uses Admin template, show_list sub-template.
+ */
+function DownloadLanguage()
+{
+	global $context, $sourcedir, $forum_version, $boarddir, $txt, $smcFunc, $scripturl, $modSettings;
+
+	loadLanguage('ManageSettings');
+	require_once($sourcedir . '/Subs-Package.php');
+
+	// Clearly we need to know what to request.
+	if (!isset($_GET['did']))
+		fatal_lang_error('no_access', false);
+
+	// Some lovely context.
+	$context['download_id'] = $_GET['did'];
+	$context['sub_template'] = 'download_language';
+	$context['menu_data_' . $context['admin_menu_id']]['current_subsection'] = 'add';
+
+	// Can we actually do the installation - and do they want to?
+	if (!empty($_POST['do_install']) && !empty($_POST['copy_file']))
+	{
+		checkSession('get');
+
+		$chmod_files = array();
+		$install_files = array();
+		// Check writable status.
+		foreach ($_POST['copy_file'] as $file)
+		{
+			// Check it's not very bad.
+			if (strpos($file, '..') !== false || (substr($file, 0, 6) != 'Themes' && !preg_match('~agreement\.[A-Za-z-_0-9]+\.txt$~', $file)))
+				fatal_error($txt['languages_download_illegal_paths']);
+
+			$chmod_files[] = $boarddir . '/' . $file;
+			$install_files[] = $file;
+		}
+
+		// Call this in case we have work to do.
+		$file_status = create_chmod_control($chmod_files);
+		$files_left = $file_status['files']['notwritable'];
+
+		// Something not writable?
+		if (!empty($files_left))
+			$context['error_message'] = $txt['languages_download_not_chmod'];
+		// Otherwise, go go go!
+		elseif (!empty($install_files))
+		{
+			$archive_content = read_tgz_file('http://download.simplemachines.org/fetch_language.php?version=' . urlencode(strtr($forum_version, array('SMF ' => ''))) . ';fetch=' . urlencode($_GET['did']), $boarddir, false, true, $install_files);
+			// Make sure the files aren't stuck in the cache.
+			package_flush_cache();
+			$context['install_complete'] = sprintf($txt['languages_download_complete_desc'], $scripturl . '?action=admin;area=languages');
+
+			return;
+		}
+	}
+
+	// Open up the old china.
+	if (!isset($archive_content))
+		$archive_content = read_tgz_file('http://download.simplemachines.org/fetch_language.php?version=' . urlencode(strtr($forum_version, array('SMF ' => ''))) . ';fetch=' . urlencode($_GET['did']), null);
+
+	if (empty($archive_content))
+		fatal_error($txt['add_language_error_no_response']);
+
+	// Now for each of the files, let's do some *stuff*
+	$context['files'] = array(
+		'lang' => array(),
+		'other' => array(),
+	);
+	$context['make_writable'] = array();
+	foreach ($archive_content as $file)
+	{
+		$dirname = dirname($file['filename']);
+		$filename = basename($file['filename']);
+		$extension = substr($filename, strrpos($filename, '.') + 1);
+
+		// Don't do anything with files we don't understand.
+		if (!in_array($extension, array('php', 'jpg', 'gif', 'jpeg', 'png', 'txt')))
+			continue;
+
+		// Basic data.
+		$context_data = array(
+			'name' => $filename,
+			'destination' => $boarddir . '/' . $file['filename'],
+			'generaldest' => $file['filename'],
+			'size' => $file['size'],
+			// Does chmod status allow the copy?
+			'writable' => false,
+			// Should we suggest they copy this file?
+			'default_copy' => true,
+			// Does the file already exist, if so is it same or different?
+			'exists' => false,
+		);
+
+		// Does the file exist, is it different and can we overwrite?
+		if (file_exists($boarddir . '/' . $file['filename']))
+		{
+			if (is_writable($boarddir . '/' . $file['filename']))
+				$context_data['writable'] = true;
+
+			// Finally, do we actually think the content has changed?
+			if ($file['size'] == filesize($boarddir . '/' . $file['filename']) && $file['md5'] == md5_file($boarddir . '/' . $file['filename']))
+			{
+				$context_data['exists'] = 'same';
+				$context_data['default_copy'] = false;
+			}
+			// Attempt to discover newline character differences.
+			elseif ($file['md5'] == md5(preg_replace("~[\r]?\n~", "\r\n", file_get_contents($boarddir . '/' . $file['filename']))))
+			{
+				$context_data['exists'] = 'same';
+				$context_data['default_copy'] = false;
+			}
+			else
+				$context_data['exists'] = 'different';
+		}
+		// No overwrite?
+		else
+		{
+			// Can we at least stick it in the directory...
+			if (is_writable($boarddir . '/' . $dirname))
+				$context_data['writable'] = true;
+		}
+
+		// I love PHP files, that's why I'm a developer and not an artistic type spending my time drinking absinth and living a life of sin...
+		if ($extension == 'php' && preg_match('~\w+\.\w+(?:-utf8)?\.php~', $filename))
+		{
+			$context_data += array(
+				'version' => '??',
+				'cur_version' => false,
+				'version_compare' => 'newer',
+			);
+
+			list ($name, $language) = explode('.', $filename);
+
+			// Let's get the new version, I like versions, they tell me that I'm up to date.
+			if (preg_match('~\s*Version:\s+(.+?);\s*' . preg_quote($name, '~') . '~i', $file['preview'], $match) == 1)
+				$context_data['version'] = $match[1];
+
+			// Now does the old file exist - if so what is it's version?
+			if (file_exists($boarddir . '/' . $file['filename']))
+			{
+				// OK - what is the current version?
+				$fp = fopen($boarddir . '/' . $file['filename'], 'rb');
+				$header = fread($fp, 768);
+				fclose($fp);
+
+				// Find the version.
+				if (preg_match('~(?://|/\*)\s*Version:\s+(.+?);\s*' . preg_quote($name, '~') . '(?:[\s]{2}|\*/)~i', $header, $match) == 1)
+				{
+					$context_data['cur_version'] = $match[1];
+
+					// How does this compare?
+					if ($context_data['cur_version'] == $context_data['version'])
+						$context_data['version_compare'] = 'same';
+					elseif ($context_data['cur_version'] > $context_data['version'])
+						$context_data['version_compare'] = 'older';
+
+					// Don't recommend copying if the version is the same.
+					if ($context_data['version_compare'] != 'newer')
+						$context_data['default_copy'] = false;
+				}
+			}
+
+			// Add the context data to the main set.
+			$context['files']['lang'][] = $context_data;
+		}
+		else
+		{
+			// If we think it's a theme thing, work out what the theme is.
+			if (substr($dirname, 0, 6) == 'Themes' && preg_match('~Themes[\\/]([^\\/]+)[\\/]~', $dirname, $match))
+				$theme_name = $match[1];
+			else
+				$theme_name = 'misc';
+
+			// Assume it's an image, could be an acceptance note etc but rare.
+			$context['files']['images'][$theme_name][] = $context_data;
+		}
+
+		// Collect together all non-writable areas.
+		if (!$context_data['writable'])
+			$context['make_writable'][] = $context_data['destination'];
+	}
+
+	// So, I'm a perfectionist - let's get the theme names.
+	$theme_indexes = array();
+	foreach ($context['files']['images'] as $k => $dummy)
+		$indexes[] = $k;
+
+	$context['theme_names'] = array();
+	if (!empty($indexes))
+	{
+		$value_data = array(
+			'query' => array(),
+			'params' => array(),
+		);
+
+		foreach ($indexes as $k => $index)
+		{
+			$value_data['query'][] = 'value LIKE {string:value_' . $k . '}';
+			$value_data['params']['value_' . $k] = '%' . $index;
+		}
+
+		$request = $smcFunc['db_query']('', '
+			SELECT id_theme, value
+			FROM {db_prefix}themes
+			WHERE id_member = {int:no_member}
+				AND variable = {string:theme_dir}
+				AND (' . implode(' OR ', $value_data['query']) . ')',
+			array_merge($value_data['params'], array(
+				'no_member' => 0,
+				'theme_dir' => 'theme_dir',
+				'index_compare_explode' => 'value LIKE \'%' . implode('\' OR value LIKE \'%', $indexes) . '\'',
+			))
+		);
+		$themes = array();
+		while ($row = $smcFunc['db_fetch_assoc']($request))
+		{
+			// Find the right one.
+			foreach ($indexes as $index)
+				if (strpos($row['value'], $index) !== false)
+					$themes[$row['id_theme']] = $index;
+		}
+		$smcFunc['db_free_result']($request);
+
+		if (!empty($themes))
+		{
+			// Now we have the id_theme we can get the pretty description.
+			$request = $smcFunc['db_query']('', '
+				SELECT id_theme, value
+				FROM {db_prefix}themes
+				WHERE id_member = {int:no_member}
+					AND variable = {string:name}
+					AND id_theme IN ({array_int:theme_list})',
+				array(
+					'theme_list' => array_keys($themes),
+					'no_member' => 0,
+					'name' => 'name',
+				)
+			);
+			while ($row = $smcFunc['db_fetch_assoc']($request))
+			{
+				// Now we have it...
+				$context['theme_names'][$themes[$row['id_theme']]] = $row['value'];
+			}
+			$smcFunc['db_free_result']($request);
+		}
+	}
+
+	// Before we go to far can we make anything writable, eh, eh?
+	if (!empty($context['make_writable']))
+	{
+		// What is left to be made writable?
+		$file_status = create_chmod_control($context['make_writable']);
+		$context['still_not_writable'] = $file_status['files']['notwritable'];
+
+		// Mark those which are now writable as such.
+		foreach ($context['files'] as $type => $data)
+		{
+			if ($type == 'lang')
+			{
+				foreach ($data as $k => $file)
+					if (!$file['writable'] && !in_array($file['destination'], $context['still_not_writable']))
+						$context['files'][$type][$k]['writable'] = true;
+			}
+			else
+			{
+				foreach ($data as $theme => $files)
+					foreach ($files as $k => $file)
+						if (!$file['writable'] && !in_array($file['destination'], $context['still_not_writable']))
+							$context['files'][$type][$theme][$k]['writable'] = true;
+			}
+		}
+
+		// Are we going to need more language stuff?
+		if (!empty($context['still_not_writable']))
+			loadLanguage('Packages');
+	}
+
+	// This is the list for the main files.
+	$listOptions = array(
+		'id' => 'lang_main_files_list',
+		'title' => $txt['languages_download_main_files'],
+		'get_items' => array(
+			'function' => create_function('', '
+				global $context;
+				return $context[\'files\'][\'lang\'];
+			'),
+		),
+		'columns' => array(
+			'name' => array(
+				'header' => array(
+					'value' => $txt['languages_download_filename'],
+				),
+				'data' => array(
+					'function' => create_function('$rowData', '
+						global $context, $txt;
+
+						return \'<strong>\' . $rowData[\'name\'] . \'</strong><br /><span class="smalltext">\' . $txt[\'languages_download_dest\'] . \': \' . $rowData[\'destination\'] . \'</span>\' . ($rowData[\'version_compare\'] == \'older\' ? \'<br />\' . $txt[\'languages_download_older\'] : \'\');
+					'),
+				),
+			),
+			'writable' => array(
+				'header' => array(
+					'value' => $txt['languages_download_writable'],
+				),
+				'data' => array(
+					'function' => create_function('$rowData', '
+						global $txt;
+
+						return \'<span style="color: \' . ($rowData[\'writable\'] ? \'green\' : \'red\') . \';">\' . ($rowData[\'writable\'] ? $txt[\'yes\'] : $txt[\'no\']) . \'</span>\';
+					'),
+					'style' => 'text-align: center',
+				),
+			),
+			'version' => array(
+				'header' => array(
+					'value' => $txt['languages_download_version'],
+				),
+				'data' => array(
+					'function' => create_function('$rowData', '
+						global $txt;
+
+						return \'<span style="color: \' . ($rowData[\'version_compare\'] == \'older\' ? \'red\' : ($rowData[\'version_compare\'] == \'same\' ? \'orange\' : \'green\')) . \';">\' . $rowData[\'version\'] . \'</span>\';
+					'),
+				),
+			),
+			'exists' => array(
+				'header' => array(
+					'value' => $txt['languages_download_exists'],
+				),
+				'data' => array(
+					'function' => create_function('$rowData', '
+						global $txt;
+
+						return $rowData[\'exists\'] ? ($rowData[\'exists\'] == \'same\' ? $txt[\'languages_download_exists_same\'] : $txt[\'languages_download_exists_different\']) : $txt[\'no\'];
+					'),
+				),
+			),
+			'copy' => array(
+				'header' => array(
+					'value' => $txt['languages_download_copy'],
+				),
+				'data' => array(
+					'function' => create_function('$rowData', '
+						return \'<input type="checkbox" name="copy_file[]" value="\' . $rowData[\'generaldest\'] . \'" \' . ($rowData[\'default_copy\'] ? \'checked="checked"\' : \'\') . \' class="input_check" />\';
+					'),
+					'style' => 'text-align: center; width: 4%;',
+				),
+			),
+		),
+	);
+
+	// Kill the cache, as it is now invalid..
+	if (!empty($modSettings['cache_enable']))
+	{
+		cache_put_data('known_languages', null, !empty($modSettings['cache_enable']) && $modSettings['cache_enable'] < 1 ? 86400 : 3600);
+		cache_put_data('known_languages_all', null, !empty($modSettings['cache_enable']) && $modSettings['cache_enable'] < 1 ? 86400 : 3600);
+	}
+
+	require_once($sourcedir . '/Subs-List.php');
+	createList($listOptions);
+
+	$context['default_list'] = 'lang_main_files_list';
+}
+
+/**
+ * This lists all the current languages and allows editing of them.
+ */
+function ModifyLanguages()
+{
+	global $txt, $context, $scripturl;
+	global $user_info, $smcFunc, $sourcedir, $language, $boarddir, $forum_version;
+
+	// Setting a new default?
+	if (!empty($_POST['set_default']) && !empty($_POST['def_language']))
+	{
+		checkSession();
+
+		if ($_POST['def_language'] != $language)
+		{
+			require_once($sourcedir . '/Subs-Admin.php');
+			updateSettingsFile(array('language' => '\'' . $_POST['def_language'] . '\''));
+			$language = $_POST['def_language'];
+		}
+	}
+
+	$listOptions = array(
+		'id' => 'language_list',
+		'items_per_page' => 20,
+		'base_href' => $scripturl . '?action=admin;area=languages',
+		'title' => $txt['edit_languages'],
+		'get_items' => array(
+			'function' => 'list_getLanguages',
+		),
+		'get_count' => array(
+			'function' => 'list_getNumLanguages',
+		),
+		'columns' => array(
+			'default' => array(
+				'header' => array(
+					'value' => $txt['languages_default'],
+				),
+				'data' => array(
+					'function' => create_function('$rowData', '
+						return \'<input type="radio" name="def_language" value="\' . $rowData[\'id\'] . \'" \' . ($rowData[\'default\'] ? \'checked="checked"\' : \'\') . \' onclick="highlightSelected(\\\'list_language_list_\' . $rowData[\'id\'] . \'\\\');" class="input_radio" />\';
+					'),
+					'style' => 'text-align: center; width: 8%;',
+				),
+			),
+			'name' => array(
+				'header' => array(
+					'value' => $txt['languages_lang_name'],
+				),
+				'data' => array(
+					'function' => create_function('$rowData', '
+						global $scripturl, $context;
+
+						return sprintf(\'<a href="%1$s?action=admin;area=languages;sa=editlang;lid=%2$s">%3$s</a>\', $scripturl, $rowData[\'id\'], $rowData[\'name\']);
+					'),
+				),
+			),
+			'character_set' => array(
+				'header' => array(
+					'value' => $txt['languages_character_set'],
+				),
+				'data' => array(
+					'db_htmlsafe' => 'char_set',
+				),
+			),
+			'count' => array(
+				'header' => array(
+					'value' => $txt['languages_users'],
+				),
+				'data' => array(
+					'db_htmlsafe' => 'count',
+					'style' => 'text-align: center',
+				),
+			),
+			'locale' => array(
+				'header' => array(
+					'value' => $txt['languages_locale'],
+				),
+				'data' => array(
+					'db_htmlsafe' => 'locale',
+				),
+			),
+		),
+		'form' => array(
+			'href' => $scripturl . '?action=admin;area=languages',
+		),
+		'additional_rows' => array(
+			array(
+				'position' => 'below_table_data',
+				'value' => '<input type="hidden" name="' . $context['session_var'] . '" value="' . $context['session_id'] . '" /><input type="submit" name="set_default" value="' . $txt['save'] . '"' . (is_writable($boarddir . '/Settings.php') ? '' : ' disabled="disabled"') . ' class="button_submit" />',
+				'style' => 'text-align: right;',
+			),
+		),
+		// For highlighting the default.
+		'javascript' => '
+					var prevClass = "";
+					var prevDiv = "";
+					function highlightSelected(box)
+					{
+						if (prevClass != "")
+							prevDiv.className = prevClass;
+
+						prevDiv = document.getElementById(box);
+						prevClass = prevDiv.className;
+
+						prevDiv.className = "highlight2";
+					}
+					highlightSelected("list_language_list_' . ($language == '' ? 'english' : $language). '");
+		',
+	);
+
+	// Display a warning if we cannot edit the default setting.
+	if (!is_writable($boarddir . '/Settings.php'))
+		$listOptions['additional_rows'][] = array(
+				'position' => 'after_title',
+				'value' => $txt['language_settings_writable'],
+				'class' => 'smalltext alert',
+			);
+
+	require_once($sourcedir . '/Subs-List.php');
+	createList($listOptions);
+
+	$context['sub_template'] = 'show_list';
+	$context['default_list'] = 'language_list';
+}
+
+/**
+ * How many languages?
+ * Callback for the list in ManageLanguageSettings().
+ */
+function list_getNumLanguages()
+{
+	global $settings;
+
+	// Return how many we have.
+	return count(getLanguages(true, false));
+}
+
+/**
+ * Fetch the actual language information.
+ * Callback for $listOptions['get_items']['function'] in ManageLanguageSettings.
+ * Determines which languages are available by looking for the "index.{language}.php" file.
+ * Also figures out how many users are using a particular language.
+ */
+function list_getLanguages()
+{
+	global $settings, $smcFunc, $language, $context, $txt;
+
+	$languages = array();
+	// Keep our old entries.
+	$old_txt = $txt;
+	$backup_actual_theme_dir = $settings['actual_theme_dir'];
+	$backup_base_theme_dir = !empty($settings['base_theme_dir']) ? $settings['base_theme_dir'] : '';
+
+	// Override these for now.
+	$settings['actual_theme_dir'] = $settings['base_theme_dir'] = $settings['default_theme_dir'];
+	getLanguages(true, false);
+
+	// Put them back.
+	$settings['actual_theme_dir'] = $backup_actual_theme_dir;
+	if (!empty($backup_base_theme_dir))
+		$settings['base_theme_dir'] = $backup_base_theme_dir;
+	else
+		unset($settings['base_theme_dir']);
+
+	// Get the language files and data...
+	foreach ($context['languages'] as $lang)
+	{
+		// Load the file to get the character set.
+		require($settings['default_theme_dir'] . '/languages/index.' . $lang['filename'] . '.php');
+
+		$languages[$lang['filename']] = array(
+			'id' => $lang['filename'],
+			'count' => 0,
+			'char_set' => $txt['lang_character_set'],
+			'default' => $language == $lang['filename'] || ($language == '' && $lang['filename'] == 'english'),
+			'locale' => $txt['lang_locale'],
+			'name' => $smcFunc['ucwords'](strtr($lang['filename'], array('_' => ' ', '-utf8' => ''))),
+		);
+	}
+
+	// Work out how many people are using each language.
+	$request = $smcFunc['db_query']('', '
+		SELECT lngfile, COUNT(*) AS num_users
+		FROM {db_prefix}members
+		GROUP BY lngfile',
+		array(
+		)
+	);
+	while ($row = $smcFunc['db_fetch_assoc']($request))
+	{
+		// Default?
+		if (empty($row['lngfile']) || !isset($languages[$row['lngfile']]))
+			$row['lngfile'] = $language;
+
+		if (!isset($languages[$row['lngfile']]) && isset($languages['english']))
+			$languages['english']['count'] += $row['num_users'];
+		elseif (isset($languages[$row['lngfile']]))
+			$languages[$row['lngfile']]['count'] += $row['num_users'];
+	}
+	$smcFunc['db_free_result']($request);
+
+	// Restore the current users language.
+	$txt = $old_txt;
+
+	// Return how many we have.
+	return $languages;
+}
+
+/**
+ * Edit language related settings.
+ *
+ * @param bool $return_config = false
+ */
+function ModifyLanguageSettings($return_config = false)
+{
+	global $scripturl, $context, $txt, $boarddir, $settings, $smcFunc, $sourcedir;
+
+	// We'll want to save them someday.
+	require_once $sourcedir . '/ManageServer.php';
+
+	// Warn the user if the backup of Settings.php failed.
+	$settings_not_writable = !is_writable($boarddir . '/Settings.php');
+	$settings_backup_fail = !@is_writable($boarddir . '/Settings_bak.php') || !@copy($boarddir . '/Settings.php', $boarddir . '/Settings_bak.php');
+
+	/* If you're writing a mod, it's a bad idea to add things here....
+	For each option:
+		variable name, description, type (constant), size/possible values, helptext.
+	OR	an empty string for a horizontal rule.
+	OR	a string for a titled section. */
+	$config_vars = array(
+		'language' => array('language', $txt['default_language'], 'file', 'select', array(), null, 'disabled' => $settings_not_writable),
+		array('userLanguage', $txt['userLanguage'], 'db', 'check', null, 'userLanguage'),
+	);
+
+	if ($return_config)
+		return $config_vars;
+
+	// Get our languages. No cache and use utf8.
+	getLanguages(false, false);
+	foreach ($context['languages'] as $lang)
+		$config_vars['language'][4][$lang['filename']] = array($lang['filename'], strtr($lang['name'], array('-utf8' => ' (UTF-8)')));
+
+	// Saving settings?
+	if (isset($_REQUEST['save']))
+	{
+		checkSession();
+		saveSettings($config_vars);
+		redirectexit('action=admin;area=languages;sa=settings');
+	}
+
+	// Setup the template stuff.
+	$context['post_url'] = $scripturl . '?action=admin;area=languages;sa=settings;save';
+	$context['settings_title'] = $txt['language_settings'];
+	$context['save_disabled'] = $settings_not_writable;
+
+	if ($settings_not_writable)
+		$context['settings_message'] = '<div class="centertext"><strong>' . $txt['settings_not_writable'] . '</strong></div><br />';
+	elseif ($settings_backup_fail)
+		$context['settings_message'] = '<div class="centertext"><strong>' . $txt['admin_backup_fail'] . '</strong></div><br />';
+
+	// Fill the config array.
+	prepareServerSettingsContext($config_vars);
+}
+
+/**
+ * Edit a particular set of language entries.
+ *
+ */
+function ModifyLanguage()
+{
+	global $settings, $context, $smcFunc, $txt, $modSettings, $boarddir, $sourcedir, $language;
+
+	loadLanguage('ManageSettings');
+
+	// Select the languages tab.
+	$context['menu_data_' . $context['admin_menu_id']]['current_subsection'] = 'edit';
+	$context['page_title'] = $txt['edit_languages'];
+	$context['sub_template'] = 'modify_language_entries';
+
+	$context['lang_id'] = $_GET['lid'];
+	list($theme_id, $file_id) = empty($_REQUEST['tfid']) || strpos($_REQUEST['tfid'], '+') === false ? array(1, '') : explode('+', $_REQUEST['tfid']);
+
+	// Clean the ID - just in case.
+	preg_match('~([A-Za-z0-9_-]+)~', $context['lang_id'], $matches);
+	$context['lang_id'] = $matches[1];
+
+	// Get all the theme data.
+	$request = $smcFunc['db_query']('', '
+		SELECT id_theme, variable, value
+		FROM {db_prefix}themes
+		WHERE id_theme != {int:default_theme}
+			AND id_member = {int:no_member}
+			AND variable IN ({string:name}, {string:theme_dir})',
+		array(
+			'default_theme' => 1,
+			'no_member' => 0,
+			'name' => 'name',
+			'theme_dir' => 'theme_dir',
+		)
+	);
+	$themes = array(
+		1 => array(
+			'name' => $txt['dvc_default'],
+			'theme_dir' => $settings['default_theme_dir'],
+		),
+	);
+	while ($row = $smcFunc['db_fetch_assoc']($request))
+		$themes[$row['id_theme']][$row['variable']] = $row['value'];
+	$smcFunc['db_free_result']($request);
+
+	// This will be where we look
+	$lang_dirs = array();
+	// Check we have themes with a path and a name - just in case - and add the path.
+	foreach ($themes as $id => $data)
+	{
+		if (count($data) != 2)
+			unset($themes[$id]);
+		elseif (is_dir($data['theme_dir'] . '/languages'))
+			$lang_dirs[$id] = $data['theme_dir'] . '/languages';
+
+		// How about image directories?
+		if (is_dir($data['theme_dir'] . '/images/' . $context['lang_id']))
+			$images_dirs[$id] = $data['theme_dir'] . '/images/' . $context['lang_id'];
+	}
+
+	$current_file = $file_id ? $lang_dirs[$theme_id] . '/' . $file_id . '.' . $context['lang_id'] . '.php' : '';
+
+	// Now for every theme get all the files and stick them in context!
+	$context['possible_files'] = array();
+	foreach ($lang_dirs as $theme => $theme_dir)
+	{
+		// Open it up.
+		$dir = dir($theme_dir);
+		while ($entry = $dir->read())
+		{
+			// We're only after the files for this language.
+			if (preg_match('~^([A-Za-z]+)\.' . $context['lang_id'] . '\.php$~', $entry, $matches) == 0)
+				continue;
+
+			//!!! Temp!
+			if ($matches[1] == 'EmailTemplates')
+				continue;
+
+			if (!isset($context['possible_files'][$theme]))
+				$context['possible_files'][$theme] = array(
+					'id' => $theme,
+					'name' => $themes[$theme]['name'],
+					'files' => array(),
+				);
+
+			$context['possible_files'][$theme]['files'][] = array(
+				'id' => $matches[1],
+				'name' => isset($txt['lang_file_desc_' . $matches[1]]) ? $txt['lang_file_desc_' . $matches[1]] : $matches[1],
+				'selected' => $theme_id == $theme && $file_id == $matches[1],
+			);
+		}
+		$dir->close();
+	}
+
+	// We no longer wish to speak this language.
+	if (!empty($_POST['delete_main']) && $context['lang_id'] != 'english')
+	{
+		checkSession();
+
+		// !!! Todo: FTP Controls?
+		require_once($sourcedir . '/Subs-Package.php');
+
+		// First, Make a backup?
+		if (!empty($modSettings['package_make_backups']) && (!isset($_SESSION['last_backup_for']) || $_SESSION['last_backup_for'] != $context['lang_id'] . '$$$'))
+		{
+			$_SESSION['last_backup_for'] = $context['lang_id'] . '$$$';
+			package_create_backup('backup_lang_' . $context['lang_id']);
+		}
+
+		// Second, loop through the array to remove the files.
+		foreach ($lang_dirs as $curPath)
+		{
+			foreach ($context['possible_files'][1]['files'] as $lang)
+				if (file_exists($curPath . '/' . $lang['id'] . '.' . $context['lang_id'] . '.php'))
+					unlink($curPath . '/' . $lang['id'] . '.' . $context['lang_id'] . '.php');
+
+			// Check for the email template.
+			if (file_exists($curPath . '/EmailTemplates.' . $context['lang_id'] . '.php'))
+				unlink($curPath . '/EmailTemplates.' . $context['lang_id'] . '.php');
+		}
+
+		// Third, the agreement file.
+		if (file_exists($boarddir . '/agreement.' . $context['lang_id'] . '.txt'))
+			unlink($boarddir . '/agreement.' . $context['lang_id'] . '.txt');
+
+		// Fourth, a related images folder?
+		foreach ($images_dirs as $curPath)
+			if (is_dir($curPath))
+				deltree($curPath);
+
+		// Members can no longer use this language.
+		$smcFunc['db_query']('', '
+			UPDATE {db_prefix}members
+			SET lngfile = {string:empty_string}
+			WHERE lngfile = {string:current_language}',
+			array(
+				'empty_string' => '',
+				'current_language' => $context['lang_id'],
+			)
+		);
+
+		// Fifth, update getLanguages() cache.
+		if (!empty($modSettings['cache_enable']))
+		{
+			cache_put_data('known_languages', null, !empty($modSettings['cache_enable']) && $modSettings['cache_enable'] < 1 ? 86400 : 3600);
+			cache_put_data('known_languages_all', null, !empty($modSettings['cache_enable']) && $modSettings['cache_enable'] < 1 ? 86400 : 3600);
+		}
+
+		// Sixth, if we deleted the default language, set us back to english?
+		if ($context['lang_id'] == $language)
+		{
+			require_once($sourcedir . '/Subs-Admin.php');
+			$language = 'english';
+			updateSettingsFile(array('language' => '\'' . $language . '\''));
+		}
+
+		// Seventh, get out of here.
+		redirectexit('action=admin;area=languages;sa=edit;' . $context['session_var'] . '=' . $context['session_id']);
+	}
+
+	// Saving primary settings?
+	$madeSave = false;
+	if (!empty($_POST['save_main']) && !$current_file)
+	{
+		checkSession();
+
+		// Read in the current file.
+		$current_data = implode('', file($settings['default_theme_dir'] . '/languages/index.' . $context['lang_id'] . '.php'));
+		// These are the replacements. old => new
+		$replace_array = array(
+			'~\$txt\[\'lang_character_set\'\]\s=\s(\'|")[^\r\n]+~' => '$txt[\'lang_character_set\'] = \'' . addslashes($_POST['character_set']) . '\';',
+			'~\$txt\[\'lang_locale\'\]\s=\s(\'|")[^\r\n]+~' => '$txt[\'lang_locale\'] = \'' . addslashes($_POST['locale']) . '\';',
+			'~\$txt\[\'lang_dictionary\'\]\s=\s(\'|")[^\r\n]+~' => '$txt[\'lang_dictionary\'] = \'' . addslashes($_POST['dictionary']) . '\';',
+			'~\$txt\[\'lang_spelling\'\]\s=\s(\'|")[^\r\n]+~' => '$txt[\'lang_spelling\'] = \'' . addslashes($_POST['spelling']) . '\';',
+			'~\$txt\[\'lang_rtl\'\]\s=\s[A-Za-z0-9]+;~' => '$txt[\'lang_rtl\'] = ' . (!empty($_POST['rtl']) ? 'true' : 'false') . ';',
+		);
+		$current_data = preg_replace(array_keys($replace_array), array_values($replace_array), $current_data);
+		$fp = fopen($settings['default_theme_dir'] . '/languages/index.' . $context['lang_id'] . '.php', 'w+');
+		fwrite($fp, $current_data);
+		fclose($fp);
+
+		$madeSave = true;
+	}
+
+	// Quickly load index language entries.
+	$old_txt = $txt;
+	require($settings['default_theme_dir'] . '/languages/index.' . $context['lang_id'] . '.php');
+	$context['lang_file_not_writable_message'] = is_writable($settings['default_theme_dir'] . '/languages/index.' . $context['lang_id'] . '.php') ? '' : sprintf($txt['lang_file_not_writable'], $settings['default_theme_dir'] . '/languages/index.' . $context['lang_id'] . '.php');
+	// Setup the primary settings context.
+	$context['primary_settings'] = array(
+		'name' => $smcFunc['ucwords'](strtr($context['lang_id'], array('_' => ' ', '-utf8' => ''))),
+		'character_set' => $txt['lang_character_set'],
+		'locale' => $txt['lang_locale'],
+		'dictionary' => $txt['lang_dictionary'],
+		'spelling' => $txt['lang_spelling'],
+		'rtl' => $txt['lang_rtl'],
+	);
+
+	// Restore normal service.
+	$txt = $old_txt;
+
+	// Are we saving?
+	$save_strings = array();
+	if (isset($_POST['save_entries']) && !empty($_POST['entry']))
+	{
+		checkSession();
+
+		// Clean each entry!
+		foreach ($_POST['entry'] as $k => $v)
+		{
+			// Only try to save if it's changed!
+			if ($_POST['entry'][$k] != $_POST['comp'][$k])
+				$save_strings[$k] = cleanLangString($v, false);
+		}
+	}
+
+	// If we are editing a file work away at that.
+	if ($current_file)
+	{
+		$context['entries_not_writable_message'] = is_writable($current_file) ? '' : sprintf($txt['lang_entries_not_writable'], $current_file);
+
+		$entries = array();
+		// We can't just require it I'm afraid - otherwise we pass in all kinds of variables!
+		$multiline_cache = '';
+		foreach (file($current_file) as $line)
+		{
+			// Got a new entry?
+			if ($line[0] == '$' && !empty($multiline_cache))
+			{
+				preg_match('~\$(helptxt|txt)\[\'(.+)\'\]\s=\s(.+);~', strtr($multiline_cache, array("\n" => '', "\t" => '')), $matches);
+				if (!empty($matches[3]))
+				{
+					$entries[$matches[2]] = array(
+						'type' => $matches[1],
+						'full' => $matches[0],
+						'entry' => $matches[3],
+					);
+					$multiline_cache = '';
+				}
+			}
+			$multiline_cache .= $line . "\n";
+		}
+		// Last entry to add?
+		if ($multiline_cache)
+		{
+			preg_match('~\$(helptxt|txt)\[\'(.+)\'\]\s=\s(.+);~', strtr($multiline_cache, array("\n" => '', "\t" => '')), $matches);
+			if (!empty($matches[3]))
+				$entries[$matches[2]] = array(
+					'type' => $matches[1],
+					'full' => $matches[0],
+					'entry' => $matches[3],
+				);
+		}
+
+		// These are the entries we can definitely save.
+		$final_saves = array();
+
+		$context['file_entries'] = array();
+		foreach ($entries as $entryKey => $entryValue)
+		{
+			// Ignore some things we set separately.
+			$ignore_files = array('lang_character_set', 'lang_locale', 'lang_dictionary', 'lang_spelling', 'lang_rtl');
+			if (in_array($entryKey, $ignore_files))
+				continue;
+
+			// These are arrays that need breaking out.
+			$arrays = array('days', 'days_short', 'months', 'months_titles', 'months_short');
+			if (in_array($entryKey, $arrays))
+			{
+				// Get off the first bits.
+				$entryValue['entry'] = substr($entryValue['entry'], strpos($entryValue['entry'], '(') + 1, strrpos($entryValue['entry'], ')') - strpos($entryValue['entry'], '('));
+				$entryValue['entry'] = explode(',', strtr($entryValue['entry'], array(' ' => '')));
+
+				// Now create an entry for each item.
+				$cur_index = 0;
+				$save_cache = array(
+					'enabled' => false,
+					'entries' => array(),
+				);
+				foreach ($entryValue['entry'] as $id => $subValue)
+				{
+					// Is this a new index?
+					if (preg_match('~^(\d+)~', $subValue, $matches))
+					{
+						$cur_index = $matches[1];
+						$subValue = substr($subValue, strpos($subValue, '\''));
+					}
+
+					// Clean up some bits.
+					$subValue = strtr($subValue, array('"' => '', '\'' => '', ')' => ''));
+
+					// Can we save?
+					if (isset($save_strings[$entryKey . '-+- ' . $cur_index]))
+					{
+						$save_cache['entries'][$cur_index] = strtr($save_strings[$entryKey . '-+- ' . $cur_index], array('\'' => ''));
+						$save_cache['enabled'] = true;
+					}
+					else
+						$save_cache['entries'][$cur_index] = $subValue;
+
+					$context['file_entries'][] = array(
+						'key' => $entryKey . '-+- ' . $cur_index,
+						'value' => $subValue,
+						'rows' => 1,
+					);
+					$cur_index++;
+				}
+
+				// Do we need to save?
+				if ($save_cache['enabled'])
+				{
+					// Format the string, checking the indexes first.
+					$items = array();
+					$cur_index = 0;
+					foreach ($save_cache['entries'] as $k2 => $v2)
+					{
+						// Manually show the custom index.
+						if ($k2 != $cur_index)
+						{
+							$items[] = $k2 . ' => \'' . $v2 . '\'';
+							$cur_index = $k2;
+						}
+						else
+							$items[] = '\'' . $v2 . '\'';
+
+						$cur_index++;
+					}
+					// Now create the string!
+					$final_saves[$entryKey] = array(
+						'find' => $entryValue['full'],
+						'replace' => '$' . $entryValue['type'] . '[\'' . $entryKey . '\'] = array(' . implode(', ', $items) . ');',
+					);
+				}
+			}
+			else
+			{
+				// Saving?
+				if (isset($save_strings[$entryKey]) && $save_strings[$entryKey] != $entryValue['entry'])
+				{
+					// !!! Fix this properly.
+					if ($save_strings[$entryKey] == '')
+						$save_strings[$entryKey] = '\'\'';
+
+					// Set the new value.
+					$entryValue['entry'] = $save_strings[$entryKey];
+					// And we know what to save now!
+					$final_saves[$entryKey] = array(
+						'find' => $entryValue['full'],
+						'replace' => '$' . $entryValue['type'] . '[\'' . $entryKey . '\'] = ' . $save_strings[$entryKey] . ';',
+					);
+				}
+
+				$editing_string = cleanLangString($entryValue['entry'], true);
+				$context['file_entries'][] = array(
+					'key' => $entryKey,
+					'value' => $editing_string,
+					'rows' => (int) (strlen($editing_string) / 38) + substr_count($editing_string, "\n") + 1,
+				);
+			}
+		}
+
+		// Any saves to make?
+		if (!empty($final_saves))
+		{
+			checkSession();
+
+			$file_contents = implode('', file($current_file));
+			foreach ($final_saves as $save)
+				$file_contents = strtr($file_contents, array($save['find'] => $save['replace']));
+
+			// Save the actual changes.
+			$fp = fopen($current_file, 'w+');
+			fwrite($fp, $file_contents);
+			fclose($fp);
+
+			$madeSave = true;
+		}
+
+		// Another restore.
+		$txt = $old_txt;
+	}
+
+	// If we saved, redirect.
+	if ($madeSave)
+		redirectexit('action=admin;area=languages;sa=editlang;lid=' . $context['lang_id']);
+}
+
+/**
+ * This function cleans language entries to/from display.
+ * @todo This function could be two functions?
+ *
+ * @param $string
+ * @param $to_display
+ */
+function cleanLangString($string, $to_display = true)
+{
+	global $smcFunc;
+
+	// If going to display we make sure it doesn't have any HTML in it - etc.
+	$new_string = '';
+	if ($to_display)
+	{
+		// Are we in a string (0 = no, 1 = single quote, 2 = parsed)
+		$in_string = 0;
+		$is_escape = false;
+		for ($i = 0; $i < strlen($string); $i++)
+		{
+			// Handle ecapes first.
+			if ($string{$i} == '\\')
+			{
+				// Toggle the escape.
+				$is_escape = !$is_escape;
+				// If we're now escaped don't add this string.
+				if ($is_escape)
+					continue;
+			}
+			// Special case - parsed string with line break etc?
+			elseif (($string{$i} == 'n' || $string{$i} == 't') && $in_string == 2 && $is_escape)
+			{
+				// Put the escape back...
+				$new_string .= $string{$i} == 'n' ? "\n" : "\t";
+				$is_escape = false;
+				continue;
+			}
+			// Have we got a single quote?
+			elseif ($string{$i} == '\'')
+			{
+				// Already in a parsed string, or escaped in a linear string, means we print it - otherwise something special.
+				if ($in_string != 2 && ($in_string != 1 || !$is_escape))
+				{
+					// Is it the end of a single quote string?
+					if ($in_string == 1)
+						$in_string = 0;
+					// Otherwise it's the start!
+					else
+						$in_string = 1;
+
+					// Don't actually include this character!
+					continue;
+				}
+			}
+			// Otherwise a double quote?
+			elseif ($string{$i} == '"')
+			{
+				// Already in a single quote string, or escaped in a parsed string, means we print it - otherwise something special.
+				if ($in_string != 1 && ($in_string != 2 || !$is_escape))
+				{
+					// Is it the end of a double quote string?
+					if ($in_string == 2)
+						$in_string = 0;
+					// Otherwise it's the start!
+					else
+						$in_string = 2;
+
+					// Don't actually include this character!
+					continue;
+				}
+			}
+			// A join/space outside of a string is simply removed.
+			elseif ($in_string == 0 && (empty($string{$i}) || $string{$i} == '.'))
+				continue;
+			// Start of a variable?
+			elseif ($in_string == 0 && $string{$i} == '$')
+			{
+				// Find the whole of it!
+				preg_match('~([\$A-Za-z0-9\'\[\]_-]+)~', substr($string, $i), $matches);
+				if (!empty($matches[1]))
+				{
+					// Come up with some pseudo thing to indicate this is a var.
+					//!!! Do better than this, please!
+					$new_string .= '{%' . $matches[1] . '%}';
+
+					// We're not going to reparse this.
+					$i += strlen($matches[1]) - 1;
+				}
+
+				continue;
+			}
+			// Right, if we're outside of a string we have DANGER, DANGER!
+			elseif ($in_string == 0)
+			{
+				continue;
+			}
+
+			// Actually add the character to the string!
+			$new_string .= $string{$i};
+			// If anything was escaped it ain't any longer!
+			$is_escape = false;
+		}
+
+		// Unhtml then rehtml the whole thing!
+		$new_string = htmlspecialchars(un_htmlspecialchars($new_string));
+	}
+	else
+	{
+		// Keep track of what we're doing...
+		$in_string = 0;
+		// This is for deciding whether to HTML a quote.
+		$in_html = false;
+		for ($i = 0; $i < strlen($string); $i++)
+		{
+			// Handle line breaks!
+			if ($string{$i} == "\n" || $string{$i} == "\t")
+			{
+				// Are we in a string? Is it the right type?
+				if ($in_string == 1)
+				{
+					// Change type!
+					$new_string .= '\' . "\\' . ($string{$i} == "\n" ? 'n' : 't');
+					$in_string = 2;
+				}
+				elseif ($in_string == 2)
+					$new_string .= '\\' . ($string{$i} == "\n" ? 'n' : 't');
+				// Otherwise start one off - joining if required.
+				else
+					$new_string .= ($new_string ? ' . ' : '') . '"\\' . ($string{$i} == "\n" ? 'n' : 't');
+
+				continue;
+			}
+			// We don't do parsed strings apart from for breaks.
+			elseif ($in_string == 2)
+			{
+				$in_string = 0;
+				$new_string .= '"';
+			}
+
+			// Not in a string yet?
+			if ($in_string != 1)
+			{
+				$in_string = 1;
+				$new_string .= ($new_string ? ' . ' : '') . '\'';
+			}
+
+			// Is this a variable?
+			if ($string{$i} == '{' && $string{$i + 1} == '%' && $string{$i + 2} == '$')
+			{
+				// Grab the variable.
+				preg_match('~\{%([\$A-Za-z0-9\'\[\]_-]+)%\}~', substr($string, $i), $matches);
+				if (!empty($matches[1]))
+				{
+					if ($in_string == 1)
+						$new_string .= '\' . ';
+					elseif ($new_string)
+						$new_string .= ' . ';
+
+					$new_string .= $matches[1];
+					$i += strlen($matches[1]) + 3;
+					$in_string = 0;
+				}
+
+				continue;
+			}
+			// Is this a lt sign?
+			elseif ($string{$i} == '<')
+			{
+				// Probably HTML?
+				if ($string{$i + 1} != ' ')
+					$in_html = true;
+				// Assume we need an entity...
+				else
+				{
+					$new_string .= '&lt;';
+					continue;
+				}
+			}
+			// What about gt?
+			elseif ($string{$i} == '>')
+			{
+				// Will it be HTML?
+				if ($in_html)
+					$in_html = false;
+				// Otherwise we need an entity...
+				else
+				{
+					$new_string .= '&gt;';
+					continue;
+				}
+			}
+			// Is it a slash? If so escape it...
+			if ($string{$i} == '\\')
+				$new_string .= '\\';
+			// The infamous double quote?
+			elseif ($string{$i} == '"')
+			{
+				// If we're in HTML we leave it as a quote - otherwise we entity it.
+				if (!$in_html)
+				{
+					$new_string .= '&quot;';
+					continue;
+				}
+			}
+			// A single quote?
+			elseif ($string{$i} == '\'')
+			{
+				// Must be in a string so escape it.
+				$new_string .= '\\';
+			}
+
+			// Finally add the character to the string!
+			$new_string .= $string{$i};
+		}
+
+		// If we ended as a string then close it off.
+		if ($in_string == 1)
+			$new_string .= '\'';
+		elseif ($in_string == 2)
+			$new_string .= '"';
+	}
+
+	return $new_string;
+}
+
+?>

+ 83 - 66
Sources/ManageSettings.php

@@ -1,6 +1,9 @@
 <?php
 
 /**
+ * This file is here to make it easier for installed mods to have
+ * settings and options.
+ *
  * Simple Machines Forum (SMF)
  *
  * @package SMF
@@ -14,60 +17,12 @@
 if (!defined('SMF'))
 	die('Hacking attempt...');
 
-/*	This file is here to make it easier for installed mods to have settings
-	and options.  It uses the following functions:
-
-	void ModifyFeatureSettings()
-		// !!!
-
-	void ModifySecuritySettings()
-		// !!!
-
-	void ModifyModSettings()
-		// !!!
-
-	void ModifyCoreFeatures()
-		// !!!
-
-	void ModifyBasicSettings()
-		// !!!
-
-	void ModifyGeneralSecuritySettings()
-		// !!!
-
-	void ModifyLayoutSettings()
-		// !!!
-
-	void ModifyKarmaSettings()
-		// !!!
-
-	void ModifyModerationSettings()
-		// !!!
-
-	void ModifySpamSettings()
-		// !!!
-
-	void ModifySignatureSettings()
-		// !!!
-
-	void pauseSignatureApplySettings()
-		// !!!
-
-	void ShowCustomProfiles()
-		// !!!
-
-	void EditCustomProfiles()
-		// !!!
-
-	void ModifyPruningSettings()
-		// !!!
-
-	void disablePostModeration()
-		// !!!
-// !!!
-*/
-
-// This just avoids some repetition.
+/**
+ * This just avoids some repetition.
+ *
+ * @param $subActions
+ * @param $defaultAction
+ */
 function loadGeneralSettingParameters($subActions = array(), $defaultAction = '')
 {
 	global $context, $txt, $sourcedir;
@@ -88,7 +43,9 @@ function loadGeneralSettingParameters($subActions = array(), $defaultAction = ''
 	$context['sub_action'] = $_REQUEST['sa'];
 }
 
-// This function passes control through to the relevant tab.
+/**
+ * This function passes control through to the relevant tab.
+ */
 function ModifyFeatureSettings()
 {
 	global $context, $txt, $scripturl, $modSettings, $settings;
@@ -131,7 +88,9 @@ function ModifyFeatureSettings()
 	$subActions[$_REQUEST['sa']]();
 }
 
-// This function passes control through to the relevant security tab.
+/**
+ * This function passes control through to the relevant security tab.
+ */
 function ModifySecuritySettings()
 {
 	global $context, $txt, $scripturl, $modSettings, $settings;
@@ -166,7 +125,9 @@ function ModifySecuritySettings()
 	$subActions[$_REQUEST['sa']]();
 }
 
-// This my friend, is for all the mod authors out there. They're like builders without the ass crack - with the possible exception of... /cut short
+/**
+ * This my friend, is for all the mod authors out there.
+ */
 function ModifyModSettings()
 {
 	global $context, $txt, $scripturl, $modSettings, $settings;
@@ -198,7 +159,11 @@ function ModifyModSettings()
 	$subActions[$_REQUEST['sa']]();
 }
 
-// This is an overall control panel enabling/disabling lots of SMF's key feature components.
+/**
+ * This is an overall control panel enabling/disabling lots of SMF's key feature components.
+ *
+ * @param $return_config
+ */
 function ModifyCoreFeatures($return_config = false)
 {
 	global $txt, $scripturl, $context, $settings, $sc, $modSettings;
@@ -446,6 +411,10 @@ function ModifyCoreFeatures($return_config = false)
 	$context['page_title'] = $txt['core_settings_title'];
 }
 
+/**
+ *
+ * @param $return_config
+ */
 function ModifyBasicSettings($return_config = false)
 {
 	global $txt, $scripturl, $context, $settings, $sc, $modSettings;
@@ -520,7 +489,11 @@ function ModifyBasicSettings($return_config = false)
 	prepareDBSettingContext($config_vars);
 }
 
-// Settings really associated with general security aspects.
+/**
+ * Settings really associated with general security aspects.
+ *
+ * @param $return_config
+ */
 function ModifyGeneralSecuritySettings($return_config = false)
 {
 	global $txt, $scripturl, $context, $settings, $sc, $modSettings;
@@ -566,6 +539,10 @@ function ModifyGeneralSecuritySettings($return_config = false)
 	prepareDBSettingContext($config_vars);
 }
 
+/**
+ *
+ * @param $return_config
+ */
 function ModifyLayoutSettings($return_config = false)
 {
 	global $txt, $scripturl, $context, $settings, $sc;
@@ -610,6 +587,10 @@ function ModifyLayoutSettings($return_config = false)
 	prepareDBSettingContext($config_vars);
 }
 
+/**
+ *
+ * @param $return_config
+ */
 function ModifyKarmaSettings($return_config = false)
 {
 	global $txt, $scripturl, $context, $settings, $sc;
@@ -647,7 +628,11 @@ function ModifyKarmaSettings($return_config = false)
 	prepareDBSettingContext($config_vars);
 }
 
-// Moderation type settings - although there are fewer than we have you believe ;)
+/**
+ * Moderation type settings - although there are fewer than we have you believe ;)
+ *
+ * @param $return_config
+ */
 function ModifyModerationSettings($return_config = false)
 {
 	global $txt, $scripturl, $context, $settings, $sc, $modSettings;
@@ -707,7 +692,10 @@ function ModifyModerationSettings($return_config = false)
 	prepareDBSettingContext($config_vars);
 }
 
-// Let's try keep the spam to a minimum ah Thantos?
+/**
+ * Let's try keep the spam to a minimum ah Thantos?
+ * @param $return_config
+ */
 function ModifySpamSettings($return_config = false)
 {
 	global $txt, $scripturl, $context, $settings, $sc, $modSettings, $smcFunc;
@@ -895,7 +883,11 @@ function ModifySpamSettings($return_config = false)
 	prepareDBSettingContext($config_vars);
 }
 
-// You'll never guess what this function does...
+/**
+ * You'll never guess what this function does...
+ *
+ * @param $return_config
+ */
 function ModifySignatureSettings($return_config = false)
 {
 	global $context, $txt, $modSettings, $sig_start, $smcFunc, $helptxt, $scripturl;
@@ -1227,7 +1219,9 @@ function ModifySignatureSettings($return_config = false)
 	prepareDBSettingContext($config_vars);
 }
 
-// Just pause the signature applying thing.
+/**
+ * Just pause the signature applying thing.
+ */
 function pauseSignatureApplySettings()
 {
 	global $context, $txt, $sig_start;
@@ -1259,7 +1253,9 @@ function pauseSignatureApplySettings()
 	obExit();
 }
 
-// Show all the custom profile fields available to the user.
+/**
+ * Show all the custom profile fields available to the user.
+ */
 function ShowCustomProfiles()
 {
 	global $txt, $scripturl, $context, $settings, $sc, $smcFunc;
@@ -1486,6 +1482,14 @@ function ShowCustomProfiles()
 	createList($listOptions);
 }
 
+/**
+ * Callback for createList().
+ *
+ * @param $start
+ * @param $items_per_page
+ * @param $sort
+ * @param $standardFields
+ */
 function list_getProfileFields($start, $items_per_page, $sort, $standardFields)
 {
 	global $txt, $modSettings, $smcFunc;
@@ -1530,6 +1534,9 @@ function list_getProfileFields($start, $items_per_page, $sort, $standardFields)
 	return $list;
 }
 
+/**
+ * Callback for createList().
+ */
 function list_getProfileFieldSize()
 {
 	global $smcFunc;
@@ -1547,7 +1554,9 @@ function list_getProfileFieldSize()
 	return $numProfileFields;
 }
 
-// Edit some profile fields?
+/**
+ * Edit some profile fields?
+ */
 function EditCustomProfiles()
 {
 	global $txt, $scripturl, $context, $settings, $sc, $smcFunc;
@@ -1939,6 +1948,10 @@ function EditCustomProfiles()
 	}
 }
 
+/**
+ * Allow to edit the settings on the pruning screen.
+ * @param $return_config
+ */
 function ModifyPruningSettings($return_config = false)
 {
 	global $txt, $scripturl, $sourcedir, $context, $settings, $sc, $modSettings;
@@ -2011,7 +2024,11 @@ function ModifyPruningSettings($return_config = false)
 	prepareDBSettingContext($config_vars);
 }
 
-// If you have a general mod setting to add stick it here.
+/**
+ * If you have a general mod setting to add stick it here.
+ *
+ * @param $return_config
+ */
 function ModifyGeneralModSettings($return_config = false)
 {
 	global $txt, $scripturl, $context, $settings, $sc, $modSettings;

+ 67 - 34
Sources/ManageSmileys.php

@@ -1,6 +1,8 @@
 <?php
 
 /**
+ * This file takes care of all administration of smileys.
+ *
  * Simple Machines Forum (SMF)
  *
  * @package SMF
@@ -14,36 +16,9 @@
 if (!defined('SMF'))
 	die('Hacking attempt...');
 
-/* // !!!
-
-	void ManageSmileys()
-		// !!!
-
-	void EditSmileySettings()
-		// !!!
-
-	void EditSmileySets()
-		// !!!
-
-	void AddSmiley()
-		// !!!
-
-	void EditSmileys()
-		// !!!
-
-	void EditSmileyOrder()
-		// !!!
-
-	void InstallSmileySet()
-		// !!!
-
-	void ImportSmileys($smileyPath)
-		// !!!
-
-	void sortSmileyTable()
-		// !!!
-*/
-
+/**
+ * This is the dispatcher of smileys administration.
+ */
 function ManageSmileys()
 {
 	global $context, $txt, $scripturl, $modSettings;
@@ -115,6 +90,11 @@ function ManageSmileys()
 	$subActions[$_REQUEST['sa']]();
 }
 
+/**
+ * Allows to modify smileys settings.
+ *
+ * @param bool $return_config = false
+ */
 function EditSmileySettings($return_config = false)
 {
 	global $modSettings, $context, $settings, $txt, $boarddir, $sourcedir, $scripturl;
@@ -181,6 +161,9 @@ function EditSmileySettings($return_config = false)
 	prepareDBSettingContext($config_vars);
 }
 
+/**
+ * List, add, remove, modify smileys sets.
+ */
 function EditSmileySets()
 {
 	global $modSettings, $context, $settings, $txt, $boarddir;
@@ -452,7 +435,14 @@ function EditSmileySets()
 	createList($listOptions);
 }
 
-// !!! to be moved to Subs-Smileys.
+/**
+ * Callback function for createList().
+ * @todo to be moved to Subs-Smileys?
+ *
+ * @param $start
+ * @param $items_per_page
+ * @param $sort
+ */
 function list_getSmileySets($start, $items_per_page, $sort)
 {
 	global $modSettings;
@@ -492,7 +482,10 @@ function list_getSmileySets($start, $items_per_page, $sort)
 	return $smiley_sets;
 }
 
-// !!! to be moved to Subs-Smileys.
+/**
+ * Callback function for createList().
+ * @todo to be moved to Subs-Smileys?
+ */
 function list_getNumSmileySets()
 {
 	global $modSettings;
@@ -500,6 +493,9 @@ function list_getNumSmileySets()
 	return count(explode(',', $modSettings['smiley_sets_known']));
 }
 
+/**
+ * Add a smiley, that's right.
+ */
 function AddSmiley()
 {
 	global $modSettings, $context, $settings, $txt, $boarddir, $smcFunc;
@@ -745,6 +741,9 @@ function AddSmiley()
 	);
 }
 
+/**
+ * Add, remove, edit smileys.
+ */
 function EditSmileys()
 {
 	global $modSettings, $context, $settings, $txt, $boarddir;
@@ -1156,6 +1155,13 @@ function EditSmileys()
 	}
 }
 
+/**
+ * Callback function for createList().
+ *
+ * @param unknown_type $start
+ * @param unknown_type $items_per_page
+ * @param unknown_type $sort
+ */
 function list_getSmileys($start, $items_per_page, $sort)
 {
 	global $smcFunc;
@@ -1175,6 +1181,9 @@ function list_getSmileys($start, $items_per_page, $sort)
 	return $smileys;
 }
 
+/**
+ * Callback function for createList().
+ */
 function list_getNumSmileys()
 {
 	global $smcFunc;
@@ -1191,6 +1200,9 @@ function list_getNumSmileys()
 	return $numSmileys;
 }
 
+/**
+ * Allows to edit smileys order.
+ */
 function EditSmileyOrder()
 {
 	global $modSettings, $context, $settings, $txt, $boarddir, $smcFunc;
@@ -1349,6 +1361,9 @@ function EditSmileyOrder()
 	cache_put_data('posting_smileys', null, 480);
 }
 
+/**
+ * Install a smiley set.
+ */
 function InstallSmileySet()
 {
 	global $sourcedir, $boarddir, $modSettings, $smcFunc;
@@ -1387,7 +1402,11 @@ function InstallSmileySet()
 	redirectexit('action=admin;area=smileys');
 }
 
-// A function to import new smileys from an existing directory into the database.
+/**
+ * A function to import new smileys from an existing directory into the database.
+ *
+ * @param string $smileyPath
+ */
 function ImportSmileys($smileyPath)
 {
 	global $modSettings, $smcFunc;
@@ -1455,6 +1474,9 @@ function ImportSmileys($smileyPath)
 	}
 }
 
+/**
+ * Allows to edit the message icons.
+ */
 function EditMessageIcons()
 {
 	global $user_info, $modSettings, $context, $settings, $txt;
@@ -1721,6 +1743,13 @@ function EditMessageIcons()
 	}
 }
 
+/**
+ * Callback function for createList().
+ *
+ * @param $start
+ * @param $items_per_page
+ * @param $sort
+ */
 function list_getMessageIcons($start, $items_per_page, $sort)
 {
 	global $smcFunc, $user_info;
@@ -1742,7 +1771,11 @@ function list_getMessageIcons($start, $items_per_page, $sort)
 	return $message_icons;
 }
 
-// This function sorts the smiley table by code length, it is needed as MySQL withdrew support for functions in order by.
+/**
+ * This function sorts the smiley table by code length,
+ * it is needed as MySQL withdrew support for functions in order by.
+ * @todo is this ordering itself needed?
+ */
 function sortSmileyTable()
 {
 	global $smcFunc;

+ 32 - 33
Sources/Memberlist.php

@@ -1,6 +1,9 @@
 <?php
 
 /**
+ * This file contains the functions for displaying and searching in the
+ * members list.
+ *
  * Simple Machines Forum (SMF)
  *
  * @package SMF
@@ -14,37 +17,16 @@
 if (!defined('SMF'))
 	die('Hacking attempt...');
 
-/*	This file contains the functions for displaying and searching in the
-	members list.  It does so with these functions:
-
-	void MemberList()
-		- shows a list of registered members.
-		- if a subaction is not specified, lists all registered members.
-		- allows searching for members with the 'search' sub action.
-		- calls MLAll or MLSearch depending on the sub action.
-		- uses the Memberlist template with the main sub template.
-		- requires the view_mlist permission.
-		- is accessed via ?action=mlist.
-
-	void MLAll()
-		- used to display all members on a page by page basis with sorting.
-		- called from MemberList().
-		- can be passed a sort parameter, to order the display of members.
-		- calls printMemberListRows to retrieve the results of the query.
-
-	void MLSearch()
-		- used to search for members or display search results.
-		- called by MemberList().
-		- if variable 'search' is empty displays search dialog box, using the
-		  search sub template.
-		- calls printMemberListRows to retrieve the results of the query.
-
-	void printMemberListRows(resource request)
-		- retrieves results of the request passed to it
-		- puts results of request into the context for the sub template.
-*/
-
-// Show a listing of the registered members.
+/**
+ * Shows a listing of registered members.
+ * If a subaction is not specified, lists all registered members.
+ * It allows searching for members with the 'search' sub action.
+ * It calls MLAll or MLSearch depending on the sub action.
+ * Requires the view_mlist permission.
+ * Accessed via ?action=mlist.
+ *
+ * @uses Memberlist template, main sub template.
+ */
 function Memberlist()
 {
 	global $scripturl, $txt, $modSettings, $context, $settings, $modSettings;
@@ -154,7 +136,12 @@ function Memberlist()
 		$subActions['all'][1]();
 }
 
-// List all members, page by page.
+/**
+ * List all members, page by page, with sorting.
+ * Called from MemberList().
+ * Can be passed a sort parameter, to order the display of members.
+ * Calls printMemberListRows to retrieve the results of the query.
+ */
 function MLAll()
 {
 	global $txt, $scripturl, $user_info;
@@ -400,7 +387,13 @@ function MLAll()
 	}
 }
 
-// Search for members...
+/**
+ * Search for members, or display search results.
+ * Called by MemberList().
+ * If variable 'search' is empty displays search dialog box, using the
+ * search sub template.
+ * Calls printMemberListRows to retrieve the results of the query.
+ */
 function MLSearch()
 {
 	global $txt, $scripturl, $context, $user_info, $modSettings, $smcFunc;
@@ -551,6 +544,12 @@ function MLSearch()
 	);
 }
 
+/**
+ * Retrieves results of the request passed to it
+ * Puts results of request into the context for the sub template.
+ *
+ * @param resource $request
+ */
 function printMemberListRows($request)
 {
 	global $scripturl, $txt, $user_info, $modSettings;

+ 10 - 13
Sources/MessageIndex.php

@@ -1,6 +1,9 @@
 <?php
 
 /**
+ * This file is what shows the listing of topics in a board.
+ * It's just one or two functions, but don't under estimate it ;).
+ *
  * Simple Machines Forum (SMF)
  *
  * @package SMF
@@ -14,18 +17,9 @@
 if (!defined('SMF'))
 	die('Hacking attempt...');
 
-/*	This file is what shows the listing of topics in a board.  It's just one
-	function, but don't under estimate it ;).
-
-	void MessageIndex()
-		// !!!
-
-	void QuickModeration()
-		// !!!
-
-*/
-
-// Show the list of topics in this board, along with any child boards.
+/**
+ * Show the list of topics in this board, along with any child boards.
+ */
 function MessageIndex()
 {
 	global $txt, $scripturl, $board, $modSettings, $context;
@@ -637,7 +631,10 @@ function MessageIndex()
 	$context['no_topic_listing'] = !empty($context['boards']) && empty($context['topics']) && !$context['can_post_new'];
 }
 
-// Allows for moderation from the message index.
+/**
+ * Allows for moderation from the message index.
+ * @todo refactor this...
+ */
 function QuickModeration()
 {
 	global $sourcedir, $board, $user_info, $modSettings, $sourcedir, $smcFunc, $context;

+ 108 - 23
Sources/ModerationCenter.php

@@ -1,6 +1,8 @@
 <?php
 
 /**
+ * Moderation Center.
+ *
  * Simple Machines Forum (SMF)
  *
  * @package SMF
@@ -14,11 +16,11 @@
 if (!defined('SMF'))
 	die('Hacking attempt...');
 
-/*
-	//!!!
-*/
-
-// Entry point for the moderation center.
+/**
+ * Entry point for the moderation center.
+ *
+ * @param bool $dont_call = false
+ */
 function ModerationMain($dont_call = false)
 {
 	global $txt, $context, $scripturl, $sc, $modSettings, $user_info, $settings, $sourcedir, $options, $smcFunc;
@@ -191,7 +193,9 @@ function ModerationMain($dont_call = false)
 	}
 }
 
-// This function basically is the home page of the moderation center.
+/**
+ * This function basically is the home page of the moderation center.
+ */
 function ModerationHome()
 {
 	global $txt, $context, $scripturl, $modSettings, $user_info, $user_settings;
@@ -233,7 +237,9 @@ function ModerationHome()
 	}
 }
 
-// Just prepares the time stuff for the simple machines latest news.
+/**
+ * Just prepares the time stuff for the simple machines latest news.
+ */
 function ModBlockLatestNews()
 {
 	global $context, $user_info;
@@ -244,7 +250,9 @@ function ModBlockLatestNews()
 	return 'latest_news';
 }
 
-// Show a list of the most active watched users.
+/**
+ * Show a list of the most active watched users.
+ */
 function ModBlockWatchedUsers()
 {
 	global $context, $smcFunc, $scripturl, $modSettings;
@@ -285,7 +293,9 @@ function ModBlockWatchedUsers()
 	return 'watched_users';
 }
 
-// Show an area for the moderator to type into.
+/**
+ * Show an area for the moderator to type into.
+ */
 function ModBlockNotes()
 {
 	global $context, $smcFunc, $scripturl, $txt, $user_info;
@@ -409,7 +419,9 @@ function ModBlockNotes()
 	return 'notes';
 }
 
-// Show a list of the most recent reported posts.
+/**
+ * Show a list of the most recent reported posts.
+ */
 function ModBlockReportedPosts()
 {
 	global $context, $user_info, $scripturl, $smcFunc;
@@ -471,7 +483,9 @@ function ModBlockReportedPosts()
 	return 'reported_posts_block';
 }
 
-// Show a list of all the group requests they can see.
+/**
+ * Show a list of all the group requests they can see.
+ */
 function ModBlockGroupRequests()
 {
 	global $context, $user_info, $scripturl, $smcFunc;
@@ -517,8 +531,10 @@ function ModBlockGroupRequests()
 	return 'group_requests_block';
 }
 
-//!!! This needs to be given its own file.
-// Browse all the reported posts...
+/**
+ * Browse all the reported posts...
+ * @todo this needs to be given its own file?
+ */
 function ReportedPosts()
 {
 	global $txt, $context, $scripturl, $modSettings, $user_info, $smcFunc;
@@ -689,8 +705,10 @@ function ReportedPosts()
 	}
 }
 
-// Act as an entrace for all group related activity.
-//!!! As for most things in this file, this needs to be moved somewhere appropriate.
+/**
+ * Act as an entrace for all group related activity.
+ * @todo As for most things in this file, this needs to be moved somewhere appropriate?
+ */
 function ModerateGroups()
 {
 	global $txt, $context, $scripturl, $modSettings, $user_info;
@@ -716,7 +734,9 @@ function ModerateGroups()
 	$subactions[$context['sub_action']]();
 }
 
-// How many open reports do we have?
+/**
+ * How many open reports do we have?
+ */
 function recountOpenReports()
 {
 	global $user_info, $context, $smcFunc;
@@ -744,6 +764,10 @@ function recountOpenReports()
 	$context['open_mod_reports'] = $open_reports;
 }
 
+/**
+ * Get details about the moderation report... specified in
+ * $_REQUEST['report'].
+ */
 function ModReport()
 {
 	global $user_info, $context, $sourcedir, $scripturl, $txt, $smcFunc;
@@ -1000,7 +1024,9 @@ function ModReport()
 	$context['sub_template'] = 'viewmodreport';
 }
 
-// Show a notice sent to a user.
+/**
+ * Show a notice sent to a user.
+ */
 function ShowNotice()
 {
 	global $smcFunc, $txt, $context;
@@ -1029,7 +1055,9 @@ function ShowNotice()
 	$context['notice_body'] = parse_bbc($context['notice_body'], false);
 }
 
-// View watched users.
+/**
+ * View watched users.
+ */
 function ViewWatchedUsers()
 {
 	global $smcFunc, $modSettings, $context, $txt, $scripturl, $user_info, $sourcedir;
@@ -1239,6 +1267,10 @@ function ViewWatchedUsers()
 	$context['default_list'] = 'watch_user_list';
 }
 
+/**
+ * Callback for createList().
+ * @param $approve_query
+ */
 function list_getWatchedUserCount($approve_query)
 {
 	global $smcFunc, $modSettings;
@@ -1257,6 +1289,15 @@ function list_getWatchedUserCount($approve_query)
 	return $totalMembers;
 }
 
+/**
+ * Callback for createList().
+ *
+ * @param $start
+ * @param $items_per_page
+ * @param $sort
+ * @param $approve_query
+ * @param $dummy
+ */
 function list_getWatchedUsers($start, $items_per_page, $sort, $approve_query, $dummy)
 {
 	global $smcFunc, $txt, $scripturl, $modSettings, $user_info, $context;
@@ -1351,6 +1392,11 @@ function list_getWatchedUsers($start, $items_per_page, $sort, $approve_query, $d
 	return $watched_users;
 }
 
+/**
+ * Callback for createList().
+ *
+ * @param $approve_query
+ */
 function list_getWatchedUserPostsCount($approve_query)
 {
 	global $smcFunc, $modSettings, $user_info;
@@ -1373,6 +1419,15 @@ function list_getWatchedUserPostsCount($approve_query)
 	return $totalMemberPosts;
 }
 
+/**
+ * Callback for createList().
+ *
+ * @param $start
+ * @param $items_per_page
+ * @param $sort
+ * @param $approve_query
+ * @param $delete_boards
+ */
 function list_getWatchedUserPosts($start, $items_per_page, $sort, $approve_query, $delete_boards)
 {
 	global $smcFunc, $txt, $scripturl, $modSettings, $user_info;
@@ -1414,7 +1469,9 @@ function list_getWatchedUserPosts($start, $items_per_page, $sort, $approve_query
 	return $member_posts;
 }
 
-// Entry point for viewing warning related stuff.
+/**
+ * Entry point for viewing warning related stuff.
+ */
 function ViewWarnings()
 {
 	global $context, $txt;
@@ -1441,7 +1498,9 @@ function ViewWarnings()
 	$subActions[$_REQUEST['sa']][0]();
 }
 
-// Simply put, look at the warning log!
+/**
+ * Simply put, look at the warning log!
+ */
 function ViewWarningLog()
 {
 	global $smcFunc, $modSettings, $context, $txt, $scripturl, $sourcedir;
@@ -1544,6 +1603,9 @@ function ViewWarningLog()
 	$context['default_list'] = 'warning_list';
 }
 
+/**
+ * Callback for createList().
+ */
 function list_getWarningCount()
 {
 	global $smcFunc, $modSettings;
@@ -1562,6 +1624,13 @@ function list_getWarningCount()
 	return $totalWarns;
 }
 
+/**
+ * Callback for createList().
+ *
+ * @param $start
+ * @param $items_per_page
+ * @param $sort
+ */
 function list_getWarnings($start, $items_per_page, $sort)
 {
 	global $smcFunc, $txt, $scripturl, $modSettings, $user_info;
@@ -1597,7 +1666,9 @@ function list_getWarnings($start, $items_per_page, $sort)
 	return $warnings;
 }
 
-// Load all the warning templates.
+/**
+ * Load all the warning templates.
+ */
 function ViewWarningTemplates()
 {
 	global $smcFunc, $modSettings, $context, $txt, $scripturl, $sourcedir, $user_info;
@@ -1741,6 +1812,9 @@ function ViewWarningTemplates()
 	$context['default_list'] = 'warning_template_list';
 }
 
+/**
+  * Callback for createList().
+  */
 function list_getWarningTemplateCount()
 {
 	global $smcFunc, $modSettings, $user_info;
@@ -1762,6 +1836,13 @@ function list_getWarningTemplateCount()
 	return $totalWarns;
 }
 
+/**
+ * Callback for createList().
+ *
+ * @param $start
+ * @param $items_per_page
+ * @param $sort
+ */
 function list_getWarningTemplates($start, $items_per_page, $sort)
 {
 	global $smcFunc, $txt, $scripturl, $modSettings, $user_info;
@@ -1798,7 +1879,9 @@ function list_getWarningTemplates($start, $items_per_page, $sort)
 	return $templates;
 }
 
-// Edit a warning template.
+/**
+ * Edit a warning template.
+ */
 function ModifyWarningTemplate()
 {
 	global $smcFunc, $context, $txt, $user_info, $sourcedir;
@@ -1929,7 +2012,9 @@ function ModifyWarningTemplate()
 	}
 }
 
-// Change moderation preferences.
+/**
+ * Change moderation preferences.
+ */
 function ModerationSettings()
 {
 	global $context, $smcFunc, $txt, $sourcedir, $scripturl, $user_settings, $user_info;

+ 31 - 21
Sources/Modlog.php

@@ -1,6 +1,9 @@
 <?php
 
 /**
+ * The moderation log is this file's only job.
+ * It views it, and that's about all it does.
+ *
  * Simple Machines Forum (SMF)
  *
  * @package SMF
@@ -14,26 +17,15 @@
 if (!defined('SMF'))
 	die('Hacking attempt...');
 
-/*	The moderation log is this file's only job.  It views it, and that's about
-	all it does.
-
-	void ViewModlog()
-		- prepares the information from the moderation log for viewing.
-		- disallows the deletion of events within twenty-four hours of now.
-		- requires the admin_forum permission.
-		- uses the Modlog template, main sub template.
-		- is accessed via ?action=moderate;area=modlog.
-
-	int list_getModLogEntries()
-		//!!!
-
-	array list_getModLogEntries($start, $items_per_page, $sort, $query_string = '', $query_params = array(), $log_type = 1)
-		- Gets the moderation log entries that match the specified paramaters
-		- limit can be an array with two values
-		- search_param and order should be proper SQL strings or blank.  If blank they are not used.
-*/
-
-// Show the moderation log
+/**
+ * Prepares the information from the moderation log for viewing.
+ * Show the moderation log.
+ * Disallows the deletion of events within twenty-four hours of now.
+ * Requires the admin_forum permission.
+ * Accessed via ?action=moderate;area=modlog.
+ *
+ * @uses Modlog template, main sub-template.
+ */
 function ViewModlog()
 {
 	global $txt, $modSettings, $context, $scripturl, $sourcedir, $user_info, $smcFunc, $settings;
@@ -302,7 +294,14 @@ function ViewModlog()
 	$context['default_list'] = 'moderation_log_list';
 }
 
-// Get the number of mod log entries.
+/**
+ * Get the number of mod log entries.
+ * Callback for createList() in ViewModlog().
+ *
+ * @param $query_string
+ * @param $query_params
+ * @param $log_type
+ */
 function list_getModLogEntryCount($query_string = '', $query_params = array(), $log_type = 1)
 {
 	global $smcFunc, $user_info;
@@ -332,6 +331,17 @@ function list_getModLogEntryCount($query_string = '', $query_params = array(), $
 	return $entry_count;
 }
 
+/**
+ * Gets the moderation log entries that match the specified parameters.
+ * Callback for createList() in ViewModlog().
+ *
+ * @param $start
+ * @param $items_per_page
+ * @param $sort
+ * @param $query_string
+ * @param $query_params
+ * @param $log_type
+ */
 function list_getModLogEntries($start, $items_per_page, $sort, $query_string = '', $query_params = array(), $log_type = 1)
 {
 	global $context, $scripturl, $txt, $smcFunc, $user_info;

+ 60 - 45
Sources/News.php

@@ -1,6 +1,8 @@
 <?php
 
 /**
+ * This file contains the files necessary to display news as an XML feed.
+ *
  * Simple Machines Forum (SMF)
  *
  * @package SMF
@@ -14,51 +16,21 @@
 if (!defined('SMF'))
 	die('Hacking attempt...');
 
-/*	This file contains the files necessary to display news as an XML feed.
-
-	void ShowXmlFeed()
-		- is called to output xml information.
-		- can be passed four subactions which decide what is output: 'recent'
-		  for recent posts, 'news' for news topics, 'members' for recently
-		  registered members, and 'profile' for a member's profile.
-		- To display a member's profile, a user id has to be given. (;u=1)
-		- uses the Stats language file.
-		- outputs an rss feed instead of a proprietary one if the 'type' get
-		  parameter is 'rss' or 'rss2'.
-		- does not use any templates, sub templates, or template layers.
-		- is accessed via ?action=.xml.
-
-	void dumpTags(array data, int indentation, string tag = use_array,
-			string format)
-		- formats data retrieved in other functions into xml format.
-		- additionally formats data based on the specific format passed.
-		- the data parameter is the array to output as xml data.
-		- indentation is the amount of indentation to use.
-		- if a tag is specified, it will be used instead of the keys of data.
-		- this function is recursively called to handle sub arrays of data.
-
-	array getXmlMembers(string format)
-		- is called to retrieve list of members from database.
-		- the array will be generated to match the format.
-		- returns array of data.
-
-	array getXmlNews(string format)
-		- is called to retrieve news topics from database.
-		- the array will be generated to match the format.
-		- returns array of topics.
-
-	array getXmlRecent(string format)
-		- is called to retrieve list of recent topics.
-		- the array will be generated to match the format.
-		- returns an array of recent posts.
-
-	array getXmlProfile(string format)
-		- is called to retrieve profile information for member into array.
-		- the array will be generated to match the format.
-		- returns an array of data.
-*/
-
-// Show an xml file representing recent information or a profile.
+/**
+ * Outputs xml data representing recent information or a profile.
+ * Can be passed 4 subactions which decide what is output:
+ *  'recent' for recent posts,
+ *  'news' for news topics,
+ *  'members' for recently registered members,
+ *  'profile' for a member's profile.
+ * To display a member's profile, a user id has to be given. (;u=1)
+ * Outputs an rss feed instead of a proprietary one if the 'type' $_GET
+ * parameter is 'rss' or 'rss2'.
+ * Accessed via ?action=.xml.
+ * Does not use any templates, sub templates, or template layers.
+ *
+ * @uses Stats language file.
+ */
 function ShowXmlFeed()
 {
 	global $board, $board_info, $context, $scripturl, $txt, $modSettings, $user_info;
@@ -451,6 +423,16 @@ function cdata_parse($data, $ns = '')
 	return strtr($cdata, array('<![CDATA[]]>' => ''));
 }
 
+/**
+ * Formats data retrieved in other functions into xml format.
+ * Additionally formats data based on the specific format passed.
+ * This function is recursively called to handle sub arrays of data.
+
+ * @param array $data, the array to output as xml data
+ * @param int $i, the amount of indentation to use.
+ * @param string $tag, if specified, it will be used instead of the keys of data.
+ * @param string $xml_format
+ */
 function dumpTags($data, $i, $tag = null, $xml_format = '')
 {
 	global $modSettings, $context, $scripturl;
@@ -508,6 +490,14 @@ function dumpTags($data, $i, $tag = null, $xml_format = '')
 	}
 }
 
+/**
+ * Retrieve the list of members from database.
+ * The array will be generated to match the format.
+ * @todo get the list of members from Subs-Members.
+ *
+ * @param string $xml_format
+ * @return array
+ */
 function getXmlMembers($xml_format)
 {
 	global $scripturl, $smcFunc;
@@ -564,6 +554,15 @@ function getXmlMembers($xml_format)
 	return $data;
 }
 
+/**
+ * Get the latest topics information from a specific board,
+ * to display later.
+ * The returned array will be generated to match the xmf_format.
+ * @todo does not belong here
+ *
+ * @param $xml_format
+ * @return array, array of topics
+ */
 function getXmlNews($xml_format)
 {
 	global $user_info, $scripturl, $modSettings, $board;
@@ -691,6 +690,14 @@ function getXmlNews($xml_format)
 	return $data;
 }
 
+/**
+ * Get the recent topics to display.
+ * The returned array will be generated to match the xml_format.
+ * @todo does not belong here.
+ *
+ * @param $xml_format
+ * @return array, of recent posts
+ */
 function getXmlRecent($xml_format)
 {
 	global $user_info, $scripturl, $modSettings, $board;
@@ -848,6 +855,14 @@ function getXmlRecent($xml_format)
 	return $data;
 }
 
+/**
+ * Get the profile information for member into an array,
+ * which will be generated to match the xml_format.
+ * @todo refactor.
+ *
+ * @param $xml_format
+ * @return array, of profile data.
+ */
 function getXmlProfile($xml_format)
 {
 	global $scripturl, $memberContext, $user_profile, $modSettings, $user_info;

+ 23 - 23
Sources/Notify.php

@@ -1,6 +1,9 @@
 <?php
 
 /**
+ * This file contains just the functions that turn on and off notifications
+ * to topics or boards.
+ *
  * Simple Machines Forum (SMF)
  *
  * @package SMF
@@ -14,29 +17,16 @@
 if (!defined('SMF'))
 	die('Hacking attempt...');
 
-/*	This file contains just the functions that turn on and off notifications to
-	topics or boards. The following two functions are included:
-
-	void Notify()
-		- is called to turn off/on notification for a particular topic.
-		- must be called with a topic specified in the URL.
-		- uses the Notify template (main sub template.) when called with no sa.
-		- the sub action can be 'on', 'off', or nothing for what to do.
-		- requires the mark_any_notify permission.
-		- upon successful completion of action will direct user back to topic.
-		- is accessed via ?action=notify.
-
-	void BoardNotify()
-		- is called to turn off/on notification for a particular board.
-		- must be called with a board specified in the URL.
-		- uses the Notify template. (notify_board sub template.)
-		- only uses the template if no sub action is used. (on/off)
-		- requires the mark_notify permission.
-		- redirects the user back to the board after it is done.
-		- is accessed via ?action=notifyboard.
-*/
-
-// Turn on/off notifications...
+/**
+ * Turn off/on notification for a particular topic.
+ * Must be called with a topic specified in the URL.
+ * The sub-action can be 'on', 'off', or nothing for what to do.
+ * Requires the mark_any_notify permission.
+ * Upon successful completion of action will direct user back to topic.
+ * Accessed via ?action=notify.
+ *
+ * @uses Notify template, main sub-template
+ */
 function Notify()
 {
 	global $scripturl, $txt, $topic, $user_info, $context, $smcFunc;
@@ -109,6 +99,16 @@ function Notify()
 	redirectexit('topic=' . $topic . '.' . $_REQUEST['start']);
 }
 
+/**
+ * Turn off/on notification for a particular board.
+ * Must be called with a board specified in the URL.
+ * Only uses the template if no sub action is used. (on/off)
+ * Requires the mark_notify permission.
+ * Redirects the user back to the board after it is done.
+ * Accessed via ?action=notifyboard.
+ *
+ * @uses Notify template, notify_board sub-template.
+ */
 function BoardNotify()
 {
 	global $scripturl, $txt, $board, $user_info, $context, $smcFunc;

+ 23 - 27
Sources/PackageGet.php

@@ -1,6 +1,8 @@
 <?php
 
 /**
+ * This file handles the package servers and packages download from Package Manager.
+ *
  * Simple Machines Forum (SMF)
  *
  * @package SMF
@@ -14,28 +16,9 @@
 if (!defined('SMF'))
 	die('Hacking attempt...');
 
-/* // !!!
-
-	void PackageGet()
-		// !!!
-
-	void PackageGBrowse()
-		// !!!
-
-	void PackageDownload()
-		// !!!
-
-	void PackageUpload()
-		// !!!
-
-	void PackageServerAdd()
-		// !!!
-
-	void PackageServerRemove()
-		// !!!
-*/
-
-// Browse the list of package servers, add servers...
+/**
+ * Browse the list of package servers, add servers...
+ */
 function PackageGet()
 {
 	global $txt, $scripturl, $context, $boarddir, $sourcedir, $modSettings;
@@ -97,6 +80,9 @@ function PackageGet()
 	$subActions[$context['sub_action']]();
 }
 
+/**
+ * Load a list of package servers.
+ */
 function PackageServers()
 {
 	global $txt, $scripturl, $context, $boarddir, $sourcedir, $modSettings, $smcFunc;
@@ -189,7 +175,9 @@ function PackageServers()
 	}
 }
 
-// Browse a server's list of packages.
+/**
+ * Browse a server's list of packages.
+ */
 function PackageGBrowse()
 {
 	global $txt, $boardurl, $context, $scripturl, $boarddir, $sourcedir, $forum_version, $context, $smcFunc;
@@ -519,7 +507,9 @@ function PackageGBrowse()
 	}
 }
 
-// Download a package.
+/**
+ * Download a package.
+ */
 function PackageDownload()
 {
 	global $txt, $scripturl, $boarddir, $context, $sourcedir, $smcFunc;
@@ -626,7 +616,9 @@ function PackageDownload()
 	$context['page_title'] = $txt['download_success'];
 }
 
-// Upload a new package to the directory.
+/**
+ * Upload a new package to the directory.
+ */
 function PackageUpload()
 {
 	global $txt, $scripturl, $boarddir, $context, $sourcedir;
@@ -710,7 +702,9 @@ function PackageUpload()
 	$context['page_title'] = $txt['package_uploaded_success'];
 }
 
-// Add a package server to the list.
+/**
+ * Add a package server to the list.
+ */
 function PackageServerAdd()
 {
 	global $smcFunc;
@@ -744,7 +738,9 @@ function PackageServerAdd()
 	redirectexit('action=admin;area=packages;get');
 }
 
-// Remove a server from the list.
+/**
+ * Remove a server from the list.
+ */
 function PackageServerRemove()
 {
 	global $smcFunc;

+ 42 - 49
Sources/Packages.php

@@ -1,6 +1,8 @@
 <?php
 
 /**
+ * This file is the main Package Manager.
+ *
  * Simple Machines Forum (SMF)
  *
  * @package SMF
@@ -14,48 +16,14 @@
 if (!defined('SMF'))
 	die('Hacking attempt...');
 
-/* // !!!
-
-	void Packages()
-		// !!!
-
-	void PackageInstallTest()
-		// !!!
-
-	void PackageInstall()
-		// !!!
-
-	void PackageList()
-		// !!!
-
-	void ExamineFile()
-		// !!!
-
-	void InstalledList()
-		// !!!
-
-	void FlushInstall()
-		// !!!
-
-	void PackageRemove()
-		// !!!
-
-	void PackageBrowse()
-		// !!!
-
-	void PackageOptions()
-		// !!!
-
-	void ViewOperations()
-		// !!!
-*/
-
-// This is the notoriously defunct package manager..... :/.
+/**
+ * This is the notoriously defunct package manager..... :/.
+ */
 function Packages()
 {
 	global $txt, $scripturl, $sourcedir, $context;
 
-	//!!! Remove this!
+	//@todo Remove this!
 	if (isset($_GET['get']) || isset($_GET['pgdownload']))
 	{
 		require_once($sourcedir . '/PackageGet.php');
@@ -122,7 +90,9 @@ function Packages()
 	$subActions[$context['sub_action']]();
 }
 
-// Test install a package.
+/**
+ * Test install a package.
+ */
 function PackageInstallTest()
 {
 	global $boarddir, $txt, $context, $scripturl, $sourcedir, $modSettings, $smcFunc, $settings;
@@ -690,7 +660,9 @@ function PackageInstallTest()
 	checkSubmitOnce('register');
 }
 
-// Apply another type of (avatar, language, etc.) package.
+/**
+ * Apply another type of (avatar, language, etc.) package.
+ */
 function PackageInstall()
 {
 	global $boarddir, $txt, $context, $boardurl, $scripturl, $sourcedir, $modSettings;
@@ -1108,7 +1080,9 @@ function PackageInstall()
 	create_chmod_control(array(), array(), true);
 }
 
-// List the files in a package.
+/**
+ * List the files in a package.
+ */
 function PackageList()
 {
 	global $txt, $scripturl, $boarddir, $context, $sourcedir;
@@ -1136,7 +1110,9 @@ function PackageList()
 		$context['files'] = listtree($boarddir . '/Packages/' . $context['filename']);
 }
 
-// List the files in a package.
+/**
+ * Display one of the files in a package.
+ */
 function ExamineFile()
 {
 	global $txt, $scripturl, $boarddir, $context, $sourcedir;
@@ -1190,7 +1166,9 @@ function ExamineFile()
 	}
 }
 
-// List the installed packages.
+/**
+ * List the installed packages.
+ */
 function InstalledList()
 {
 	global $txt, $scripturl, $context;
@@ -1202,7 +1180,9 @@ function InstalledList()
 	$context['installed_mods'] = loadInstalledPackages();
 }
 
-// Empty out the installed list.
+/**
+ * Empty out the installed list.
+ */
 function FlushInstall()
 {
 	global $boarddir, $sourcedir, $smcFunc;
@@ -1227,7 +1207,9 @@ function FlushInstall()
 	redirectexit('action=admin;area=packages;sa=installed');
 }
 
-// Delete a package.
+/**
+ * Delete a package.
+ */
 function PackageRemove()
 {
 	global $scripturl, $boarddir;
@@ -1257,7 +1239,9 @@ function PackageRemove()
 	redirectexit('action=admin;area=packages;sa=browse');
 }
 
-// Browse a list of installed packages.
+/**
+ * Browse a list of installed packages.
+ */
 function PackageBrowse()
 {
 	global $txt, $boarddir, $scripturl, $context, $forum_version;
@@ -1447,6 +1431,9 @@ function PackageOptions()
 	$context['package_make_backups'] = !empty($modSettings['package_make_backups']);
 }
 
+/**
+ * List operations
+ */
 function ViewOperations()
 {
 	global $context, $txt, $boarddir, $sourcedir, $smcFunc, $modSettings;
@@ -1531,7 +1518,9 @@ function ViewOperations()
 	$context['sub_template'] = 'view_operations';
 }
 
-// Allow the admin to reset permissions on files.
+/**
+ * Allow the admin to reset permissions on files.
+ */
 function PackagePermissions()
 {
 	global $context, $txt, $modSettings, $boarddir, $sourcedir, $cachedir, $smcFunc, $package_ftp;
@@ -2005,7 +1994,9 @@ function fetchPerms__recursive($path, &$data, $level)
 	}
 }
 
-// Actually action the permission changes they want.
+/**
+ * Actually action the permission changes they want.
+ */
 function PackagePermissionsAction()
 {
 	global $context, $txt, $time_start, $package_ftp;
@@ -2228,7 +2219,9 @@ function PackagePermissionsAction()
 	redirectexit('action=admin;area=packages;sa=perms' . (!empty($context['back_look_data']) ? ';back_look=' . base64_encode(serialize($context['back_look_data'])) : '') . ';' . $context['session_var'] . '=' . $context['session_id']);
 }
 
-// Test an FTP connection.
+/**
+ * Test an FTP connection.
+ */
 function PackageFTPTest()
 {
 	global $context, $txt, $package_ftp;

+ 56 - 59
Sources/Poll.php

@@ -1,6 +1,9 @@
 <?php
 
 /**
+ * This file contains the functions for voting, locking, removing and
+ * editing polls. Note that that posting polls is done in Post.php.
+ *
  * Simple Machines Forum (SMF)
  *
  * @package SMF
@@ -14,61 +17,16 @@
 if (!defined('SMF'))
 	die('Hacking attempt...');
 
-/*	This file contains the functions for voting, locking, removing and editing
-	polls. Note that that posting polls is done in Post.php.
-
-	void Vote()
-		- is called to register a vote in a poll.
-		- must be called with a topic and option specified.
-		- uses the Post language file.
-		- requires the poll_vote permission.
-		- upon successful completion of action will direct user back to topic.
-		- is accessed via ?action=vote.
-
-	void LockVoting()
-		- is called to lock or unlock voting on a poll.
-		- must be called with a topic specified in the URL.
-		- an admin always has over riding permission to lock a poll.
-		- if not an admin must have poll_lock_any permission.
-		- otherwise must be poll starter with poll_lock_own permission.
-		- upon successful completion of action will direct user back to topic.
-		- is accessed via ?action=lockvoting.
-
-	void EditPoll()
-		- is called to display screen for editing or adding a poll.
-		- must be called with a topic specified in the URL.
-		- if the user is adding a poll to a topic, must contain the variable
-		  'add' in the url.
-		- uses the Post language file.
-		- uses the Poll template (main sub template.).
-		- user must have poll_edit_any/poll_add_any permission for the relevant
-		  action.
-		- otherwise must be poll starter with poll_edit_own permission for
-		  editing, or be topic starter with poll_add_any permission for adding.
-		- is accessed via ?action=editpoll.
-
-	void EditPoll2()
-		- is called to update the settings for a poll, or add a new one.
-		- must be called with a topic specified in the URL.
-		- user must have poll_edit_any/poll_add_any permission for the relevant
-		  action.
-		- otherwise must be poll starter with poll_edit_own permission for
-		  editing, or be topic starter with poll_add_any permission for adding.
-		- in the case of an error will redirect back to EditPoll and display
-		  the relevant error message.
-		- upon successful completion of action will direct user back to topic.
-		- is accessed via ?action=editpoll2.
-
-	void RemovePoll()
-		- is called to remove a poll from a topic.
-		- must be called with a topic specified in the URL.
-		- user must have poll_remove_any permission.
-		- otherwise must be poll starter with poll_remove_own permission.
-		- upon successful completion of action will direct user back to topic.
-		- is accessed via ?action=removepoll.
-*/
-
-// Allow the user to vote.
+/**
+ * Allow the user to vote.
+ * It is called to register a vote in a poll.
+ * Must be called with a topic and option specified.
+ * Requires the poll_vote permission.
+ * Upon successful completion of action will direct user back to topic.
+ * Accessed via ?action=vote.
+ *
+ * @uses Post language file.
+ */
 function Vote()
 {
 	global $topic, $txt, $user_info, $smcFunc, $sourcedir, $modSettings;
@@ -260,7 +218,16 @@ function Vote()
 	redirectexit('topic=' . $topic . '.' . $_REQUEST['start']);
 }
 
-// Lock the voting for a poll.
+//
+/**
+ * Lock the voting for a poll.
+ * Must be called with a topic specified in the URL.
+ * An admin always has over riding permission to lock a poll.
+ * If not an admin must have poll_lock_any permission, otherwise must
+ * be poll starter with poll_lock_own permission.
+ * Upon successful completion of action will direct user back to topic.
+ * Accessed via ?action=lockvoting.
+ */
 function LockVoting()
 {
 	global $topic, $user_info, $smcFunc;
@@ -314,7 +281,19 @@ function LockVoting()
 	redirectexit('topic=' . $topic . '.' . $_REQUEST['start']);
 }
 
-// Ask what to change in a poll.
+/**
+ * Display screen for editing or adding a poll.
+ * Must be called with a topic specified in the URL.
+ * If the user is adding a poll to a topic, must contain the variable
+ * 'add' in the url.
+ * User must have poll_edit_any/poll_add_any permission for the
+ * relevant action, otherwise must be poll starter with poll_edit_own
+ * permission for editing, or be topic starter with poll_add_any permission for adding.
+ * Accessed via ?action=editpoll.
+ *
+ * @uses Post language file.
+ * @uses Poll template, main sub-template.
+ */
 function EditPoll()
 {
 	global $txt, $user_info, $context, $topic, $board, $smcFunc, $sourcedir, $scripturl;
@@ -591,7 +570,18 @@ function EditPoll()
 	checkSubmitOnce('register');
 }
 
-// Change a poll...
+/**
+ * Update the settings for a poll, or add a new one.
+ * Must be called with a topic specified in the URL.
+ * The user must have poll_edit_any/poll_add_any permission
+ * for the relevant action. Otherwise they must be poll starter
+ * with poll_edit_own permission for editing, or be topic starter
+ * with poll_add_any permission for adding.
+ * In the case of an error, this function will redirect back to
+ * EditPoll and display the relevant error message.
+ * Upon successful completion of action will direct user back to topic.
+ * Accessed via ?action=editpoll2.
+ */
 function EditPoll2()
 {
 	global $txt, $topic, $board, $context;
@@ -885,7 +875,14 @@ function EditPoll2()
 	redirectexit('topic=' . $topic . '.' . $_REQUEST['start']);
 }
 
-// Remove a poll from a topic without removing the topic.
+/**
+ * Remove a poll from a topic without removing the topic.
+ * Must be called with a topic specified in the URL.
+ * Requires poll_remove_any permission, unless it's the poll starter
+ * with poll_remove_own permission.
+ * Upon successful completion of action will direct user back to topic.
+ * Accessed via ?action=removepoll.
+ */
 function RemovePoll()
 {
 	global $topic, $user_info, $smcFunc;

+ 31 - 11
Sources/PostModeration.php

@@ -1,6 +1,8 @@
 <?php
 
 /**
+ * This file's job is to handle things related to post moderation.
+ *
  * Simple Machines Forum (SMF)
  *
  * @package SMF
@@ -14,11 +16,9 @@
 if (!defined('SMF'))
 	die('Hacking attempt...');
 
-/*
-	//!!!
-*/
-
-// This is a handling function for all things post moderation...
+/**
+ * This is a handling function for all things post moderation...
+ */
 function PostModerationMain()
 {
 	global $sourcedir;
@@ -45,7 +45,9 @@ function PostModerationMain()
 	$subactions[$_REQUEST['sa']]();
 }
 
-// View all unapproved posts.
+/**
+ * View all unapproved posts.
+ */
 function UnapprovedPosts()
 {
 	global $txt, $scripturl, $context, $user_info, $sourcedir, $smcFunc;
@@ -300,7 +302,9 @@ function UnapprovedPosts()
 	$context['sub_template'] = 'unapproved_posts';
 }
 
-// View all unapproved attachments.
+/**
+ * View all unapproved attachments.
+ */
 function UnapprovedAttachments()
 {
 	global $txt, $scripturl, $context, $user_info, $sourcedir, $smcFunc;
@@ -455,7 +459,9 @@ function UnapprovedAttachments()
 	$context['sub_template'] = 'unapproved_attachments';
 }
 
-// Approve a post, just the one.
+/**
+ * Approve a post, just the one.
+ */
 function ApproveMessage()
 {
 	global $user_info, $topic, $board, $sourcedir, $smcFunc;
@@ -502,7 +508,13 @@ function ApproveMessage()
 	redirectexit('topic=' . $topic . '.msg' . $_REQUEST['msg']. '#msg' . $_REQUEST['msg']);
 }
 
-// Approve a batch of posts (or topics in their own right)
+/**
+ * Approve a batch of posts (or topics in their own right)
+ *
+ * @param $messages
+ * @param $messageDetails
+ * @param $current_view
+ */
 function approveMessages($messages, $messageDetails, $current_view = 'replies')
 {
 	global $sourcedir;
@@ -528,7 +540,9 @@ function approveMessages($messages, $messageDetails, $current_view = 'replies')
 	}
 }
 
-// This is a helper function - basically approve everything!
+/**
+ * This is a helper function - basically approve everything!
+ */
 function approveAllData()
 {
 	global $smcFunc, $sourcedir;
@@ -574,7 +588,13 @@ function approveAllData()
 	}
 }
 
-// remove a batch of messages (or topics)
+/**
+ * Remove a batch of messages (or topics)
+ *
+ * @param array $messages
+ * @param array $messageDetails
+ * @param string $current_view
+ */
 function removeMessages($messages, $messageDetails, $current_view = 'replies')
 {
 	global $sourcedir, $modSettings;

+ 11 - 10
Sources/Printpage.php

@@ -1,6 +1,9 @@
 <?php
 
 /**
+ * This file contains just one function that formats a topic to be printer
+ * friendly.
+ *
  * Simple Machines Forum (SMF)
  *
  * @package SMF
@@ -14,16 +17,14 @@
 if (!defined('SMF'))
 	die('Hacking attempt...');
 
-/*	This file contains just one function that formats a topic to be printer
-	friendly.
-
-	void PrintTopic()
-		- is called to format a topic to be printer friendly.
-		- must be called with a topic specified.
-		- uses the Printpage (main sub template.) template.
-		- uses the print_above/print_below later without the main layer.
-		- is accessed via ?action=printpage.
-*/
+/**
+ * Format a topic to be printer friendly.
+ * Must be called with a topic specified.
+ * Accessed via ?action=printpage.
+ *
+ * @uses Printpage template, main sub-template.
+ * @uses print_above/print_below later without the main layer.
+ */
 
 function PrintTopic()
 {

+ 7 - 2
Sources/Search.php

@@ -1833,8 +1833,13 @@ function PlushSearch2()
 	);
 }
 
-// Callback to return messages - saves memory.
-// !!! Fix this, update it, whatever... from Display.php mainly.
+/**
+ * Callback to return messages - saves memory.
+ * @todo Fix this, update it, whatever... from Display.php mainly.
+ * Note that the call to loadAttachmentContext() doesn't work:
+ * this function doesn't fulfill the pre-condition to fill $attachments global...
+ * So all it does is to fallback and return.
+ */
 function prepareSearchContext($reset = false)
 {
 	global $txt, $modSettings, $scripturl, $user_info, $sourcedir;

+ 5 - 137
Sources/Subs.php

@@ -2537,140 +2537,6 @@ function highlight_php_code($code)
 	return strtr($buffer, array('\'' => '&#039;', '<code>' => '', '</code>' => ''));
 }
 
-// Put this user in the online log.
-function writeLog($force = false)
-{
-	global $user_info, $user_settings, $context, $modSettings, $settings, $topic, $board, $smcFunc, $sourcedir;
-
-	// If we are showing who is viewing a topic, let's see if we are, and force an update if so - to make it accurate.
-	if (!empty($settings['display_who_viewing']) && ($topic || $board))
-	{
-		// Take the opposite approach!
-		$force = true;
-		// Don't update for every page - this isn't wholly accurate but who cares.
-		if ($topic)
-		{
-			if (isset($_SESSION['last_topic_id']) && $_SESSION['last_topic_id'] == $topic)
-				$force = false;
-			$_SESSION['last_topic_id'] = $topic;
-		}
-	}
-
-	// Are they a spider we should be tracking? Mode = 1 gets tracked on its spider check...
-	if (!empty($user_info['possibly_robot']) && !empty($modSettings['spider_mode']) && $modSettings['spider_mode'] > 1)
-	{
-		require_once($sourcedir . '/ManageSearchEngines.php');
-		logSpider();
-	}
-
-	// Don't mark them as online more than every so often.
-	if (!empty($_SESSION['log_time']) && $_SESSION['log_time'] >= (time() - 8) && !$force)
-		return;
-
-	if (!empty($modSettings['who_enabled']))
-	{
-		$serialized = $_GET + array('USER_AGENT' => $_SERVER['HTTP_USER_AGENT']);
-
-		// In the case of a dlattach action, session_var may not be set.
-		if (!isset($context['session_var']))
-			$context['session_var'] = $_SESSION['session_var'];
-
-		unset($serialized['sesc'], $serialized[$context['session_var']]);
-		$serialized = serialize($serialized);
-	}
-	else
-		$serialized = '';
-
-	// Guests use 0, members use their session ID.
-	$session_id = $user_info['is_guest'] ? 'ip' . $user_info['ip'] : session_id();
-
-	// Grab the last all-of-SMF-specific log_online deletion time.
-	$do_delete = cache_get_data('log_online-update', 30) < time() - 30;
-
-	// If the last click wasn't a long time ago, and there was a last click...
-	if (!empty($_SESSION['log_time']) && $_SESSION['log_time'] >= time() - $modSettings['lastActive'] * 20)
-	{
-		if ($do_delete)
-		{
-			$smcFunc['db_query']('delete_log_online_interval', '
-				DELETE FROM {db_prefix}log_online
-				WHERE log_time < {int:log_time}
-					AND session != {string:session}',
-				array(
-					'log_time' => time() - $modSettings['lastActive'] * 60,
-					'session' => $session_id,
-				)
-			);
-
-			// Cache when we did it last.
-			cache_put_data('log_online-update', time(), 30);
-		}
-
-		$smcFunc['db_query']('', '
-			UPDATE {db_prefix}log_online
-			SET log_time = {int:log_time}, ip = IFNULL(INET_ATON({string:ip}), 0), url = {string:url}
-			WHERE session = {string:session}',
-			array(
-				'log_time' => time(),
-				'ip' => $user_info['ip'],
-				'url' => $serialized,
-				'session' => $session_id,
-			)
-		);
-
-		// Guess it got deleted.
-		if ($smcFunc['db_affected_rows']() == 0)
-			$_SESSION['log_time'] = 0;
-	}
-	else
-		$_SESSION['log_time'] = 0;
-
-	// Otherwise, we have to delete and insert.
-	if (empty($_SESSION['log_time']))
-	{
-		if ($do_delete || !empty($user_info['id']))
-			$smcFunc['db_query']('', '
-				DELETE FROM {db_prefix}log_online
-				WHERE ' . ($do_delete ? 'log_time < {int:log_time}' : '') . ($do_delete && !empty($user_info['id']) ? ' OR ' : '') . (empty($user_info['id']) ? '' : 'id_member = {int:current_member}'),
-				array(
-					'current_member' => $user_info['id'],
-					'log_time' => time() - $modSettings['lastActive'] * 60,
-				)
-			);
-
-		$smcFunc['db_insert']($do_delete ? 'ignore' : 'replace',
-			'{db_prefix}log_online',
-			array('session' => 'string', 'id_member' => 'int', 'id_spider' => 'int', 'log_time' => 'int', 'ip' => 'raw', 'url' => 'string'),
-			array($session_id, $user_info['id'], empty($_SESSION['id_robot']) ? 0 : $_SESSION['id_robot'], time(), 'IFNULL(INET_ATON(\'' . $user_info['ip'] . '\'), 0)', $serialized),
-			array('session')
-		);
-	}
-
-	// Mark your session as being logged.
-	$_SESSION['log_time'] = time();
-
-	// Well, they are online now.
-	if (empty($_SESSION['timeOnlineUpdated']))
-		$_SESSION['timeOnlineUpdated'] = time();
-
-	// Set their login time, if not already done within the last minute.
-	if (SMF != 'SSI' && !empty($user_info['last_login']) && $user_info['last_login'] < time() - 60)
-	{
-		// Don't count longer than 15 minutes.
-		if (time() - $_SESSION['timeOnlineUpdated'] > 60 * 15)
-			$_SESSION['timeOnlineUpdated'] = time();
-
-		$user_settings['total_time_logged_in'] += time() - $_SESSION['timeOnlineUpdated'];
-		updateMemberData($user_info['id'], array('last_login' => time(), 'member_ip' => $user_info['ip'], 'member_ip2' => $_SERVER['BAN_CHECK_IP'], 'total_time_logged_in' => $user_settings['total_time_logged_in']));
-
-		if (!empty($modSettings['cache_enable']) && $modSettings['cache_enable'] >= 2)
-			cache_put_data('user_settings-' . $user_info['id'], $user_settings, 60);
-
-		$user_info['total_time_logged_in'] += time() - $_SESSION['timeOnlineUpdated'];
-		$_SESSION['timeOnlineUpdated'] = time();
-	}
-}
-
 /**
  * Make sure the browser doesn't come back and repost the form data.
  * Should be used whenever anything is posted.
@@ -2847,9 +2713,11 @@ function obExit($header = null, $do_footer = null, $from_index = false, $from_fa
 		exit;
 }
 
-
-
-// Track Statistics.
+/**
+ * Track Statistics.
+ *
+ * @param array $stats = array()
+ */
 function trackStats($stats = array())
 {
 	global $modSettings, $smcFunc;

+ 520 - 0
Themes/default/ManageLanguages.template.php

@@ -0,0 +1,520 @@
+<?php
+
+/**
+ * Simple Machines Forum (SMF)
+ *
+ * @package SMF
+ * @author Simple Machines
+ * @copyright 2011 Simple Machines
+ * @license http://www.simplemachines.org/about/smf/license.php BSD
+ *
+ * @version 2.0
+ */
+
+/**
+ * Download a new language file.
+ */
+function template_download_language()
+{
+	global $context, $settings, $options, $txt, $scripturl, $modSettings;
+
+	// Actually finished?
+	if (!empty($context['install_complete']))
+	{
+		echo '
+	<div id="admincenter">
+		<div class="cat_bar">
+			<h3 class="catbg">
+				', $txt['languages_download_complete'], '
+			</h3>
+		</div>
+		<div class="windowbg">
+			<span class="topslice"><span></span></span>
+			<div class="content">
+				', $context['install_complete'], '
+			</div>
+			<span class="botslice"><span></span></span>
+		</div>
+	</div>
+	<br class="clear" />';
+		return;
+	}
+
+	// An error?
+	if (!empty($context['error_message']))
+		echo '
+	<div id="errorbox">
+		<p>', $context['error_message'], '</p>
+	</div>';
+
+	// Provide something of an introduction...
+	echo '
+	<div id="admincenter">
+		<form action="', $scripturl, '?action=admin;area=languages;sa=downloadlang;did=', $context['download_id'], ';', $context['session_var'], '=', $context['session_id'], '" method="post" accept-charset="', $context['character_set'], '">
+			<div class="cat_bar">
+				<h3 class="catbg">
+					', $txt['languages_download'], '
+				</h3>
+			</div>
+			<div class="windowbg">
+				<span class="topslice"><span></span></span>
+				<div class="content">
+					<p>
+						', $txt['languages_download_note'], '
+					</p>
+					<div class="smalltext">
+						', $txt['languages_download_info'], '
+					</div>
+				</div>
+				<span class="botslice"><span></span></span>
+			</div>';
+
+	// Show the main files.
+	template_show_list('lang_main_files_list');
+
+	// Now, all the images and the likes, hidden via javascript 'cause there are so fecking many.
+	echo '
+			<br />
+			<div class="title_bar">
+				<h3 class="titlebg">
+					', $txt['languages_download_theme_files'], '
+				</h3>
+			</div>
+			<table class="table_grid" cellspacing="0" width="100%">
+				<thead>
+					<tr class="catbg">
+						<th class="first_th" scope="col">
+							', $txt['languages_download_filename'], '
+						</th>
+						<th scope="col" width="100">
+							', $txt['languages_download_writable'], '
+						</th>
+						<th scope="col" width="100">
+							', $txt['languages_download_exists'], '
+						</th>
+						<th class="last_th" scope="col" width="50">
+							', $txt['languages_download_copy'], '
+						</th>
+					</tr>
+				</thead>
+				<tbody>';
+
+	foreach ($context['files']['images'] as $theme => $group)
+	{
+		$count = 0;
+		echo '
+				<tr class="titlebg">
+					<td colspan="4">
+						<img src="', $settings['images_url'], '/sort_down.gif" id="toggle_image_', $theme, '" alt="*" />&nbsp;', isset($context['theme_names'][$theme]) ? $context['theme_names'][$theme] : $theme, '
+					</td>
+				</tr>';
+
+		$alternate = false;
+		foreach ($group as $file)
+		{
+			echo '
+				<tr class="windowbg', $alternate ? '2' : '', '" id="', $theme, '-', $count++, '">
+					<td>
+						<strong>', $file['name'], '</strong><br />
+						<span class="smalltext">', $txt['languages_download_dest'], ': ', $file['destination'], '</span>
+					</td>
+					<td>
+						<span style="color: ', ($file['writable'] ? 'green' : 'red'), ';">', ($file['writable'] ? $txt['yes'] : $txt['no']), '</span>
+					</td>
+					<td>
+						', $file['exists'] ? ($file['exists'] == 'same' ? $txt['languages_download_exists_same'] : $txt['languages_download_exists_different']) : $txt['no'], '
+					</td>
+					<td>
+						<input type="checkbox" name="copy_file[]" value="', $file['generaldest'], '"', ($file['default_copy'] ? ' checked="checked"' : ''), ' class="input_check" />
+					</td>
+				</tr>';
+			$alternate = !$alternate;
+		}
+	}
+
+	echo '
+			</tbody>
+			</table>';
+
+	// Do we want some FTP baby?
+	// If the files are not writable, we might!
+	if (!empty($context['still_not_writable']))
+	{
+		if (!empty($context['package_ftp']['error']))
+			echo '
+			<div id="errorbox">
+				<tt>', $context['package_ftp']['error'], '</tt>
+			</div>';
+
+		echo '
+			<div class="cat_bar">
+				<h3 class="catbg">
+					', $txt['package_ftp_necessary'], '
+				</h3>
+			</div>
+			<div class="windowbg">
+				<span class="topslice"><span></span></span>
+				<div class="content">
+					<p>', $txt['package_ftp_why'],'</p>
+					<dl class="settings">
+						<dt
+							<label for="ftp_server">', $txt['package_ftp_server'], ':</label>
+						</dt>
+						<dd>
+							<div class="floatright" style="margin-right: 1px;"><label for="ftp_port" style="padding-top: 2px; padding-right: 2ex;">', $txt['package_ftp_port'], ':&nbsp;</label> <input type="text" size="3" name="ftp_port" id="ftp_port" value="', isset($context['package_ftp']['port']) ? $context['package_ftp']['port'] : (isset($modSettings['package_port']) ? $modSettings['package_port'] : '21'), '" class="input_text" /></div>
+							<input type="text" size="30" name="ftp_server" id="ftp_server" value="', isset($context['package_ftp']['server']) ? $context['package_ftp']['server'] : (isset($modSettings['package_server']) ? $modSettings['package_server'] : 'localhost'), '" style="width: 70%;" class="input_text" />
+						</dd>
+
+						<dt>
+							<label for="ftp_username">', $txt['package_ftp_username'], ':</label>
+						</dt>
+						<dd>
+							<input type="text" size="50" name="ftp_username" id="ftp_username" value="', isset($context['package_ftp']['username']) ? $context['package_ftp']['username'] : (isset($modSettings['package_username']) ? $modSettings['package_username'] : ''), '" style="width: 99%;" class="input_text" />
+						</dd>
+
+						<dt>
+							<label for="ftp_password">', $txt['package_ftp_password'], ':</label>
+						</dt>
+						<dd>
+							<input type="password" size="50" name="ftp_password" id="ftp_password" style="width: 99%;" class="input_text" />
+						</dd>
+
+						<dt>
+							<label for="ftp_path">', $txt['package_ftp_path'], ':</label>
+						</dt>
+						<dd>
+							<input type="text" size="50" name="ftp_path" id="ftp_path" value="', $context['package_ftp']['path'], '" style="width: 99%;" class="input_text" />
+						</dd>
+					</dl>
+				</div>
+				<span class="botslice"><span></span></span>
+			</div>';
+	}
+
+	// Install?
+	echo '
+			<div class="righttext padding">
+				<input type="hidden" name="', $context['session_var'], '" value="', $context['session_id'], '" />
+				<input type="submit" name="do_install" value="', $txt['add_language_smf_install'], '" class="button_submit" />
+			</div>
+		</form>
+	</div>
+	<br class="clear" />';
+
+	// The javascript for expand and collapse of sections.
+	echo '
+	<script type="text/javascript"><!-- // --><![CDATA[';
+
+	// Each theme gets its own handler.
+	foreach ($context['files']['images'] as $theme => $group)
+	{
+		$count = 0;
+		echo '
+			var oTogglePanel_', $theme, ' = new smc_Toggle({
+				bToggleEnabled: true,
+				bCurrentlyCollapsed: true,
+				aSwappableContainers: [';
+		foreach ($group as $file)
+			echo '
+					', JavaScriptEscape($theme . '-' . $count++), ',';
+		echo '
+					null
+				],
+				aSwapImages: [
+					{
+						sId: \'toggle_image_', $theme, '\',
+						srcExpanded: smf_images_url + \'/sort_down.gif\',
+						altExpanded: \'*\',
+						srcCollapsed: smf_images_url + \'/selected.gif\',
+						altCollapsed: \'*\'
+					}
+				]
+			});';
+	}
+
+	echo '
+	// ]]></script>';
+}
+
+/**
+ * Edit language entries.
+ */
+function template_modify_language_entries()
+{
+	global $context, $settings, $options, $txt, $scripturl;
+
+	echo '
+	<div id="admincenter">
+		<form action="', $scripturl, '?action=admin;area=languages;sa=editlang;lid=', $context['lang_id'], '" method="post" accept-charset="', $context['character_set'], '">
+			<div class="cat_bar">
+				<h3 class="catbg">
+					', $txt['edit_languages'], '
+				</h3>
+			</div>';
+
+	// Not writable?
+	if ($context['lang_file_not_writable_message'])
+	{
+		// Oops, show an error for ya.
+		echo '
+			<div id="errorbox">
+				<p class="alert">', $context['lang_file_not_writable_message'], '</p>
+			</div>';
+	}
+
+	// Show the language entries
+	echo '
+			<div class="information">
+				', $txt['edit_language_entries_primary'], '
+			</div>
+			<div class="windowbg">
+				<span class="topslice"><span></span></span>
+				<div class="content">
+					<fieldset>
+						<legend>', $context['primary_settings']['name'], '</legend>
+					<dl class="settings">
+						<dt>
+							', $txt['languages_character_set'], ':
+						</dt>
+						<dd>
+							<input type="text" name="character_set" size="20" value="', $context['primary_settings']['character_set'], '"', (empty($context['file_entries']) ? '' : ' disabled="disabled"'), ' class="input_text" />
+						</dd>
+						<dt>
+							', $txt['languages_locale'], ':
+						</dt>
+						<dd>
+							<input type="text" name="locale" size="20" value="', $context['primary_settings']['locale'], '"', (empty($context['file_entries']) ? '' : ' disabled="disabled"'), ' class="input_text" />
+						</dd>
+						<dt>
+							', $txt['languages_dictionary'], ':
+						</dt>
+						<dd>
+							<input type="text" name="dictionary" size="20" value="', $context['primary_settings']['dictionary'], '"', (empty($context['file_entries']) ? '' : ' disabled="disabled"'), ' class="input_text" />
+						</dd>
+						<dt>
+							', $txt['languages_spelling'], ':
+						</dt>
+						<dd>
+							<input type="text" name="spelling" size="20" value="', $context['primary_settings']['spelling'], '"', (empty($context['file_entries']) ? '' : ' disabled="disabled"'), ' class="input_text" />
+						</dd>
+						<dt>
+							', $txt['languages_rtl'], ':
+						</dt>
+						<dd>
+							<input type="checkbox" name="rtl"', $context['primary_settings']['rtl'] ? ' checked="checked"' : '', ' class="input_check"', (empty($context['file_entries']) ? '' : ' disabled="disabled"'), ' />
+						</dd>
+					</dl>
+					</fieldset>
+					<div class="righttext">
+						<input type="hidden" name="', $context['session_var'], '" value="', $context['session_id'], '" />
+						<input type="submit" name="save_main" value="', $txt['save'], '"', $context['lang_file_not_writable_message'] || !empty($context['file_entries']) ? ' disabled="disabled"' : '', ' class="button_submit" />';
+
+	// Allow deleting entries.
+	if ($context['lang_id'] != 'english')
+	{
+		// English can't be deleted though.
+		echo '
+						<input type="submit" name="delete_main" value="', $txt['delete'], '"', $context['lang_file_not_writable_message'] || !empty($context['file_entries']) ? ' disabled="disabled"' : '', ' onclick="confirm(\'', $txt['languages_delete_confirm'], '\');" class="button_submit" />';
+	}
+
+	echo '
+					</div>
+				</div>
+				<span class="botslice"><span></span></span>
+			</div>
+		</form>
+
+		<form action="', $scripturl, '?action=admin;area=languages;sa=editlang;lid=', $context['lang_id'], ';entries" id="entry_form" method="post" accept-charset="', $context['character_set'], '">
+			<div class="title_bar">
+				<h3 class="titlebg">
+					', $txt['edit_language_entries'], '
+				</h3>
+			</div>
+			<div id="taskpad" class="floatright">
+				', $txt['edit_language_entries_file'], ':
+					<select name="tfid" onchange="if (this.value != -1) document.forms.entry_form.submit();">';
+	foreach ($context['possible_files'] as $id_theme => $theme)
+	{
+		echo '
+						<option value="-1">', $theme['name'], '</option>';
+
+		foreach ($theme['files'] as $file)
+		{
+			echo '
+						<option value="', $id_theme, '+', $file['id'], '"', $file['selected'] ? ' selected="selected"' : '', '> =&gt; ', $file['name'], '</option>';
+		}
+	}
+
+	echo '
+					</select>
+					<input type="hidden" name="', $context['session_var'], '" value="', $context['session_id'], '" />
+					<input type="submit" value="', $txt['go'], '" class="button_submit" />
+			</div>';
+
+	// Is it not writable?
+	// Show an error.
+	if (!empty($context['entries_not_writable_message']))
+		echo '
+			<div id="errorbox">
+				<span class="alert">', $context['entries_not_writable_message'], '</span>
+			</div>';
+
+	// Already have some file entries?
+	if (!empty($context['file_entries']))
+	{
+		echo '
+			<div class="windowbg2">
+				<span class="topslice"><span></span></span>
+				<div class="content">
+					<dl class="settings">';
+
+		$cached = array();
+		foreach ($context['file_entries'] as $entry)
+		{
+			// Do it in two's!
+			if (empty($cached))
+			{
+				$cached = $entry;
+				continue;
+			}
+
+			echo '
+						<dt>
+							<span class="smalltext">', $cached['key'], '</span>
+						</dt>
+						<dd>
+							<span class="smalltext">', $entry['key'], '</span>
+						</dd>
+						<dt>
+							<input type="hidden" name="comp[', $cached['key'], ']" value="', $cached['value'], '" />
+							<textarea name="entry[', $cached['key'], ']" cols="40" rows="', $cached['rows'] < 2 ? 2 : $cached['rows'], '" style="' . ($context['browser']['is_ie8'] ? 'width: 635px; max-width: 96%; min-width: 96%' : 'width: 96%') . ';">', $cached['value'], '</textarea>
+						</dt>
+						<dd>
+							<input type="hidden" name="comp[', $entry['key'], ']" value="', $entry['value'], '" />
+							<textarea name="entry[', $entry['key'], ']" cols="40" rows="', $entry['rows'] < 2 ? 2 : $entry['rows'], '" style="' . ($context['browser']['is_ie8'] ? 'width: 635px; max-width: 96%; min-width: 96%' : 'width: 96%') . ';">', $entry['value'], '</textarea>
+						</dd>';
+			$cached = array();
+		}
+
+		// Odd number?
+		if (!empty($cached))
+		{
+			// Alternative time
+			echo '
+
+						<dt>
+							<span class="smalltext">', $cached['key'], '</span>
+						</dt>
+						<dd>
+						</dd>
+						<dt>
+							<input type="hidden" name="comp[', $cached['key'], ']" value="', $cached['value'], '" />
+							<textarea name="entry[', $cached['key'], ']" cols="40" rows="2" style="' . ($context['browser']['is_ie8'] ? 'width: 635px; max-width: 96%; min-width: 96%' : 'width: 96%') . ';">', $cached['value'], '</textarea>
+						</dt>
+						<dd>
+						</dd>';
+		}
+
+		echo '
+					</dl>
+					<input type="submit" name="save_entries" value="', $txt['save'], '"', !empty($context['entries_not_writable_message']) ? ' disabled="disabled"' : '', ' class="button_submit" />';
+
+		echo '
+				</div>
+				<span class="botslice"><span></span></span>
+			</div>';
+	}
+	echo '
+		</form>
+	</div>
+	<br class="clear" />';
+}
+
+/**
+ * Add a new language
+ *
+ */
+function template_add_language()
+{
+	global $context, $settings, $options, $txt, $scripturl;
+
+	echo '
+	<div id="admincenter">
+		<form action="', $scripturl, '?action=admin;area=languages;sa=add;', $context['session_var'], '=', $context['session_id'], '" method="post" accept-charset="', $context['character_set'], '">
+			<div class="cat_bar">
+				<h3 class="catbg">
+					', $txt['add_language'], '
+				</h3>
+			</div>
+			<div class="windowbg">
+				<span class="topslice"><span></span></span>
+				<div class="content">
+					<fieldset>
+						<legend>', $txt['add_language_smf'], '</legend>
+						<label class="smalltext">', $txt['add_language_smf_browse'], '</label>
+						<input type="text" name="smf_add" size="40" value="', !empty($context['smf_search_term']) ? $context['smf_search_term'] : '', '" class="input_text" />';
+
+	// Do we have some errors? Too bad.
+	if (!empty($context['smf_error']))
+	{
+		// Display a little error box.
+		echo '
+						<div class="smalltext error">', $txt['add_language_error_' . $context['smf_error']], '</div>';
+	}
+
+	echo '
+
+					</fieldset>
+					<div class="righttext">
+						', $context['browser']['is_ie'] ? '<input type="text" name="ie_fix" style="display: none;" class="input_text" /> ' : '', '
+						<input type="submit" name="smf_add_sub" value="', $txt['search'], '" class="button_submit" />
+					</div>
+				</div>
+				<span class="botslice"><span></span></span>
+			</div>
+		';
+
+	// Had some results?
+	if (!empty($context['smf_languages']))
+	{
+		echo '
+			<div class="information">', $txt['add_language_smf_found'], '</div>
+
+				<table class="table_grid" cellspacing="0" width="100%">
+					<thead>
+						<tr class="catbg">
+							<th class="first_th" scope="col">', $txt['name'], '</th>
+							<th scope="col">', $txt['add_language_smf_desc'], '</th>
+							<th scope="col">', $txt['add_language_smf_version'], '</th>
+							<th scope="col">', $txt['add_language_smf_utf8'], '</th>
+							<th class="last_th" scope="col">', $txt['add_language_smf_install'], '</th>
+						</tr>
+					</thead>
+					<tbody>';
+
+		foreach ($context['smf_languages'] as $language)
+		{
+			// Write each language information out.
+			echo '
+						<tr class="windowbg2">
+							<td align="left">', $language['name'], '</td>
+							<td align="left">', $language['description'], '</td>
+							<td align="left">', $language['version'], '</td>
+							<td align="center">', $language['utf8'] ? $txt['yes'] : $txt['no'], '</td>
+							<td align="left"><a href="', $language['link'], '">', $txt['add_language_smf_install'], '</a></td>
+						</tr>';
+		}
+
+		echo '
+					</tbody>
+					</table>';
+	}
+
+	echo '
+		</form>
+	</div>
+	<br class="clear" />';
+}
+
+
+?>