Browse Source

! Refactor our session handler implementation into a separate Session.php file. Load.php is overloaded. :P
! One more compatibility function found on the way: let it be in Subs-Compat.php.
! Code documentation standardization, many files.

Spuds 12 years ago
parent
commit
43a6f4bd7a

+ 1 - 0
SSI.php

@@ -60,6 +60,7 @@ if (substr($sourcedir, 0, 1) == '.' && substr($sourcedir, 1, 1) != '.')
 
 // Load the important includes.
 require_once($sourcedir . '/QueryString.php');
+require_once($sourcedir . '/Session.php');
 require_once($sourcedir . '/Subs.php');
 require_once($sourcedir . '/Errors.php');
 require_once($sourcedir . '/Load.php');

+ 1 - 1
Sources/Class-Graphics.php

@@ -694,7 +694,7 @@ class gif_file
 // 64-bit only functions?
 if (!function_exists('smf_crc32'))
 {
-	include $sourcedir . '/Subs-Compat.php';
+	require_once $sourcedir . '/Subs-Compat.php';
 }
 
 ?>

+ 0 - 1
Sources/Help.php

@@ -64,7 +64,6 @@ function ShowHelp()
 	$context['sub_template'] = 'manual';
 }
 
-// Show some of the more detailed help to give the admin an idea...
 /**
  * Show some of the more detailed help to give the admin an idea...
  * It shows a popup for administrative or user help.

+ 164 - 299
Sources/Load.php

@@ -1,6 +1,8 @@
 <?php
 
 /**
+ * This file has the hefty job of loading information for the forum.
+ *
  * Simple Machines Forum (SMF)
  *
  * @package SMF
@@ -14,116 +16,11 @@
 if (!defined('SMF'))
 	die('Hacking attempt...');
 
-/*	This file has the hefty job of loading information for the forum.  It uses
-	the following functions:
-
-	void reloadSettings()
-		- loads or reloads the $modSettings array.
-		- loads any integration settings, SMF_INTEGRATION_SETTINGS, etc.
-
-	void loadUserSettings()
-		- sets up the $user_info array
-		- assigns $user_info['query_wanna_see_board'] for what boards the user can see.
-		- first checks for cookie or intergration validation.
-		- uses the current session if no integration function or cookie is found.
-		- checks password length, if member is activated and the login span isn't over.
-		- if validation fails for the user, $id_member is set to 0.
-		- updates the last visit time when needed.
-
-	void loadBoard()
-		- sets up the $board_info array for current board information.
-		- if cache is enabled, the $board_info array is stored in cache.
-		- redirects to appropriate post if only message id is requested.
-		- is only used when inside a topic or board.
-		- determines the local moderators for the board.
-		- adds group id 3 if the user is a local moderator for the board they are in.
-		- prevents access if user is not in proper group nor a local moderator of the board.
-
-	void loadPermissions()
-		// !!!
-
-	array loadMemberData(array members, bool is_name = false, string set = 'normal')
-		// !!!
-
-	bool loadMemberContext(int id_member)
-		// !!!
-
-	void loadTheme(int id_theme = auto_detect)
-		// !!!
-
-	void loadTemplate(string template_name, array style_sheets = array(), bool fatal = true)
-		- loads a template file with the name template_name from the current,
-		  default, or base theme.
-		- uses the template_include() function to include the file.
-		- detects a wrong default theme directory and tries to work around it.
-		- if fatal is true, dies with an error message if the template cannot
-		  be found.
-
-	void loadSubTemplate(string sub_template_name, bool fatal = false)
-		- loads the sub template specified by sub_template_name, which must be
-		  in an already-loaded template.
-		- if ?debug is in the query string, shows administrators a marker after
-		  every sub template for debugging purposes.
-
-	string loadLanguage(string template_name, string language = default, bool fatal = true, bool force_reload = false)
-		// !!!
-
-	array getBoardParents(int id_parent)
-		- finds all the parents of id_parent, and that board itself.
-		- additionally detects the moderators of said boards.
-		- returns an array of information about the boards found.
-
-	string &censorText(string &text, bool force = false)
-		- censors the passed string.
-		- if the theme setting allow_no_censored is on, and the theme option
-		  show_no_censored is enabled, does not censor - unless force is set.
-		- caches the list of censored words to reduce parsing.
-
-	void template_include(string filename, bool only_once = false)
-		- loads the template or language file specified by filename.
-		- if once is true, only includes the file once (like include_once.)
-		- uses eval unless disableTemplateEval is enabled.
-		- outputs a parse error if the file did not exist or contained errors.
-		- attempts to detect the error and line, and show detailed information.
-
-	void loadSession()
-		// !!!
-
-	void loadDatabase()
-		- takes care of mysql_set_mode, if set.
-		// !!!
-
-	bool sessionOpen(string session_save_path, string session_name)
-	bool sessionClose()
-	bool sessionRead(string session_id)
-	bool sessionWrite(string session_id, string data)
-	bool sessionDestroy(string session_id)
-	bool sessionGC(int max_lifetime)
-		- implementations of PHP's session API.
-		- handle the session data in the database (more scalable.)
-		- use the databaseSession_lifetime setting for garbage collection.
-		- set by loadSession().
-
-	void cache_put_data(string key, mixed value, int ttl = 120)
-		- puts value in the cache under key for ttl seconds.
-		- may "miss" so shouldn't be depended on, and may go to any of many
-		  various caching servers.
-		- supports eAccelerator, Turck MMCache, ZPS, and memcached.
-
-	mixed cache_get_data(string key, int ttl = 120)
-		- gets the value from the cache specified by key, so long as it is not
-		  older than ttl seconds.
-		- may often "miss", so shouldn't be depended on.
-		- supports the same as cache_put_data().
-
-	void get_memcached_server(int recursion_level = 3)
-		- used by cache_get_data() and cache_put_data().
-		- attempts to connect to a random server in the cache_memcached
-		  setting.
-		- recursively calls itself up to recursion_level times.
-*/
-
-// Load the $modSettings array.
+/**
+ * Load the $modSettings array.
+ * @todo okay question of the day: why a function loading settings is called
+ * reloadSettings()
+ */
 function reloadSettings()
 {
 	global $modSettings, $boarddir, $smcFunc, $txt, $db_character_set, $context, $sourcedir;
@@ -296,7 +193,18 @@ function reloadSettings()
 	call_integration_hook('integrate_pre_load');
 }
 
-// Load all the important user information...
+
+/**
+ * Load all the important user information.
+ * What it does:
+ * 	- sets up the $user_info array
+	- assigns $user_info['query_wanna_see_board'] for what boards the user can see.
+	- first checks for cookie or integration validation.
+	- uses the current session if no integration function or cookie is found.
+	- checks password length, if member is activated and the login span isn't over.
+		- if validation fails for the user, $id_member is set to 0.
+		- updates the last visit time when needed.
+ */
 function loadUserSettings()
 {
 	global $modSettings, $user_settings, $sourcedir, $smcFunc;
@@ -545,7 +453,17 @@ function loadUserSettings()
 		$user_info['query_wanna_see_board'] = '(' . $user_info['query_see_board'] . ' AND b.id_board NOT IN (' . implode(',', $user_info['ignoreboards']) . '))';
 }
 
-// Check for moderators and see if they have access to the board.
+/**
+ * Check for moderators and see if they have access to the board.
+ * What it does:
+ * - sets up the $board_info array for current board information.
+ * - if cache is enabled, the $board_info array is stored in cache.
+ * - redirects to appropriate post if only message id is requested.
+ * - is only used when inside a topic or board.
+ * - determines the local moderators for the board.
+ * - adds group id 3 if the user is a local moderator for the board they are in.
+ * - prevents access if user is not in proper group nor a local moderator of the board.
+ */
 function loadBoard()
 {
 	global $txt, $scripturl, $context, $modSettings;
@@ -802,7 +720,9 @@ function loadBoard()
 		$user_info['groups'][] = 3;
 }
 
-// Load this user's permissions.
+/**
+ * Load this user's permissions.
+ */
 function loadPermissions()
 {
 	global $user_info, $board, $board_info, $modSettings, $smcFunc, $sourcedir;
@@ -915,7 +835,13 @@ function loadPermissions()
 	}
 }
 
-// Loads an array of users' data by ID or member_name.
+/**
+ * Loads an array of users' data by ID or member_name.
+ *
+ * @param $users
+ * @param $is_name
+ * @param string $set = 'normal'
+ */
 function loadMemberData($users, $is_name = false, $set = 'normal')
 {
 	global $user_profile, $modSettings, $board_info, $smcFunc;
@@ -1072,7 +998,12 @@ function loadMemberData($users, $is_name = false, $set = 'normal')
 	return empty($loaded_ids) ? false : $loaded_ids;
 }
 
-// Loads the user's basic values... meant for template/theme usage.
+/**
+ * Loads the user's basic values... meant for template/theme usage.
+ *
+ * @param $user
+ * @param bool $display_custom_fields
+ */
 function loadMemberContext($user, $display_custom_fields = false)
 {
 	global $memberContext, $user_profile, $txt, $scripturl, $user_info;
@@ -1271,6 +1202,9 @@ function loadMemberContext($user, $display_custom_fields = false)
 	return true;
 }
 
+/**
+ * This function is... detecting the browser, right.
+ */
 function detectBrowser()
 {
 	global $context, $user_info;
@@ -1321,7 +1255,12 @@ function detectBrowser()
 		$context['browser']['possibly_robot'] = false;
 }
 
-// Load a theme, by ID.
+/**
+ * Load a theme, by ID.
+ *
+ * @param int $id_theme = 0
+ * @parambool $initialize = true
+ */
 function loadTheme($id_theme = 0, $initialize = true)
 {
 	global $user_info, $user_settings, $board_info, $sc, $boarddir;
@@ -1768,7 +1707,18 @@ function loadTheme($id_theme = 0, $initialize = true)
 	$context['theme_loaded'] = true;
 }
 
-// Load a template - if the theme doesn't include it, use the default.
+/**
+ * Load a template - if the theme doesn't include it, use the default.
+ * What this function does:
+ * - loads a template file with the name template_name from the current, default,
+ *  or base theme.
+ *  - uses the template_include() function to include the file.
+ *  - detects a wrong default theme directory and tries to work around it.
+ *  - if fatal is true, dies with an error message if the template cannot be found.
+ * @param string $template_name
+ * @param array $style_sheets = array()
+ * @param bool $fatal = true
+ */
 function loadTemplate($template_name, $style_sheets = array(), $fatal = true)
 {
 	global $context, $settings, $txt, $scripturl, $boarddir, $db_show_debug;
@@ -1849,7 +1799,18 @@ function loadTemplate($template_name, $style_sheets = array(), $fatal = true)
 		return false;
 }
 
-// Load a sub template... fatal is for templates that shouldn't get a 'pretty' error screen.
+
+/**
+ * Load a sub-template.
+ * What it does:
+ * 	- loads the sub template specified by sub_template_name, which must be in an already-loaded
+ *  template.
+ *  - if ?debug is in the query string, shows administrators a marker after every sub template
+ *   for debugging purposes.
+ *   @todo get rid of reading $_REQUEST directly
+ * @param string $sub_template_name
+ * @param bool $fatal = false, $fatal = true is for templates that shouldn't get a 'pretty' error screen.
+ */
 function loadSubTemplate($sub_template_name, $fatal = false)
 {
 	global $context, $settings, $options, $txt, $db_show_debug;
@@ -1874,7 +1835,14 @@ function loadSubTemplate($sub_template_name, $fatal = false)
 	}
 }
 
-// Load a language file.  Tries the current and default themes as well as the user and global languages.
+/**
+ *  Load a language file.  Tries the current and default themes as well as the user and global languages.
+ *
+ * @param string $template_name
+ * @param string $lang
+ * @param bool $fatal = true
+ * @param bool $force_reload = false
+ */
 function loadLanguage($template_name, $lang = '', $fatal = true, $force_reload = false)
 {
 	global $user_info, $language, $settings, $context, $modSettings;
@@ -1966,7 +1934,14 @@ function loadLanguage($template_name, $lang = '', $fatal = true, $force_reload =
 	return $lang;
 }
 
-// Get all parent boards (requires first parent as parameter)
+/**
+ * Get all parent boards (requires first parent as parameter)
+ * It finds all the parents of id_parent, and that board itself.
+ * Additionally, it detects the moderators of said boards.
+ *
+ * @param int $id_parent
+ * @return an array of information about the boards found.
+ */
 function getBoardParents($id_parent)
 {
 	global $scripturl, $smcFunc;
@@ -2028,7 +2003,13 @@ function getBoardParents($id_parent)
 	return $boards;
 }
 
-// Attempt to reload our languages.
+/**
+ * Attempt to reload our known languages.
+ * It will try to choose only utf8 or non-utf8 languages.
+ *
+ * @param bool $use_cache = true
+ * @param bool $favor_utf8 = true
+ */
 function getLanguages($use_cache = true, $favor_utf8 = true)
 {
 	global $context, $smcFunc, $settings, $modSettings;
@@ -2093,7 +2074,17 @@ function getLanguages($use_cache = true, $favor_utf8 = true)
 	return $context['languages'];
 }
 
-// Replace all vulgar words with respective proper words. (substring or whole words..)
+/**
+ * Replace all vulgar words with respective proper words. (substring or whole words..)
+ * What this function does:
+ *  - it censors the passed string.
+ *  - if the theme setting allow_no_censored is on, and the theme option
+ *  	  show_no_censored is enabled, does not censor - unless force is set.
+ *  - it caches the list of censored words to reduce parsing.
+ * @todo what is this function doing here?
+ * @param $text
+ * @param $force
+ */
 function &censorText(&$text, $force = false)
 {
 	global $modSettings, $options, $settings, $txt;
@@ -2127,7 +2118,16 @@ function &censorText(&$text, $force = false)
 	return $text;
 }
 
-// Load the template/language file using eval or require? (with eval we can show an error message!)
+/**
+ * Load the template/language file using eval or require? (with eval we can show an error message!)
+ * 	- loads the template or language file specified by filename.
+ * 	- uses eval unless disableTemplateEval is enabled.
+ * 	- outputs a parse error if the file did not exist or contained errors.
+ * 	- attempts to detect the error and line, and show detailed information.
+ *
+ * @param string $filename
+ * @param bool $once = false, if true only includes the file once (like include_once)
+ */
 function template_include($filename, $once = false)
 {
 	global $context, $settings, $options, $txt, $scripturl, $modSettings;
@@ -2320,181 +2320,9 @@ function template_include($filename, $once = false)
 	}
 }
 
-// Attempt to start the session, unless it already has been.
-function loadSession()
-{
-	global $HTTP_SESSION_VARS, $modSettings, $boardurl, $sc;
-
-	// Attempt to change a few PHP settings.
-	@ini_set('session.use_cookies', true);
-	@ini_set('session.use_only_cookies', false);
-	@ini_set('url_rewriter.tags', '');
-	@ini_set('session.use_trans_sid', false);
-	@ini_set('arg_separator.output', '&amp;');
-
-	if (!empty($modSettings['globalCookies']))
-	{
-		$parsed_url = parse_url($boardurl);
-
-		if (preg_match('~^\d{1,3}(\.\d{1,3}){3}$~', $parsed_url['host']) == 0 && preg_match('~(?:[^\.]+\.)?([^\.]{2,}\..+)\z~i', $parsed_url['host'], $parts) == 1)
-			@ini_set('session.cookie_domain', '.' . $parts[1]);
-	}
-	// !!! Set the session cookie path?
-
-	// If it's already been started... probably best to skip this.
-	if ((@ini_get('session.auto_start') == 1 && !empty($modSettings['databaseSession_enable'])) || session_id() == '')
-	{
-		// Attempt to end the already-started session.
-		if (@ini_get('session.auto_start') == 1)
-			@session_write_close();
-
-		// This is here to stop people from using bad junky PHPSESSIDs.
-		if (isset($_REQUEST[session_name()]) && preg_match('~^[A-Za-z0-9]{16,32}$~', $_REQUEST[session_name()]) == 0 && !isset($_COOKIE[session_name()]))
-		{
-			$session_id = md5(md5('smf_sess_' . time()) . mt_rand());
-			$_REQUEST[session_name()] = $session_id;
-			$_GET[session_name()] = $session_id;
-			$_POST[session_name()] = $session_id;
-		}
-
-		// Use database sessions? (they don't work in 4.1.x!)
-		if (!empty($modSettings['databaseSession_enable']) && @version_compare(PHP_VERSION, '4.2.0') != -1)
-		{
-			session_set_save_handler('sessionOpen', 'sessionClose', 'sessionRead', 'sessionWrite', 'sessionDestroy', 'sessionGC');
-			@ini_set('session.gc_probability', '1');
-		}
-		elseif (@ini_get('session.gc_maxlifetime') <= 1440 && !empty($modSettings['databaseSession_lifetime']))
-			@ini_set('session.gc_maxlifetime', max($modSettings['databaseSession_lifetime'], 60));
-
-		// Use cache setting sessions?
-		if (empty($modSettings['databaseSession_enable']) && !empty($modSettings['cache_enable']) && php_sapi_name() != 'cli')
-		{
-			if (function_exists('mmcache_set_session_handlers'))
-				mmcache_set_session_handlers();
-			elseif (function_exists('eaccelerator_set_session_handlers'))
-				eaccelerator_set_session_handlers();
-		}
-
-		session_start();
-
-		// Change it so the cache settings are a little looser than default.
-		if (!empty($modSettings['databaseSession_loose']))
-			header('Cache-Control: private');
-	}
-
-	// While PHP 4.1.x should use $_SESSION, it seems to need this to do it right.
-	if (@version_compare(PHP_VERSION, '4.2.0') == -1)
-		$HTTP_SESSION_VARS['php_412_bugfix'] = true;
-
-	// Set the randomly generated code.
-	if (!isset($_SESSION['session_var']))
-	{
-		$_SESSION['session_value'] = md5(session_id() . mt_rand());
-		$_SESSION['session_var'] = substr(preg_replace('~^\d+~', '', sha1(mt_rand() . session_id() . mt_rand())), 0, rand(7, 12));
-	}
-	$sc = $_SESSION['session_value'];
-}
-
-function sessionOpen($save_path, $session_name)
-{
-	return true;
-}
-
-function sessionClose()
-{
-	return true;
-}
-
-function sessionRead($session_id)
-{
-	global $smcFunc;
-
-	if (preg_match('~^[A-Za-z0-9]{16,32}$~', $session_id) == 0)
-		return false;
-
-	// Look for it in the database.
-	$result = $smcFunc['db_query']('', '
-		SELECT data
-		FROM {db_prefix}sessions
-		WHERE session_id = {string:session_id}
-		LIMIT 1',
-		array(
-			'session_id' => $session_id,
-		)
-	);
-	list ($sess_data) = $smcFunc['db_fetch_row']($result);
-	$smcFunc['db_free_result']($result);
-
-	return $sess_data;
-}
-
-function sessionWrite($session_id, $data)
-{
-	global $smcFunc;
-
-	if (preg_match('~^[A-Za-z0-9]{16,32}$~', $session_id) == 0)
-		return false;
-
-	// First try to update an existing row...
-	$result = $smcFunc['db_query']('', '
-		UPDATE {db_prefix}sessions
-		SET data = {string:data}, last_update = {int:last_update}
-		WHERE session_id = {string:session_id}',
-		array(
-			'last_update' => time(),
-			'data' => $data,
-			'session_id' => $session_id,
-		)
-	);
-
-	// If that didn't work, try inserting a new one.
-	if ($smcFunc['db_affected_rows']() == 0)
-		$result = $smcFunc['db_insert']('ignore',
-			'{db_prefix}sessions',
-			array('session_id' => 'string', 'data' => 'string', 'last_update' => 'int'),
-			array($session_id, $data, time()),
-			array('session_id')
-		);
-
-	return $result;
-}
-
-function sessionDestroy($session_id)
-{
-	global $smcFunc;
-
-	if (preg_match('~^[A-Za-z0-9]{16,32}$~', $session_id) == 0)
-		return false;
-
-	// Just delete the row...
-	return $smcFunc['db_query']('', '
-		DELETE FROM {db_prefix}sessions
-		WHERE session_id = {string:session_id}',
-		array(
-			'session_id' => $session_id,
-		)
-	);
-}
-
-function sessionGC($max_lifetime)
-{
-	global $modSettings, $smcFunc;
-
-	// Just set to the default or lower?  Ignore it for a higher value. (hopefully)
-	if (!empty($modSettings['databaseSession_lifetime']) && ($max_lifetime <= 1440 || $modSettings['databaseSession_lifetime'] > $max_lifetime))
-		$max_lifetime = max($modSettings['databaseSession_lifetime'], 60);
-
-	// Clean up ;).
-	return $smcFunc['db_query']('', '
-		DELETE FROM {db_prefix}sessions
-		WHERE last_update < {int:last_update}',
-		array(
-			'last_update' => time() - $max_lifetime,
-		)
-	);
-}
-
-// Load up a database connection.
+/**
+ * Initialize a database connection.
+ */
 function loadDatabase()
 {
 	global $db_persist, $db_connection, $db_server, $db_user, $db_passwd;
@@ -2524,7 +2352,16 @@ function loadDatabase()
 		db_fix_prefix($db_prefix, $db_name);
 }
 
-// Try to retrieve a cache entry. On failure, call the appropriate function.
+/**
+ * Try to retrieve a cache entry. On failure, call the appropriate function.
+ * @todo find a better place for cache implementation
+ *
+ * @param $key
+ * @param $file
+ * @param $function
+ * @param $params
+ * @param int $level = 1
+ */
 function cache_quick_get($key, $file, $function, $params, $level = 1)
 {
 	global $modSettings, $sourcedir;
@@ -2551,6 +2388,16 @@ function cache_quick_get($key, $file, $function, $params, $level = 1)
 	return $cache_block['data'];
 }
 
+/**
+ * Puts value in the cache under key for ttl seconds.
+ * It may "miss" so shouldn't be depended on, and may go to any of many
+ * various caching servers.
+ * It supports eAccelerator, Turck MMCache, APC, ZPS, and memcached.
+ *
+ * @param string $key
+ * @param mixed $value
+ * @param int $ttl = 120
+ */
 function cache_put_data($key, $value, $ttl = 120)
 {
 	global $boardurl, $sourcedir, $modSettings, $memcached;
@@ -2651,6 +2498,16 @@ function cache_put_data($key, $value, $ttl = 120)
 		$cache_hits[$cache_count]['t'] = array_sum(explode(' ', microtime())) - array_sum(explode(' ', $st));
 }
 
+/**
+ * Gets the value from the cache specified by key, so long as it is not older
+ * than ttl seconds.
+ * It may often "miss", so shouldn't be depended on.
+ * It supports the same as cache_put_data().
+ *
+ * @param string $key
+ * @param int $ttl = 120
+ * @return string
+ */
 function cache_get_data($key, $ttl = 120)
 {
 	global $boardurl, $sourcedir, $modSettings, $memcached;
@@ -2717,6 +2574,14 @@ function cache_get_data($key, $ttl = 120)
 		return @unserialize($value);
 }
 
+/**
+ * Get memcache servers.
+ * This function is used by cache_get_data() and cache_put_data().
+ * It attempts to connect to a random server in the cache_memcached setting.
+ * It recursively calls itself up to recursion_level times.
+ *
+ * @param int $level = 3
+ */
 function get_memcached_server($level = 3)
 {
 	global $modSettings, $memcached, $db_persist;

+ 22 - 19
Sources/LockTopic.php

@@ -1,6 +1,9 @@
 <?php
 
 /**
+ * This file only takes care of two things - locking and sticky-ing.
+ * @todo and it's called after one of those. :P
+ *
  * Simple Machines Forum (SMF)
  *
  * @package SMF
@@ -14,25 +17,16 @@
 if (!defined('SMF'))
 	die('Hacking attempt...');
 
-/*	This file only takes care of two things - locking and stickying.
-
-	void LockTopic()
-		- locks a topic, toggles between locked/unlocked/admin locked.
-		- only admins can unlock topics locked by other admins.
-		- requires the lock_own or lock_any permission.
-		- logs the action to the moderator log.
-		- returns to the topic after it is done.
-		- accessed via ?action=lock.
-
-	void Sticky()
-		- stickies a topic - toggles between sticky and normal.
-		- requires the make_sticky permission.
-		- adds an entry to the moderator log.
-		- when done, sends the user back to the topic.
-		- accessed via ?action=sticky.
+/**
+ * Locks a topic... either by way of a moderator or the topic starter.
+ * What this does:
+ *  - locks a topic, toggles between locked/unlocked/admin locked.
+ *  - only admins can unlock topics locked by other admins.
+ *  - requires the lock_own or lock_any permission.
+ *  - logs the action to the moderator log.
+ *  - returns to the topic after it is done.
+ *  - it is accessed via ?action=lock.
 */
-
-// Locks a topic... either by way of a moderator or the topic starter.
 function LockTopic()
 {
 	global $topic, $user_info, $sourcedir, $board, $smcFunc;
@@ -100,7 +94,16 @@ function LockTopic()
 	redirectexit('topic=' . $topic . '.' . $_REQUEST['start'] . (WIRELESS ? ';moderate' : ''));
 }
 
-// Sticky a topic.  Can't be done by topic starters - that would be annoying!
+/**
+ * Sticky a topic.
+ * Can't be done by topic starters - that would be annoying!
+ * What this does:
+ *  - stickies a topic - toggles between sticky and normal.
+ *  - requires the make_sticky permission.
+ *  - adds an entry to the moderator log.
+ *  - when done, sends the user back to the topic.
+ *  - accessed via ?action=sticky.
+ */
 function Sticky()
 {
 	global $modSettings, $topic, $board, $sourcedir, $smcFunc;

+ 61 - 45
Sources/LogInOut.php

@@ -1,6 +1,9 @@
 <?php
 
 /**
+ * This file is concerned pretty entirely, as you see from its name, with
+ * logging in and out members, and the validation of that.
+ *
  * Simple Machines Forum (SMF)
  *
  * @package SMF
@@ -14,47 +17,15 @@
 if (!defined('SMF'))
 	die('Hacking attempt...');
 
-/*	This file is concerned pretty entirely, as you see from its name, with
-	logging in and out members, and the validation of that.  It contains:
-
-	void Login()
-		- shows a page for the user to type in their username and password.
-		- caches the referring URL in $_SESSION['login_url'].
-		- uses the Login template and language file with the login sub
-		  template.
-		- if you are using a wireless device, uses the protocol_login sub
-		  template in the Wireless template.
-		- accessed from ?action=login.
-
-	void Login2()
-		- actually logs you in and checks that login was successful.
-		- employs protection against a specific IP or user trying to brute
-		  force a login to an account.
-		- on error, uses the same templates Login() uses.
-		- upgrades password encryption on login, if necessary.
-		- after successful login, redirects you to $_SESSION['login_url'].
-		- accessed from ?action=login2, by forms.
-
-	void Logout(bool internal = false)
-		- logs the current user out of their account.
-		- requires that the session hash is sent as well, to prevent automatic
-		  logouts by images or javascript.
-		- doesn't check the session if internal is true.
-		- redirects back to $_SESSION['logout_url'], if it exists.
-		- accessed via ?action=logout;session_var=...
-
-	string md5_hmac(string data, string key)
-		- old style SMF 1.0.x/YaBB SE 1.5.x hashing.
-		- returns the HMAC MD5 of data with key.
-
-	string phpBB3_password_check(string passwd, string passwd_hash)
-		- custom encryption for phpBB3 based passwords.
-
-	void validatePasswordFlood(id_member, password_flood_value = false, was_correct = false)
-		- this function helps protect against brute force attacks on a member's password.
-*/
-
-// Ask them for their login information.
+/**
+ * Ask them for their login information. (shows a page for the user to type
+ *  in their username and password.)
+ *  It caches the referring URL in $_SESSION['login_url'].
+ *  It is accessed from ?action=login.
+ *  @uses Login template and language file with the login sub-template.
+ *  @uses the protocol_login sub-template in the Wireless template,
+ *   if you are using a wireless device
+ */
 function Login()
 {
 	global $txt, $context, $scripturl;
@@ -89,7 +60,17 @@ function Login()
 		unset($_SESSION['login_url']);
 }
 
-// Perform the actual logging-in.
+/**
+ * Actually logs you in.
+ * What it does:
+ * - checks credentials and checks that login was successful.
+ * - it employs protection against a specific IP or user trying to brute force
+ *  a login to an account.
+ * - upgrades password encryption on login, if necessary.
+ * - after successful login, redirects you to $_SESSION['login_url'].
+ * - accessed from ?action=login2, by forms.
+ * On error, uses the same templates Login() uses.
+ */
 function Login2()
 {
 	global $txt, $scripturl, $user_info, $user_settings, $smcFunc;
@@ -416,6 +397,9 @@ function Login2()
 	DoLogin();
 }
 
+/**
+ * Check activation status of the current user.
+ */
 function checkActivation()
 {
 	global $context, $txt, $scripturl, $user_settings, $modSettings;
@@ -462,6 +446,9 @@ function checkActivation()
 	return true;
 }
 
+/**
+ * Perform the logging in. (set cookie, call hooks, etc)
+ */
 function DoLogin()
 {
 	global $txt, $scripturl, $user_info, $user_settings, $smcFunc;
@@ -537,7 +524,16 @@ function DoLogin()
 		redirectexit('action=logout;' . $context['session_var'] . '=' . $context['session_id'], $context['server']['needs_login_fix']);
 }
 
-// Log the user out.
+/**
+ * Logs the current user out of their account.
+ * It requires that the session hash is sent as well, to prevent automatic logouts
+ *  by images or javascript.
+ * It redirects back to $_SESSION['logout_url'], if it exists.
+ * It is accessed via ?action=logout;session_var=...
+ *
+ * @param bool $internal, if true, it doesn't check the session
+ * @param $redirect
+ */
 function Logout($internal = false, $redirect = true)
 {
 	global $sourcedir, $user_info, $user_settings, $context, $modSettings, $smcFunc;
@@ -594,7 +590,13 @@ function Logout($internal = false, $redirect = true)
 	}
 }
 
-// MD5 Encryption used for older passwords.
+/**
+ * MD5 Encryption used for older passwords. (SMF 1.0.x/YaBB SE 1.5.x hashing)
+ *
+ * @param string $data
+ * @param string $key
+ * @return string, the HMAC MD5 of data with key
+ */
 function md5_hmac($data, $key)
 {
 	$key = str_pad(strlen($key) <= 64 ? $key : pack('H*', md5($key)), 64, chr(0x00));
@@ -602,6 +604,13 @@ function md5_hmac($data, $key)
 }
 
 // Special encryption used by phpBB3.
+/**
+ * Custom encryption for phpBB3 based passwords.
+ *
+ * @param string $passwd
+ * @param string $passwd_hash
+ * @return string
+ */
 function phpBB3_password_check($passwd, $passwd_hash)
 {
 	// Too long or too short?
@@ -661,7 +670,14 @@ function phpBB3_password_check($passwd, $passwd_hash)
 	return $output;
 }
 
-// This protects against brute force attacks on a member's password. Importantly even if the password was right we DON'T TELL THEM!
+/**
+ * This protects against brute force attacks on a member's password.
+ * Importantly, even if the password was right we DON'T TELL THEM!
+ *
+ * @param $id_member
+ * @param $password_flood_value = false
+ * @param $was_correct = false
+ */
 function validatePasswordFlood($id_member, $password_flood_value = false, $was_correct = false)
 {
 	global $smcFunc, $cookiename, $sourcedir;

+ 135 - 97
Sources/ManageAttachments.php

@@ -1,6 +1,9 @@
 <?php
 
 /**
+ * This file doing the job of attachments and avatars maintenance and management.
+ * @todo refactor as controller-model
+ *
  * Simple Machines Forum (SMF)
  *
  * @package SMF
@@ -14,95 +17,17 @@
 if (!defined('SMF'))
 	die('Hacking attempt...');
 
-/* /!!!
-
-	void ManageAttachments()
-		- main 'Attachments and Avatars' center function.
-		- entry point for index.php?action=admin;area=manageattachments.
-		- requires the manage_attachments permission.
-		- load the ManageAttachments template.
-		- uses the Admin language file.
-		- uses the template layer 'manage_files' for showing the tab bar.
-		- calls a function based on the sub-action.
-
-	void ManageAttachmentSettings()
-		- show/change attachment settings.
-		- default sub action for the 'Attachments and Avatars' center.
-		- uses the 'attachments' sub template.
-		- called by index.php?action=admin;area=manageattachments;sa=attachements.
-
-	void ManageAvatarSettings()
-		- show/change avatar settings.
-		- called by index.php?action=admin;area=manageattachments;sa=avatars.
-		- uses the 'avatars' sub template.
-		- show/set permissions for permissions: 'profile_server_avatar',
-		  'profile_upload_avatar' and 'profile_remote_avatar'.
-
-	void BrowseFiles()
-		- show a list of attachment or avatar files.
-		- called by ?action=admin;area=manageattachments;sa=browse for attachments and
-		  ?action=admin;area=manageattachments;sa=browse;avatars for avatars.
-		- uses the 'browse' sub template
-		- allows sorting by name, date, size and member.
-		- paginates results.
-
-	void MaintainFiles()
-		- show several file maintenance options.
-		- called by ?action=admin;area=manageattachments;sa=maintain.
-		- uses the 'maintain' sub template.
-		- calculates file statistics (total file size, number of attachments,
-		  number of avatars, attachment space available).
-
-	void MoveAvatars()
-		- move avatars from or to the attachment directory.
-		- called from the maintenance screen by
-		  ?action=admin;area=manageattachments;sa=moveAvatars.
-
-	void RemoveAttachmentByAge()
-		- remove attachments older than a given age.
-		- called from the maintenance screen by
-		  ?action=admin;area=manageattachments;sa=byAge.
-		- optionally adds a certain text to the messages the attachments were
-		  removed from.
-
-	void RemoveAttachmentBySize()
-		- remove attachments larger than a given size.
-		- called from the maintenance screen by
-		  ?action=admin;area=manageattachments;sa=bySize.
-		- optionally adds a certain text to the messages the attachments were
-		  removed from.
-
-	void RemoveAttachment()
-		- remove a selection of attachments or avatars.
-		- called from the browse screen as submitted form by
-		  ?action=admin;area=manageattachments;sa=remove
-
-	void RemoveAllAttachments()
-		- removes all attachments in a single click
-		- called from the maintenance screen by
-		  ?action=admin;area=manageattachments;sa=removeall.
-
-	array removeAttachments(array condition, string query_type = '', bool return_affected_messages = false, bool autoThumbRemoval = true)
-		- removes attachments or avatars based on a given query condition.
-		- called by several remove avatar/attachment functions in this file.
-		- removes attachments based that match the $condition.
-		- allows query_types 'messages' and 'members', whichever is need by the
-		  $condition parameter.
-
-	void RepairAttachments()
-		// !!!
-
-	void PauseAttachmentMaintenance()
-		// !!!
-
-	void ApproveAttach()
-		// !!!
-
-	void ApproveAttachments()
-		// !!!
-*/
-
-// The main attachment management function.
+/**
+ * The main 'Attachments and Avatars' management function.
+ * This function is the entry point for index.php?action=admin;area=manageattachments
+ * and it calls a function based on the sub-action.
+ * It requires the manage_attachments permission.
+ *
+ * @uses ManageAttachments template.
+ * @uses Admin language file.
+ * @uses template layer 'manage_files' for showing the tab bar.
+ *
+ */
 function ManageAttachments()
 {
 	global $txt, $modSettings, $scripturl, $context, $options;
@@ -148,6 +73,15 @@ function ManageAttachments()
 	$subActions[$context['sub_action']]();
 }
 
+/**
+ * Allows to show/change attachment settings.
+ * This is the default sub-action of the 'Attachments and Avatars' center.
+ * Called by index.php?action=admin;area=manageattachments;sa=attachements.
+ *
+ * @param bool $return_config = false
+ * @uses 'attachments' sub template.
+ */
+
 function ManageAttachmentSettings($return_config = false)
 {
 	global $txt, $modSettings, $scripturl, $context, $options, $sourcedir;
@@ -211,6 +145,15 @@ function ManageAttachmentSettings($return_config = false)
 	$context['sub_template'] = 'show_settings';
 }
 
+/**
+ * This allows to show/change avatar settings.
+ * Called by index.php?action=admin;area=manageattachments;sa=avatars.
+ * Show/set permissions for permissions: 'profile_server_avatar',
+ * 	'profile_upload_avatar' and 'profile_remote_avatar'.
+ *
+ * @param $return_config
+ * @uses 'avatars' sub template.
+ */
 function ManageAvatarSettings($return_config = false)
 {
 	global $txt, $context, $modSettings, $sourcedir, $scripturl;
@@ -291,6 +234,15 @@ function ManageAvatarSettings($return_config = false)
 	$context['sub_template'] = 'show_settings';
 }
 
+/**
+ * Show a list of attachment or avatar files.
+ * Called by ?action=admin;area=manageattachments;sa=browse for attachments
+ *  and ?action=admin;area=manageattachments;sa=browse;avatars for avatars.
+ * Allows sorting by name, date, size and member.
+ * Paginates results.
+ *
+ *  @uses the 'browse' sub template
+ */
 function BrowseFiles()
 {
 	global $context, $txt, $scripturl, $options, $modSettings;
@@ -481,6 +433,13 @@ function BrowseFiles()
 	createList($listOptions);
 }
 
+/**
+ * @todo this doesn't belong here.
+ * @param $start
+ * @param $items_per_page
+ * @param $sort
+ * @param $browse_type
+ */
 function list_getFiles($start, $items_per_page, $sort, $browse_type)
 {
 	global $smcFunc, $txt;
@@ -534,6 +493,10 @@ function list_getFiles($start, $items_per_page, $sort, $browse_type)
 	return $files;
 }
 
+/**
+ * @todo refactor these model functions.
+ * @param $browse_type
+ */
 function list_getNumFiles($browse_type)
 {
 	global $smcFunc;
@@ -569,6 +532,14 @@ function list_getNumFiles($browse_type)
 	return $num_files;
 }
 
+/**
+ * Show several file maintenance options.
+ * Called by ?action=admin;area=manageattachments;sa=maintain.
+ * Calculates file statistics (total file size, number of attachments,
+ * number of avatars, attachment space available).
+ *
+ * @uses the 'maintain' sub template.
+ */
 function MaintainFiles()
 {
 	global $context, $modSettings, $txt, $smcFunc;
@@ -641,7 +612,10 @@ function MaintainFiles()
 	$context['attach_multiple_dirs'] = !empty($modSettings['currentAttachmentUploadDir']);
 }
 
-// !!! Not implemented yet.
+/**
+ * Move avatars from their current location, to the custom_avatar_dir folder.
+ * Called from the maintenance screen by ?action=admin;area=manageattachments;sa=moveAvatars.
+ */
 function MoveAvatars()
 {
 	global $modSettings, $smcFunc;
@@ -691,6 +665,14 @@ function MoveAvatars()
 	redirectexit('action=admin;area=manageattachments;sa=maintenance');
 }
 
+/**
+ * Remove attachments older than a given age.
+ * Called from the maintenance screen by
+ *   ?action=admin;area=manageattachments;sa=byAge.
+ * It optionally adds a certain text to the messages the attachments
+ *  were removed from.
+ *  @todo refactor this silly superglobals use...
+ */
 function RemoveAttachmentByAge()
 {
 	global $modSettings, $smcFunc;
@@ -725,6 +707,13 @@ function RemoveAttachmentByAge()
 	redirectexit('action=admin;area=manageattachments' . (empty($_REQUEST['avatars']) ? ';sa=maintenance' : ';avatars'));
 }
 
+/**
+ * Remove attachments larger than a given size.
+ * Called from the maintenance screen by
+ *  ?action=admin;area=manageattachments;sa=bySize.
+ * Optionally adds a certain text to the messages the attachments were
+ * 	removed from.
+ */
 function RemoveAttachmentBySize()
 {
 	global $modSettings, $smcFunc;
@@ -749,6 +738,11 @@ function RemoveAttachmentBySize()
 	redirectexit('action=admin;area=manageattachments;sa=maintenance');
 }
 
+/**
+ * Remove a selection of attachments or avatars.
+ * Called from the browse screen as submitted form by
+ *  ?action=admin;area=manageattachments;sa=remove
+ */
 function RemoveAttachment()
 {
 	global $modSettings, $txt, $smcFunc;
@@ -786,7 +780,11 @@ function RemoveAttachment()
 	redirectexit('action=admin;area=manageattachments;sa=browse;' . $_REQUEST['type'] . ';sort=' . $_GET['sort'] . (isset($_GET['desc']) ? ';desc' : '') . ';start=' . $_REQUEST['start']);
 }
 
-// !!! Not implemented (yet?)
+/**
+ * Removes all attachments in a single click
+ * Called from the maintenance screen by
+ *  ?action=admin;area=manageattachments;sa=removeall.
+ */
 function RemoveAllAttachments()
 {
 	global $txt, $smcFunc;
@@ -813,7 +811,19 @@ function RemoveAllAttachments()
 	redirectexit('action=admin;area=manageattachments;sa=maintenance');
 }
 
-// Removes attachments - allowed query_types: '', 'messages', 'members'
+/**
+ * Removes attachments or avatars based on a given query condition.
+ * Called by several remove avatar/attachment functions in this file.
+ * It removes attachments based that match the $condition.
+ * It allows query_types 'messages' and 'members', whichever is need by the
+ * $condition parameter.
+ * It does no permissions check.
+ *
+ * @param array $condition
+ * @param string $query_type
+ * @param bool $return_affected_messages = false
+ * @param bool $autoThumbRemoval = true
+ */
 function removeAttachments($condition, $query_type = '', $return_affected_messages = false, $autoThumbRemoval = true)
 {
 	global $modSettings, $smcFunc;
@@ -925,7 +935,9 @@ function removeAttachments($condition, $query_type = '', $return_affected_messag
 		return array_unique($msgs);
 }
 
-// This function should find attachments in the database that no longer exist and clear them, and fix filesize issues.
+/**
+ * This function should find attachments in the database that no longer exist and clear them, and fix filesize issues.
+ */
 function RepairAttachments()
 {
 	global $modSettings, $context, $txt, $smcFunc;
@@ -1400,6 +1412,14 @@ function RepairAttachments()
 
 }
 
+/**
+ * Function called in-between each round of attachments and avatar repairs.
+ * Called by repairAttachments().
+ * If repairAttachments() has more steps added, this function needs updated!
+ *
+ * @param array $to_fix attachments to fix
+ * @param int $max_substep = 0
+ */
 function pauseAttachmentMaintenance($to_fix, $max_substep = 0)
 {
 	global $context, $txt, $time_start;
@@ -1437,7 +1457,9 @@ function pauseAttachmentMaintenance($to_fix, $max_substep = 0)
 	obExit();
 }
 
-// Called from a mouse click, works out what we want to do with attachments and actions it.
+/**
+ * Called from a mouse click, works out what we want to do with attachments and actions it.
+ */
 function ApproveAttach()
 {
 	global $smcFunc;
@@ -1520,7 +1542,11 @@ function ApproveAttach()
 	redirectexit($redirect);
 }
 
-// Approve an attachment, or maybe even more - no permission check!
+/**
+ * Approve an attachment, or maybe even more - no permission check!
+ *
+ * @param $attachments
+ */
 function ApproveAttachments($attachments)
 {
 	global $smcFunc;
@@ -1573,6 +1599,9 @@ function ApproveAttachments($attachments)
 	);
 }
 
+/**
+ * This function lists and allows updating of multiple attachments paths.
+ */
 function ManageAttachmentPaths()
 {
 	global $modSettings, $scripturl, $context, $txt, $sourcedir, $smcFunc;
@@ -1739,7 +1768,9 @@ function ManageAttachmentPaths()
 	$context['sub_template'] = 'attachment_paths';
 }
 
-// Prepare the actual attachment directories to be displayed in the list.
+/**
+ * Prepare the actual attachment directories to be displayed in the list.
+ */
 function list_getAttachDirs()
 {
 	global $smcFunc, $modSettings, $context, $txt;
@@ -1797,7 +1828,14 @@ function list_getAttachDirs()
 	return $attachdirs;
 }
 
-// Checks the status of an attachment directory and returns an array of the status key, if that status key signifies an error, and the folder size.
+/**
+ * Checks the status of an attachment directory and returns an array
+ *  of the status key, if that status key signifies an error, and
+ *  the folder size.
+ *
+ * @param string $dir
+ * @param int $expected_files
+ */
 function attachDirStatus($dir, $expected_files)
 {
 	if (!is_dir($dir))

+ 119 - 70
Sources/ManageBans.php

@@ -1,6 +1,9 @@
 <?php
 
 /**
+ * This file contains all the functions used for the ban center.
+ * @todo refactor as controller-model
+ *
  * Simple Machines Forum (SMF)
  *
  * @package SMF
@@ -14,74 +17,16 @@
 if (!defined('SMF'))
 	die('Hacking attempt...');
 
-/* This file contains all the functions used for the ban center.
-
-	void Ban()
-		- the main entrance point for all ban center functions.
-		- is accesssed by ?action=admin;area=ban.
-		- choses a function based on the 'sa' parameter.
-		- defaults to BanList().
-		- requires the ban_members permission.
-		- initializes the admin tabs.
-		- load the ManageBans template.
-
-	void BanList()
-		- shows a list of bans currently set.
-		- is accesssed by ?action=admin;area=ban;sa=list.
-		- uses the main ManageBans template.
-		- removes expired bans.
-		- allows sorting on different criteria.
-		- also handles removal of selected ban items.
-
-	void BanEdit()
-		- the screen for adding new bans and modifying existing ones.
-		- adding new bans:
-			- is accesssed by ?action=admin;area=ban;sa=add.
-			- uses the ban_edit sub template of the ManageBans template.
-		- modifying existing bans:
-			- is accesssed by ?action=admin;area=ban;sa=edit;bg=x
-			- uses the ban_edit sub template of the ManageBans template.
-			- shows a list of ban triggers for the specified ban.
-		- handles submitted forms that add, modify or remove ban triggers.
-
-	void BanEditTrigger()
-		- the screen for adding new ban triggers or modifying existing ones.
-		- adding new ban triggers:
-			- is accessed by ?action=admin;area=ban;sa=edittrigger;bg=x
-			- uses the ban_edit_trigger sub template of ManageBans.
-		- editing existing ban triggers:
-			- is accessed by ?action=admin;area=ban;sa=edittrigger;bg=x;bi=y
-			- uses the ban_edit_trigger sub template of ManageBans.
-
-	void BanBrowseTriggers()
-		- screen for showing the banned enities
-		- is accessed by ?action=admin;area=ban;sa=browse
-		- uses the browse_triggers sub template of the ManageBans template.
-		- uses sub-tabs for browsing by IP, hostname, email or username.
-
-	array BanLog()
-		- show a list of logged access attempts by banned users.
-		- is accessed by ?action=admin;area=ban;sa=log.
-		- allows sorting of several columns.
-		- also handles deletion of (a selection of) log entries.
-
-	string range2ip(array $low, array $high)
-		- reverse function of ip2range().
-		- converts a given array of IP numbers to a single string
-		- range2ip(array(10, 10, 10, 0), array(10, 10, 20, 255)) returns
-		   '10.10.10-20.*
-
-	array checkExistingTriggerIP(array $ip_array, string $fullip)
-		- checks whether a given IP range already exists in the trigger list.
-		- if yes, it returns an error message. Otherwise, it returns
-		  an array optimized for the database.
-
-	void updateBanMembers()
-		- updates the members table to match the new bans.
-		- is_activated >= 10: a member is banned.
-*/
-
-// Ban center.
+/**
+ * Ban center. The main entrance point for all ban center functions.
+ * It is accesssed by ?action=admin;area=ban.
+ * It choses a function based on the 'sa' parameter, like many others.
+ * The default sub-action is BanList().
+ * It requires the ban_members permission.
+ * It initializes the admin tabs.
+ *
+ * @uses ManageBans template.
+ */
 function Ban()
 {
 	global $context, $txt, $scripturl;
@@ -139,7 +84,15 @@ function Ban()
 	$subActions[$_REQUEST['sa']]();
 }
 
-// List all the bans.
+/**
+ * Shows a list of bans currently set.
+ * It is accesssed by ?action=admin;area=ban;sa=list.
+ * It removes expired bans.
+ * It allows sorting on different criteria.
+ * It also handles removal of selected ban items.
+ *
+ * @uses the main ManageBans template.
+ */
 function BanList()
 {
 	global $txt, $context, $ban_request, $ban_counts, $scripturl;
@@ -338,6 +291,14 @@ function BanList()
 	$context['default_list'] = 'ban_list';
 }
 
+/**
+ * Get bans, what else? For the given options.
+ *
+ * @param int $start
+ * @param int $items_per_page
+ * @param string $sort
+ * @return array
+ */
 function list_getBans($start, $items_per_page, $sort)
 {
 	global $smcFunc;
@@ -380,6 +341,19 @@ function list_getNumBans()
 	return $numBans;
 }
 
+/**
+ * This function is behind the screen for adding new bans and modifying existing ones.
+ * Adding new bans:
+ * 	- is accesssed by ?action=admin;area=ban;sa=add.
+ * 	- uses the ban_edit sub template of the ManageBans template.
+ * Modifying existing bans:
+ *  - is accesssed by ?action=admin;area=ban;sa=edit;bg=x
+ *  - uses the ban_edit sub template of the ManageBans template.
+ *  - shows a list of ban triggers for the specified ban.
+ *  - handles submitted forms that add, modify or remove ban triggers.
+ *
+ *  @todo insane number of writing to superglobals here...
+ */
 function BanEdit()
 {
 	global $txt, $modSettings, $context, $ban_request, $scripturl, $smcFunc;
@@ -1013,6 +987,16 @@ function BanEdit()
 		$context['sub_template'] = 'ban_edit';
 }
 
+/**
+ * This function handles the ins and outs of the screen for adding new ban
+ * triggers or modifying existing ones.
+ * Adding new ban triggers:
+ * 	- is accessed by ?action=admin;area=ban;sa=edittrigger;bg=x
+ * 	- uses the ban_edit_trigger sub template of ManageBans.
+ * Editing existing ban triggers:
+ *  - is accessed by ?action=admin;area=ban;sa=edittrigger;bg=x;bi=y
+ *  - uses the ban_edit_trigger sub template of ManageBans.
+ */
 function BanEditTrigger()
 {
 	global $context, $smcFunc;
@@ -1092,6 +1076,13 @@ function BanEditTrigger()
 	}
 }
 
+/**
+ * This handles the screen for showing the banned entities
+ * It is accessed by ?action=admin;area=ban;sa=browse
+ * It uses sub-tabs for browsing by IP, hostname, email or username.
+ *
+ * @uses ManageBans template, browse_triggers sub template.
+ */
 function BanBrowseTriggers()
 {
 	global $modSettings, $context, $scripturl, $smcFunc, $txt;
@@ -1287,6 +1278,15 @@ function BanBrowseTriggers()
 	$context['default_list'] = 'ban_trigger_list';
 }
 
+/**
+ * Get ban triggers for the given parameters.
+ *
+ * @param int $start
+ * @param int $items_per_page
+ * @param string $sort
+ * @param string $trigger_type
+ * @return array
+ */
 function list_getBanTriggers($start, $items_per_page, $sort, $trigger_type)
 {
 	global $smcFunc;
@@ -1320,6 +1320,12 @@ function list_getBanTriggers($start, $items_per_page, $sort, $trigger_type)
 	return $ban_triggers;
 }
 
+/**
+ * This returns the total number of ban triggers of the given type.
+ *
+ * @param string $trigger_type
+ * @return int
+ */
 function list_getNumBanTriggers($trigger_type)
 {
 	global $smcFunc;
@@ -1345,6 +1351,14 @@ function list_getNumBanTriggers($trigger_type)
 	return $num_triggers;
 }
 
+/**
+ * This handles the listing of ban log entries, and allows their deletion.
+ * Shows a list of logged access attempts by banned users.
+ * It is accessed by ?action=admin;area=ban;sa=log.
+ * How it works:
+ *  - allows sorting of several columns.
+ *  - also handles deletion of (a selection of) log entries.
+ */
 function BanLog()
 {
 	global $scripturl, $context, $smcFunc, $sourcedir, $txt;
@@ -1363,7 +1377,7 @@ function BanLog()
 				)
 			);
 
-		// 'Delte selection' button was pressed.
+		// 'Delete selection' button was pressed.
 		else
 		{
 			// Make sure every entry is integer.
@@ -1493,6 +1507,14 @@ function BanLog()
 	$context['default_list'] = 'ban_log';
 }
 
+/**
+ * Load a list of ban log entries from the database.
+ * (no permissions check)
+ *
+ * @param int $start
+ * @param int $items_per_page
+ * @param string $sort
+ */
 function list_getBanLogEntries($start, $items_per_page, $sort)
 {
 	global $smcFunc;
@@ -1516,6 +1538,9 @@ function list_getBanLogEntries($start, $items_per_page, $sort)
 	return $log_entries;
 }
 
+/**
+ * This returns the total count of ban log entries.
+ */
 function list_getNumBanLogEntries()
 {
 	global $smcFunc;
@@ -1532,6 +1557,17 @@ function list_getNumBanLogEntries()
 	return $num_entries;
 }
 
+/**
+ * Convert a range of given IP number into a single string.
+ * It's practically the reverse function of ip2range().
+ *
+ * @example
+ * range2ip(array(10, 10, 10, 0), array(10, 10, 20, 255)) returns '10.10.10-20.*
+ *
+ * @param array $low, IPv4 format
+ * @param array $high, IPv4 format
+ * @return string
+ */
 function range2ip($low, $high)
 {
 	if (count($low) != 4 || count($high) != 4)
@@ -1555,6 +1591,15 @@ function range2ip($low, $high)
 	return implode('.', $ip);
 }
 
+/**
+ * Checks whether a given IP range already exists in the trigger list.
+ * If yes, it returns an error message. Otherwise, it returns an array
+ *  optimized for the database.
+ *
+ * @param array $ip_array
+ * @param string $fullip
+ * @return bool
+ */
 function checkExistingTriggerIP($ip_array, $fullip = '')
 {
 	global $smcFunc, $scripturl;
@@ -1598,6 +1643,10 @@ function checkExistingTriggerIP($ip_array, $fullip = '')
 	return $values;
 }
 
+/**
+ * As it says... this tries to review the list of banned members, to match new bans.
+ * Note: is_activated >= 10: a member is banned.
+ */
 function updateBanMembers()
 {
 	global $smcFunc;

+ 62 - 57
Sources/ManageBoards.php

@@ -1,6 +1,8 @@
 <?php
 
 /**
+ * Manage and maintain the boards and categories of the forum.
+ *
  * Simple Machines Forum (SMF)
  *
  * @package SMF
@@ -14,58 +16,15 @@
 if (!defined('SMF'))
 	die('Hacking attempt...');
 
-/* Manage and maintain the boards and categories of the forum.
-
-	void ManageBoards()
-		- main entry point for all the manageboards admin screens.
-		- called by ?action=admin;area=manageboards.
-		- checks the permissions, based on the sub-action.
-		- loads the ManageBoards language file.
-		- calls a function based on the sub-action.
-
-	void ManageBoardsMain()
-		- main screen showing all boards and categories.
-		- called by ?action=admin;area=manageboards or ?action=admin;area=manageboards;sa=move.
-		- uses the main template of the ManageBoards template.
-		- requires manage_boards permission.
-		- also handles the interface for moving boards.
-
-	void EditCategory()
-		- screen for editing and repositioning a category.
-		- called by ?action=admin;area=manageboards;sa=cat
-		- uses the modify_category sub-template of the ManageBoards template.
-		- requires manage_boards permission.
-		- also used to show the confirm deletion of category screen
-		  (sub-template confirm_category_delete).
-
-	void EditCategory2()
-		- function for handling a submitted form saving the category.
-		- called by ?action=admin;area=manageboards;sa=cat2
-		- requires manage_boards permission.
-		- also handles deletion of a category.
-		- redirects to ?action=admin;area=manageboards.
-
-	void EditBoard()
-		- screen for editing and repositioning a board.
-		- called by ?action=admin;area=manageboards;sa=board
-		- uses the modify_board sub-template of the ManageBoards template.
-		- requires manage_boards permission.
-		- also used to show the confirm deletion of category screen
-		  (sub-template confirm_board_delete).
-
-	void EditBoard2()
-		- function for handling a submitted form saving the board.
-		- called by ?action=admin;area=manageboards;sa=board2
-		- requires manage_boards permission.
-		- also handles deletion of a board.
-		- redirects to ?action=admin;area=manageboards.
-
-	void EditBoardSettings()
-		- a screen to set a few general board and category settings.
-		- uses the modify_general_settings sub template.
-*/
-
-// The controller; doesn't do anything, just delegates.
+/**
+ * The main dispatcher; doesn't do anything, just delegates.
+ * This is the main entry point for all the manageboards admin screens.
+ * Called by ?action=admin;area=manageboards.
+ * It checks the permissions, based on the sub-action, and calls a function
+ *  based on the sub-action.
+ *
+ *  @uses ManageBoards language file.
+ */
 function ManageBoards()
 {
 	global $context, $txt, $scripturl;
@@ -111,7 +70,14 @@ function ManageBoards()
 	$subActions[$_REQUEST['sa']][0]();
 }
 
-// The main control panel thing.
+/**
+ * The main control panel thing, the screen showing all boards and categories.
+ * Called by ?action=admin;area=manageboards or ?action=admin;area=manageboards;sa=move.
+ * Requires manage_boards permission.
+ * It also handles the interface for moving boards.
+ *
+ * @uses ManageBoards template, main sub-template.
+ */
 function ManageBoardsMain()
 {
 	global $txt, $context, $cat_tree, $boards, $boardList, $scripturl, $sourcedir, $txt;
@@ -229,7 +195,16 @@ function ManageBoardsMain()
 	$context['can_manage_permissions'] = allowedTo('manage_permissions');
 }
 
-// Modify a specific category.
+/**
+ * Modify a specific category.
+ * (screen for editing and repositioning a category.)
+ * Also used to show the confirm deletion of category screen
+ * (sub-template confirm_category_delete).
+ * Called by ?action=admin;area=manageboards;sa=cat
+ * Requires manage_boards permission.
+ *
+ * @uses ManageBoards template, modify_category sub-template.
+ */
 function EditCategory()
 {
 	global $txt, $context, $cat_tree, $boardList, $boards, $sourcedir;
@@ -307,7 +282,14 @@ function EditCategory()
 	}
 }
 
-// Complete the modifications to a specific category.
+/**
+ * Function for handling a submitted form saving the category.
+ * (complete the modifications to a specific category.)
+ * It also handles deletion of a category.
+ * It requires manage_boards permission.
+ * Called by ?action=admin;area=manageboards;sa=cat2
+ * Redirects to ?action=admin;area=manageboards.
+ */
 function EditCategory2()
 {
 	global $sourcedir;
@@ -360,7 +342,17 @@ function EditCategory2()
 	redirectexit('action=admin;area=manageboards');
 }
 
-// Modify a specific board...
+/**
+ * Modify a specific board...
+ * 	void EditBoard()
+		- screen for editing and repositioning a board.
+		- called by ?action=admin;area=manageboards;sa=board
+		- uses the modify_board sub-template of the ManageBoards template.
+		- requires manage_boards permission.
+		- also used to show the confirm deletion of category screen
+		  (sub-template confirm_board_delete).
+
+ */
 function EditBoard()
 {
 	global $txt, $context, $cat_tree, $boards, $boardList, $sourcedir, $smcFunc, $modSettings;
@@ -560,7 +552,14 @@ function EditBoard()
 	}
 }
 
-// Make changes to/delete a board.
+/**
+ * Make changes to/delete a board.
+ * (function for handling a submitted form saving the board.)
+ * It also handles deletion of a board.
+ * Called by ?action=admin;area=manageboards;sa=board2
+ * Redirects to ?action=admin;area=manageboards.
+ * It requires manage_boards permission.
+ */
 function EditBoard2()
 {
 	global $txt, $sourcedir, $modSettings, $smcFunc, $context;
@@ -728,6 +727,12 @@ function ModifyCat()
 	redirectexit();
 }
 
+/**
+ * A screen to set a few general board and category settings.
+ *
+ * @uses modify_general_settings sub-template.
+ * @param $return_config
+ */
 function EditBoardSettings($return_config = false)
 {
 	global $context, $txt, $sourcedir, $modSettings, $scripturl, $smcFunc;

+ 19 - 3
Sources/ManageCalendar.php

@@ -1,6 +1,8 @@
 <?php
 
 /**
+ * This file allows you to manage the calendar.
+ *
  * Simple Machines Forum (SMF)
  *
  * @package SMF
@@ -14,7 +16,12 @@
 if (!defined('SMF'))
 	die('Hacking attempt...');
 
-// The main controlling function doesn't have much to do... yet.
+/**
+ * The main controlling function doesn't have much to do... yet.
+ * Just check permissions and delegate to the rest.
+ *
+ * @uses ManageCalendar language file.
+ */
 function ManageCalendar()
 {
 	global $context, $txt, $scripturl, $modSettings;
@@ -54,7 +61,9 @@ function ManageCalendar()
 	$subActions[$_REQUEST['sa']]();
 }
 
-// The function that handles adding, and deleting holiday data
+/**
+ * The function that handles adding, and deleting holiday data
+ */
 function ModifyHolidays()
 {
 	global $sourcedir, $scripturl, $txt, $context;
@@ -167,7 +176,9 @@ function ModifyHolidays()
 	$context['sub_template'] = 'show_list';
 }
 
-// This function is used for adding/editing a specific holiday
+/**
+ * This function is used for adding/editing a specific holiday
+ */
 function EditHoliday()
 {
 	global $txt, $context, $scripturl, $smcFunc;
@@ -269,6 +280,11 @@ function EditHoliday()
 	$context['holiday']['last_day'] = (int) strftime('%d', mktime(0, 0, 0, $context['holiday']['month'] == 12 ? 1 : $context['holiday']['month'] + 1, 0, $context['holiday']['month'] == 12 ? $context['holiday']['year'] + 1 : $context['holiday']['year']));
 }
 
+/**
+ * Show and allow to modify calendar settings. Obviously.
+ *
+ * @param bool $return_config = false
+ */
 function ModifyCalendarSettings($return_config = false)
 {
 	global $modSettings, $context, $settings, $txt, $boarddir, $sourcedir, $scripturl, $smcFunc;

+ 27 - 27
Sources/ManageErrors.php

@@ -1,6 +1,9 @@
 <?php
 
 /**
+ * The main purpose of this file is to show a list of all errors that were
+ * logged on the forum, and allow filtering and deleting them.
+ *
  * Simple Machines Forum (SMF)
  *
  * @package SMF
@@ -14,32 +17,14 @@
 if (!defined('SMF'))
 	die('Hacking attempt...');
 
-/* Show a list of all errors that were logged on the forum.
-
-	void ViewErrorLog()
-		- sets all the context up to show the error log for maintenance.
-		- uses the Errors template and error_log sub template.
-		- requires the maintain_forum permission.
-		- uses the 'view_errors' administration area.
-		- accessed from ?action=admin;area=logs;sa=errorlog.
-
-	void deleteErrors()
-		- deletes all or some of the errors in the error log.
-		- applies any necessary filters to deletion.
-		- should only be called by ViewErrorLog().
-		- attempts to TRUNCATE the table to reset the auto_increment.
-		- redirects back to the error log when done.
-
-	void ViewFile()
-		- will do php highlighting on the file specified in $_REQUEST['file']
-		- file must be readable
-		- full file path must be base64 encoded
-		- user must have admin_forum permission
-		- the line number number is specified by $_REQUEST['line']
-		- Will try to get the 20 lines before and after the specified line
-*/
-
-// View the forum's error log.
+/**
+ * View the forum's error log.
+ * This function sets all the context up to show the error log for maintenance.
+ * It requires the maintain_forum permission.
+ * It is accessed from ?action=admin;area=logs;sa=errorlog.
+ *
+ * @uses the Errors template and error_log sub template.
+ */
 function ViewErrorLog()
 {
 	global $scripturl, $txt, $context, $modSettings, $user_profile, $filter, $boarddir, $sourcedir, $themedir, $smcFunc;
@@ -284,7 +269,13 @@ function ViewErrorLog()
 	$context['sub_template'] = 'error_log';
 }
 
-// Delete errors from the database.
+/**
+ * Delete all or some of the errors in the error log.
+ * It applies any necessary filters to deletion.
+ * This should only be called by ViewErrorLog().
+ * It attempts to TRUNCATE the table to reset the auto_increment.
+ * Redirects back to the error log when done.
+ */
 function deleteErrors()
 {
 	global $filter, $smcFunc;
@@ -327,6 +318,15 @@ function deleteErrors()
 	redirectexit('action=admin;area=logs;sa=errorlog' . (isset($_REQUEST['desc']) ? ';desc' : ''));
 }
 
+/**
+ * View a file specified in $_REQUEST['file'], with php highlighting on it
+ * Preconditions:
+ * file must be readable,
+ * full file path must be base64 encoded,
+ * user must have admin_forum permission.
+ * The line number number is specified by $_REQUEST['line']...
+ * The function will try to get the 20 lines before and after the specified line.
+ */
 function ViewFile()
 {
 	global $context, $txt, $boarddir, $sourcedir;

+ 36 - 22
Sources/ManageMail.php

@@ -1,6 +1,10 @@
 <?php
 
 /**
+ * This file is all about mail, how we love it so. In particular it handles the admin side of
+ * mail configuration, as well as reviewing the mail queue - if enabled.
+ * @todo refactor as controller-model.
+ *
  * Simple Machines Forum (SMF)
  *
  * @package SMF
@@ -14,24 +18,9 @@
 if (!defined('SMF'))
 	die('Hacking attempt...');
 
-/*	This file is all about mail, how we love it so. In particular it handles the admin side of
-	mail configuration, as well as reviewing the mail queue - if enabled.
-
-	void ManageMail()
-		// !!
-
-	void BrowseMailQueue()
-		// !!
-
-	void ModifyMailSettings()
-		// !!
-
-	void ClearMailQueue()
-		// !!
-
-*/
-
-// This function passes control through to the relevant section
+/**
+ * Main dispatcher. This function checks permissions and passes control through to the relevant section.
+ */
 function ManageMail()
 {
 	global $context, $txt, $scripturl, $modSettings, $sourcedir;
@@ -69,7 +58,9 @@ function ManageMail()
 	$subActions[$_REQUEST['sa']]();
 }
 
-// Display the mail queue...
+/**
+ * Display the mail queue...
+ */
 function BrowseMailQueue()
 {
 	global $scripturl, $context, $modSettings, $txt, $smcFunc;
@@ -218,6 +209,13 @@ function BrowseMailQueue()
 	$context['sub_template'] = 'browse';
 }
 
+/**
+ * This function grabs the mail queue items from the database, according to the params given.
+ *
+ * @param int $start
+ * @param int $items_per_page
+ * @param string $sort
+ */
 function list_getMailQueue($start, $items_per_page, $sort)
 {
 	global $smcFunc, $txt;
@@ -248,6 +246,9 @@ function list_getMailQueue($start, $items_per_page, $sort)
 	return $mails;
 }
 
+/**
+ * Returns the total count of items in the mail queue.
+ */
 function list_getMailQueueSize()
 {
 	global $smcFunc;
@@ -265,6 +266,11 @@ function list_getMailQueueSize()
 	return $mailQueueSize;
 }
 
+/**
+ * Allows to view and modify the mail settings.
+ *
+ * @param bool $return_config
+ */
 function ModifyMailSettings($return_config = false)
 {
 	global $txt, $scripturl, $context, $settings, $birthdayEmails, $modSettings;
@@ -347,7 +353,9 @@ function ModifyMailSettings($return_config = false)
 	// ]]></script>';
 }
 
-// This function clears the mail queue of all emails, and at the end redirects to browse.
+/**
+ * This function clears the mail queue of all emails, and at the end redirects to browse.
+ */
 function ClearMailQueue()
 {
 	global $sourcedir, $smcFunc;
@@ -386,7 +394,9 @@ function ClearMailQueue()
 	return BrowseMailQueue();
 }
 
-// Used for pausing the mail queue.
+/**
+ * Used for pausing the mail queue.
+ */
 function pauseMailQueueClear()
 {
 	global $context, $txt, $time_start;
@@ -418,7 +428,11 @@ function pauseMailQueueClear()
 	obExit();
 }
 
-// Little function to calculate how long ago a time was.
+/**
+ * Little utility function to calculate how long ago a time was.
+ *
+ * @param long $time_diff
+ */
 function time_since($time_diff)
 {
 	global $txt;

+ 103 - 110
Sources/ManageMaintenance.php

@@ -1,6 +1,8 @@
 <?php
 
 /**
+ * Forum maintenance. Important stuff.
+ *
  * Simple Machines Forum (SMF)
  *
  * @package SMF
@@ -14,100 +16,10 @@
 if (!defined('SMF'))
 	die('Hacking attempt...');
 
-/* /!!!
-
-	void ManageMaintenance()
-		// !!!
-
-	void MaintainDatabase()
-		// !!!
-
-	void MaintainMembers()
-		// !!!
-
-	void MaintainTopics()
-		// !!!
-
-	void MaintainCleanCache()
-		// !!!
-
-	void MaintainFindFixErrors()
-		// !!!
-
-	void MaintainEmptyUnimportantLogs()
-		// !!!
-
-	void ConvertUtf8()
-		- converts the data and database tables to UTF-8 character set.
-		- requires the admin_forum permission.
-		- uses the convert_utf8 sub template of the Admin template.
-		- only works if UTF-8 is not the global character set.
-		- supports all character sets used by SMF's language files.
-		- redirects to ?action=admin;area=maintain after finishing.
-		- is linked from the maintenance screen (if applicable).
-		- accessed by ?action=admin;area=maintain;sa=database;activity=convertutf8.
-
-	void ConvertEntities()
-		- converts HTML-entities to UTF-8 characters.
-		- requires the admin_forum permission.
-		- uses the convert_entities sub template of the Admin template.
-		- only works if UTF-8 has been set as database and global character set.
-		- is divided in steps of 10 seconds.
-		- is linked from the maintenance screen (if applicable).
-		- accessed by ?action=admin;area=maintain;sa=database;activity=convertentities.
-
-	void OptimizeTables()
-		- optimizes all tables in the database and lists how much was saved.
-		- requires the admin_forum permission.
-		- uses the rawdata sub template (built in.)
-		- shows as the maintain_forum admin area.
-		- updates the optimize scheduled task such that the tables are not
-		  automatically optimized again too soon.
-		- accessed from ?action=admin;area=maintain;sa=database;activity=optimize.
-
-	void AdminBoardRecount()
-		- recounts many forum totals that can be recounted automatically
-		  without harm.
-		- requires the admin_forum permission.
-		- shows the maintain_forum admin area.
-		- fixes topics with wrong num_replies.
-		- updates the num_posts and num_topics of all boards.
-		- recounts instant_messages but not unread_messages.
-		- repairs messages pointing to boards with topics pointing to
-		  other boards.
-		- updates the last message posted in boards and children.
-		- updates member count, latest member, topic count, and message count.
-		- redirects back to ?action=admin;area=maintain when complete.
-		- accessed via ?action=admin;area=maintain;sa=database;activity=recount.
-
-	void VersionDetail()
-		- parses the comment headers in all files for their version information
-		  and outputs that for some javascript to check with simplemacines.org.
-		- does not connect directly with simplemachines.org, but rather
-		  expects the client to.
-		- requires the admin_forum permission.
-		- uses the view_versions admin area.
-		- loads the view_versions sub template (in the Admin template.)
-		- accessed through ?action=admin;area=maintain;sa=routine;activity=version.
-
-	void MaintainReattributePosts()
-		// !!!
-
-	void MaintainDownloadBackup()
-		// !!!
-
-	void MaintainPurgeInactiveMembers()
-		// !!!
-
-	void MaintainRemoveOldPosts(bool do_action = true)
-		// !!!
-
-	mixed MaintainMassMoveTopics()
-		- Moves topics from one board to another.
-		- User the not_done template to pause the process.
-*/
-
-// The maintenance access point.
+/**
+ * Main dispatcher, the maintenance access point.
+ * This, as usual, checks permissions, loads language files, and forwards to the actual workers.
+ */
 function ManageMaintenance()
 {
 	global $txt, $modSettings, $scripturl, $context, $options;
@@ -203,7 +115,9 @@ function ManageMaintenance()
 		$context['maintenance_finished'] = $txt['utf8_title'];
 }
 
-// Supporting function for the database maintenance area.
+/**
+ * Supporting function for the database maintenance area.
+ */
 function MaintainDatabase()
 {
 	global $context, $db_type, $db_character_set, $modSettings, $smcFunc, $txt;
@@ -218,7 +132,9 @@ function MaintainDatabase()
 		$context['maintenance_finished'] = $txt['entity_convert_title'];
 }
 
-// Supporting function for the routine maintenance area.
+/**
+ * Supporting function for the routine maintenance area.
+ */
 function MaintainRoutine()
 {
 	global $context, $txt;
@@ -227,7 +143,9 @@ function MaintainRoutine()
 		$context['maintenance_finished'] = $txt['maintain_recount'];
 }
 
-// Supporting function for the members maintenance area.
+/**
+ * Supporting function for the members maintenance area.
+ */
 function MaintainMembers()
 {
 	global $context, $smcFunc, $txt;
@@ -255,7 +173,9 @@ function MaintainMembers()
 	$smcFunc['db_free_result']($result);
 }
 
-// Supporting function for the topics maintenance area.
+/**
+ * Supporting function for the topics maintenance area.
+ */
 function MaintainTopics()
 {
 	global $context, $smcFunc, $txt;
@@ -294,7 +214,9 @@ function MaintainTopics()
 		$context['maintenance_finished'] = $txt['move_topics_maintenance'];
 }
 
-// Find and fix all errors.
+/**
+ * Find and fix all errors on the forum.
+ */
 function MaintainFindFixErrors()
 {
 	global $sourcedir;
@@ -303,7 +225,10 @@ function MaintainFindFixErrors()
 	RepairBoards();
 }
 
-// Wipes the whole cache directory.
+/**
+ * Wipes the whole cache directory.
+ * This only applies to SMF's own cache directory, though.
+ */
 function MaintainCleanCache()
 {
 	global $context, $txt;
@@ -314,7 +239,9 @@ function MaintainCleanCache()
 	$context['maintenance_finished'] = $txt['maintain_cache'];
 }
 
-// Empties all uninmportant logs
+/**
+ * Empties all uninmportant logs
+ */
 function MaintainEmptyUnimportantLogs()
 {
 	global $context, $smcFunc, $txt;
@@ -370,7 +297,17 @@ function Destroy()
 	obExit(false);
 }
 
-// Convert both data and database tables to UTF-8 character set.
+/**
+ * Convert both data and database tables to UTF-8 character set.
+ * It requires the admin_forum permission.
+ * This only works if UTF-8 is not the global character set.
+ * It supports all character sets used by SMF's language files.
+ * It redirects to ?action=admin;area=maintain after finishing.
+ * This action is linked from the maintenance screen (if it's applicable).
+ * Accessed by ?action=admin;area=maintain;sa=database;activity=convertutf8.
+ *
+ * @uses the convert_utf8 sub template of the Admin template.
+ */
 function ConvertUtf8()
 {
 	global $scripturl, $context, $txt, $language, $db_character_set;
@@ -720,7 +657,17 @@ function ConvertUtf8()
 	redirectexit('action=admin;area=maintain;done=convertutf8');
 }
 
-// Convert HTML-entities to their UTF-8 character equivalents.
+/**
+ * Converts HTML-entities to their UTF-8 character equivalents.
+ * This requires the admin_forum permission.
+ * Pre-condition: UTF-8 has been set as database and global character set.
+ *
+ * It is divided in steps of 10 seconds.
+ * This action is linked from the maintenance screen (if applicable).
+ * It is accessed by ?action=admin;area=maintain;sa=database;activity=convertentities.
+ *
+ * @uses Admin template, convert_entities sub-template.
+ */
 function ConvertEntities()
 {
 	global $db_character_set, $modSettings, $context, $sourcedir, $smcFunc;
@@ -916,7 +863,15 @@ function ConvertEntities()
 	$context['continue_countdown'] = -1;
 }
 
-// Optimize the database's tables.
+/**
+ * Optimizes all tables in the database and lists how much was saved.
+ * It requires the admin_forum permission.
+ * It shows as the maintain_forum admin area.
+ * It is accessed from ?action=admin;area=maintain;sa=database;activity=optimize.
+ * It also updates the optimize scheduled task such that the tables are not automatically optimized again too soon.
+
+ * @uses the rawdata sub template (built in.)
+ */
 function OptimizeTables()
 {
 	global $db_type, $db_name, $db_prefix, $txt, $context, $scripturl, $sourcedir, $smcFunc;
@@ -975,7 +930,21 @@ function OptimizeTables()
 	CalculateNextTrigger('auto_optimize', true);
 }
 
-// Recount all the important board totals.
+/**
+ * Recount many forum totals that can be recounted automatically without harm.
+ * it requires the admin_forum permission.
+ * It shows the maintain_forum admin area.
+ * Totals recounted:
+ * - fixes for topics with wrong num_replies.
+ * - updates for num_posts and num_topics of all boards.
+ * - recounts instant_messages but not unread_messages.
+ * - repairs messages pointing to boards with topics pointing to other boards.
+ * - updates the last message posted in boards and children.
+ * - updates member count, latest member, topic count, and message count.
+ *
+ * The function redirects back to ?action=admin;area=maintain when complete.
+ * It is accessed via ?action=admin;area=maintain;sa=database;activity=recount.
+ */
 function AdminBoardRecount()
 {
 	global $txt, $context, $scripturl, $modSettings, $sourcedir;
@@ -1462,7 +1431,17 @@ function AdminBoardRecount()
 	redirectexit('action=admin;area=maintain;sa=routine;done=recount');
 }
 
-// Perform a detailed version check.  A very good thing ;).
+/**
+ * Perform a detailed version check.  A very good thing ;).
+ * The function parses the comment headers in all files for their version information,
+ * and outputs that for some javascript to check with simplemachines.org.
+ * It does not connect directly with simplemachines.org, but rather expects the client to.
+ *
+ * It requires the admin_forum permission.
+ * Uses the view_versions admin area.
+ * Accessed through ?action=admin;area=maintain;sa=routine;activity=version.
+ * @uses Admin template, view_versions sub-template.
+ */
 function VersionDetail()
 {
 	global $forum_version, $txt, $sourcedir, $context;
@@ -1494,7 +1473,9 @@ function VersionDetail()
 	$context['page_title'] = $txt['admin_version_check'];
 }
 
-// Removing old posts doesn't take much as we really pass through.
+/**
+ * Re-attribute posts.
+ */
 function MaintainReattributePosts()
 {
 	global $sourcedir, $context, $txt;
@@ -1521,7 +1502,9 @@ function MaintainReattributePosts()
 	$context['maintenance_finished'] = $txt['maintain_reattribute_posts'];
 }
 
-// Handling function for the backup stuff.
+/**
+ * Handling function for the backup stuff.
+ */
 function MaintainDownloadBackup()
 {
 	global $sourcedir;
@@ -1530,7 +1513,10 @@ function MaintainDownloadBackup()
 	DumpDatabase2();
 }
 
-// Removing old members?
+/**
+ * Removing old members. Done and out!
+ * @todo refactor
+ */
 function MaintainPurgeInactiveMembers()
 {
 	global $sourcedir, $context, $smcFunc, $txt;
@@ -1612,7 +1598,9 @@ function MaintainPurgeInactiveMembers()
 	$context['maintenance_finished'] = $txt['maintain_members'];
 }
 
-// Removing old posts doesn't take much as we really pass through.
+/**
+ * Removing old posts doesn't take much as we really pass through.
+ */
 function MaintainRemoveOldPosts()
 {
 	global $sourcedir, $context, $txt;
@@ -1622,6 +1610,11 @@ function MaintainRemoveOldPosts()
 	RemoveOldTopics2();
 }
 
+/**
+ * Moves topics from one board to another.
+ *
+ * @uses not_done template to pause the process.
+ */
 function MaintainMassMoveTopics()
 {
 	global $smcFunc, $sourcedir, $context, $txt;

+ 57 - 58
Sources/ManageMembergroups.php

@@ -1,6 +1,8 @@
 <?php
 
 /**
+ * This file is concerned with anything in the Manage Membergroups screen.
+ *
  * Simple Machines Forum (SMF)
  *
  * @package SMF
@@ -14,59 +16,17 @@
 if (!defined('SMF'))
 	die('Hacking attempt...');
 
-/* This file is concerned with anything in the Manage Membergroups screen.
-
-	void ModifyMembergroups()
-		- entrance point of the 'Manage Membergroups' center.
-		- called by ?action=admin;area=membergroups.
-		- loads the ManageMembergroups template.
-		- loads the MangeMembers language file.
-		- requires the manage_membergroups or the admin_forum permission.
-		- calls a function based on the given subaction.
-		- defaults to sub action 'index' or without manage_membergroup
-		  permissions to 'settings'.
-
-	void MembergroupIndex()
-		- shows an overview of the current membergroups.
-		- called by ?action=admin;area=membergroups.
-		- requires the manage_membergroups permission.
-		- uses the main ManageMembergroups template.
-		- splits the membergroups in regular ones and post count based groups.
-		- also counts the number of members part of each membergroup.
-
-	void AddMembergroup()
-		- allows to add a membergroup and set some initial properties.
-		- called by ?action=admin;area=membergroups;sa=add.
-		- requires the manage_membergroups permission.
-		- uses the new_group sub template of ManageMembergroups.
-		- allows to use a predefined permission profile or copy one from
-		  another group.
-		- redirects to action=admin;area=membergroups;sa=edit;group=x.
-
-	void DeleteMembergroup()
-		- deletes a membergroup by URL.
-		- called by ?action=admin;area=membergroups;sa=delete;group=x;session_var=y.
-		- requires the manage_membergroups permission.
-		- redirects to ?action=admin;area=membergroups.
-
-	void EditMembergroup()
-		- screen to edit a specific membergroup.
-		- called by ?action=admin;area=membergroups;sa=edit;group=x.
-		- requires the manage_membergroups permission.
-		- uses the edit_group sub template of ManageMembergroups.
-		- also handles the delete button of the edit form.
-		- redirects to ?action=admin;area=membergroups.
-
-	void ModifyMembergroupsettings()
-		- set some general membergroup settings and permissions.
-		- called by ?action=admin;area=membergroups;sa=settings
-		- requires the admin_forum permission (and manage_permissions for
-		  changing permissions)
-		- uses membergroup_settings sub template of ManageMembergroups.
-		- redirects to itself.
-*/
 
-// The entrance point for all 'Manage Membergroup' actions.
+/**
+ * Main dispatcher, the entrance point for all 'Manage Membergroup' actions.
+ * It forwards to a function based on the given subaction, default being subaction 'index', or, without manage_membergroup
+ * permissions, then 'settings'.
+ * Called by ?action=admin;area=membergroups.
+ * Requires the manage_membergroups or the admin_forum permission.
+ *
+ * @uses ManageMembergroups template.
+ * @uses ManageMembers language file.
+*/
 function ModifyMembergroups()
 {
 	global $context, $txt, $scripturl, $sourcedir;
@@ -105,7 +65,15 @@ function ModifyMembergroups()
 	$subActions[$_REQUEST['sa']][0]();
 }
 
-// An overview of the current membergroups.
+/**
+ * Shows an overview of the current membergroups.
+ * Called by ?action=admin;area=membergroups.
+ * Requires the manage_membergroups permission.
+ * Splits the membergroups in regular ones and post count based groups.
+ * It also counts the number of members part of each membergroup.
+ *
+ * @uses ManageMembergroups template, main.
+ */
 function MembergroupIndex()
 {
 	global $txt, $scripturl, $context, $settings, $smcFunc, $sourcedir;
@@ -340,7 +308,15 @@ function MembergroupIndex()
 	createList($listOptions);
 }
 
-// Add a membergroup.
+/**
+ * This function handles adding a membergroup and setting some initial properties.
+ * Called by ?action=admin;area=membergroups;sa=add.
+ * It requires the manage_membergroups permission.
+ * Allows to use a predefined permission profile or copy one from another group.
+ * Redirects to action=admin;area=membergroups;sa=edit;group=x.
+ *
+ * @uses the new_group sub template of ManageMembergroups.
+ */
 function AddMembergroup()
 {
 	global $context, $txt, $sourcedir, $modSettings, $smcFunc;
@@ -595,7 +571,14 @@ function AddMembergroup()
 	$smcFunc['db_free_result']($result);
 }
 
-// Deleting a membergroup by URL (not implemented).
+/**
+ * Deleting a membergroup by URL (not implemented).
+ * Called by ?action=admin;area=membergroups;sa=delete;group=x;session_var=y.
+ * Requires the manage_membergroups permission.
+ * Redirects to ?action=admin;area=membergroups.
+ *
+ * @todo look at this
+ */
 function DeleteMembergroup()
 {
 	global $sourcedir;
@@ -609,7 +592,16 @@ function DeleteMembergroup()
 	redirectexit('action=admin;area=membergroups;');
 }
 
-// Editing a membergroup.
+/**
+ * Editing a membergroup.
+ * Screen to edit a specific membergroup.
+ * Called by ?action=admin;area=membergroups;sa=edit;group=x.
+ * It requires the manage_membergroups permission.
+ * Also handles the delete button of the edit form.
+ * Redirects to ?action=admin;area=membergroups.
+ *
+ * @uses the edit_group sub template of ManageMembergroups.
+ */
 function EditMembergroup()
 {
 	global $context, $txt, $sourcedir, $modSettings, $smcFunc;
@@ -924,7 +916,7 @@ function EditMembergroup()
 
 		// There might have been some post group changes.
 		updateStats('postgroups');
-		// We've definetely changed some group stuff.
+		// We've definitely changed some group stuff.
 		updateSettings(array(
 			'settings_updated' => time(),
 		));
@@ -1039,7 +1031,14 @@ function EditMembergroup()
 	$context['page_title'] = $txt['membergroups_edit_group'];
 }
 
-// Set general membergroup settings.
+/**
+ * Set some general membergroup settings and permissions.
+ * Called by ?action=admin;area=membergroups;sa=settings
+ * Requires the admin_forum permission (and manage_permissions for changing permissions)
+ * Redirects to itself.
+ *
+ * @uses membergroup_settings sub template of ManageMembergroups.
+ */
 function ModifyMembergroupsettings()
 {
 	global $context, $sourcedir, $scripturl, $modSettings, $txt;

+ 5 - 11
Sources/Subs-Auth.php

@@ -102,7 +102,7 @@ if (!defined('SMF'))
 // Actually set the login cookie...
 function setLoginCookie($cookie_length, $id, $password = '')
 {
-	global $cookiename, $boardurl, $modSettings;
+	global $cookiename, $boardurl, $modSettings, $sourcedir;
 
 	// If changing state force them to re-address some permission caching.
 	$_SESSION['mc']['time'] = 0;
@@ -160,6 +160,9 @@ function setLoginCookie($cookie_length, $id, $password = '')
 	// Make sure the user logs in with a new session ID.
 	if (!isset($_SESSION['login_' . $cookiename]) || $_SESSION['login_' . $cookiename] !== $data)
 	{
+		// We need to meddle with the session.
+		require_once($sourcedir . '/Session.php');
+
 		// Backup and remove the old session.
 		$oldSessionData = $_SESSION;
 		$_SESSION = array();
@@ -184,16 +187,7 @@ function setLoginCookie($cookie_length, $id, $password = '')
 // PHP < 4.3.2 doesn't have this function
 if (!function_exists('session_regenerate_id'))
 {
-	function session_regenerate_id()
-	{
-		// Too late to change the session now.
-		if (headers_sent())
-			return false;
-
-		session_id(strtolower(md5(uniqid(mt_rand(), true))));
-		return true;
-	}
-
+	require_once $sourcedir . 'Subs-Compat.php';
 }
 
 // Get the domain and path for the cookie...

+ 15 - 2
Sources/Subs-Compat.php

@@ -5,7 +5,7 @@
  * PHP, such as the sha1() function, missing extensions, or 64-bit vs 32-bit
  * systems. It is only included for those older versions or when the respective
  * extension or function cannot be found.
- * 
+ *
  * Simple Machines Forum (SMF)
  *
  * @package SMF
@@ -41,7 +41,7 @@ if (!function_exists('str_split'))
 	/**
 	 * Split a string into an array.
 	 * @param $str the string to split
-	 * @param $str_length 
+	 * @param $str_length
 	 */
 	function str_split($str, $str_length = 1)
 	{
@@ -274,4 +274,17 @@ if (!function_exists('smf_crc32'))
 	}
 }
 
+// PHP < 4.3.2 doesn't have this function
+if (!function_exists('session_regenerate_id'))
+{
+	function session_regenerate_id()
+	{
+		// Too late to change the session now.
+		if (headers_sent())
+			return false;
+
+		session_id(strtolower(md5(uniqid(mt_rand(), true))));
+		return true;
+	}
+}
 ?>

+ 14 - 12
index.php

@@ -1,6 +1,15 @@
 <?php
 
 /**
+ * This, as you have probably guessed, is the crux on which SMF functions.
+ * Everything should start here, so all the setup and security is done
+ * properly.  The most interesting part of this file is the action array in
+ * the smf_main() function.  It is formatted as so:
+ * 	'action-in-url' => array('Source-File.php', 'FunctionToCall'),
+ *
+ * Then, you can access the FunctionToCall() function from Source-File.php
+ * with the URL index.php?action=action-in-url.  Relatively simple, no?
+ *
  * Simple Machines Forum (SMF)
  *
  * @package SMF
@@ -11,17 +20,6 @@
  * @version 2.0
  */
 
-/*	This, as you have probably guessed, is the crux on which SMF functions.
-	Everything should start here, so all the setup and security is done
-	properly.  The most interesting part of this file is the action array in
-	the smf_main() function.  It is formatted as so:
-
-		'action-in-url' => array('Source-File.php', 'FunctionToCall'),
-
-	Then, you can access the FunctionToCall() function from Source-File.php
-	with the URL index.php?action=action-in-url.  Relatively simple, no?
-*/
-
 $forum_version = 'SMF 2.0';
 
 // Get everything started up...
@@ -48,6 +46,7 @@ if ((empty($cachedir) || !file_exists($cachedir)) && file_exists($boarddir . '/c
 
 // And important includes.
 require_once($sourcedir . '/QueryString.php');
+require_once($sourcedir . '/Session.php');
 require_once($sourcedir . '/Subs.php');
 require_once($sourcedir . '/Errors.php');
 require_once($sourcedir . '/Load.php');
@@ -153,7 +152,10 @@ call_user_func(smf_main());
 // Call obExit specially; we're coming from the main area ;).
 obExit(null, null, true);
 
-// The main controlling function.
+/**
+ * The main dispatcher.
+ * This delegates to each area.
+ */
 function smf_main()
 {
 	global $modSettings, $settings, $user_info, $board, $topic, $board_info, $maintenance, $sourcedir;