Location: PHPKode > projects > PhabCMS > phabcms/functions.php
<?PHP
	// *** This code is under the BSD license as specified in doc/LICENSE of the phab³CMS project
	// *** All written by hide@address.com unless otherwise stated.
	// *** Note to anyone reading the source; I'm quite aware of my ignorance, so please berrate me for flaws at the above address
	// *** All the source should either be available at http://phabcms.sourceforge.net or perhaps somewhere on http://ahri.net


	/*
	Get User Group
		Use:
			$getUserGroup = getUserGroup (userGroupID);
		Returns:
			* false - something went wrong
			* array (name, level)
	*/
	function getUserGroup ($userGroupID)
		{
			$return = false;

			$db = new extended_sqlObject;
			$db->query ("SELECT * FROM {$db->tablePrefix}_usergroups WHERE id='$userGroupID'");
 
			while ($db->nextRecord ())
				{
					$return = array
						(
							'name' => $db->record['name'],
							'level' => $db->record['level']
						);
				}

			return $return;
		}


	/*
	Get User
		Use:
			$getUser = getUser (user);
		Returns:
			* false - something went wrong
			* array (user, email, sig, groupn, pass, salt)
	*/
	function getUser ($user)
		{
			$return = false;

			$db = new extended_sqlObject;
			$db->query ("SELECT * FROM {$db->tablePrefix}_users WHERE user='$user'");

			while ($db->nextRecord ())
				{
					$return = array
						(
							'user' => $db->record['user'],
							'email' => $db->record['email'],
							'sig' => $db->record['sig'],
							'groupn' => $db->record['groupn'],
							'pass' => $db->record['pass'],
							'salt' => $db->record['salt']
						);
				}

			return $return;
		}


	/*
	Get Section Group
		Use:
			$getSectionGroup = getSectionGroup (sectionGroupID);
		Returns:
			* false - something went wrong
			* array (name, rlevel, wlevel)
	*/
	function getSectionGroup ($sectionGroupID)
		{
			$return = false;

			$db = new extended_sqlObject;
			$db->query ("SELECT * FROM {$db->tablePrefix}_sectiongroups WHERE id='$sectionGroupID'");

			while ($db->nextRecord ())
				{
					$return = array
						(
							'name' => $db->record['name'],
							'rlevel' => $db->record['rlevel'],
							'wlevel' => $db->record['wlevel'],
							'sort' => $db->record['sort']
						);
				}

			return $return;
		}


	/*
	Get Section
		Use:
			$getSection = getSection (sectionID);
		Returns:
			* false - something went wrong
			* array (name, userGroups, moderators (array), groupn, module)
	*/
	function getSection ($sectionID)
		{
			$return = false;

			$db = new extended_sqlObject;
			$db->query ("SELECT * FROM {$db->tablePrefix}_sections WHERE id='$sectionID'");

			while ($db->nextRecord ())
				{
					$return = array
						(
							'name' => $db->record['name'],
							'userGroups' => $db->record['userGroups'],
							'groupn' => $db->record['groupn'],
							'module' => $db->record['module'],
							'sort' => $db->record['sort']
						);

					$moderators = array ('x', 'x');
					$mods = explode (' ', $db->record['moderators']);
					for ($i = 0; $i < sizeof ($mods); $i++)
							if ($mods[$i] != '')
									array_push ($moderators, $mods[$i]);

					$mods = array ('moderators' => $moderators);
					$return = array_merge ($return, $mods);
				}

			return $return;
		}


	/*
	Get Post
		Use:
			$getPost = getPost (postID);
		Returns:
			* false - something went wrong
			* array (id, poster, date, time, title, content, section, thread, edit)
	*/
	function getPost ($postID)
		{
			$return = false;

			$db = new extended_sqlObject;
			$db->query ("SELECT * FROM {$db->tablePrefix}_posts WHERE id='$postID'");

			while ($db->nextRecord ())
				{
					$return = array
						(
							'id' => $db->record['id'],
							'poster' => $db->record['poster'],
							'date' => date ('j/m/Y', $db->record['datetime']),
							'time' => date ('H:i:s', $db->record['datetime']),
							'title' => $db->record['title'],
							'content' => $db->record['content'],
							'section' => $db->record['section'],
							'thread' => $db->record['thread'],
							'edit' => $db->record['edit']
						);
				}

			return $return;
		}


	/*
	Return Module
		Use:
			$returnModule = returnModule ((s|p), ID);
		Returns:
			* module
			* false
	*/
	function returnModule ($type, $id)
		{
			if (($type == 'p') && (is_numeric ($id)))
				{
					$getPost = getPost ($id);					// request the post info on the post/thread

					if (!$getPost['section'])					// it's just a post on a thread, let's get the thread ID
						{
							$id = $getPost['thread'];			// now we have the thread ID
							$getPost = getPost ($id);			// request the post info on the thread
							$getSection = getSection ($getPost['section']);
							return $getSection['module'];
						}

					else
						{
							$getSection = getSection ($getPost['section']);
							return $getSection['module'];
						}

					return false;
				}

			elseif (($type == 's') && (is_numeric ($id)))
				{
					$getSection = getSection ($id);
					return $getSection['module'];
				}
		}


	/*
	Return Section Level
		Use:
			returnSectionLevel (sectionID);
		Returns:
			* array (rlevel, wlevel)
	*/
	function returnSectionLevel ($sectionID)
		{
			$getSection = getSection ($sectionID);
			$getSectionGroup = getSectionGroup ($getSection['groupn']);
			return array
				(
					'rlevel' => $getSectionGroup['rlevel'],
					'wlevel' => $getSectionGroup['wlevel']
				);
		}


	/*
	Return Post Level
		Use:
			$returnPostLevel = returnPostLevel (postID);
		Returns:
			* array (rlevel, wlevel)
			* false
	*/
	function returnPostLevel ($postID)
		{
			$getPost = getPost ($postID);					// request the post info on the post/thread

			if ($getPost['thread'] > 0)						// it's just a post on a thread, let's get the thread ID
				{
					$postID = $getPost['thread'];			// now we have the thread ID
					$getPost = getPost ($postID);			// request the post info on the thread
				}

			if ($getPost['section'] > 0)
					return returnSectionLevel ($getPost['section']);

			return false;
		}


	/*
	Return Post Section
		Use:
			returnPostSection ($id);
		Returns:
			* sectionID
			* false
	*/
	function returnPostSection ($postID)
		{
			$getPost = getPost ($postID);					// request the post info on the post/thread

			if ($getPost['thread'] > 0)						// it's just a post on a thread, let's get the thread ID
				{
					$postID = $getPost['thread'];			// now we have the thread ID
					$getPost = getPost ($postID);			// request the post info on the thread
					return $getPost['section'];
				}

			if ($getPost['section'] > 0)
					return $getPost['section'];

			return false;
		}


	/*
	Rand String Generation
	Use:
		randString (#);
	Returns:
		* Requested string, or error if input arguements were erronious
	Notes:
		* # must be a positive value (it's turned into an integer anyway) indicating the number of random characters to return
	*/
	function randString ($length)
		{
			if ((is_numeric ($length)) && ($length > 0))
				{
					$length = intval ($length);
					while (strlen ($string) != $length)
						{
							$allchars = 'abcdefghijklnmopqrstuvwxyzABCDEFGHIJKLNMOPQRSTUVWXYZ0123456789!?@#';
							unset ($string);
							for ($i = 0; $i < $length; $i++)
								{
									mt_srand ((double) microtime () * 1000000);
									$string .= $allchars [mt_rand (0, strlen ($allchars))];
								}
						}
					return $string;
				}
			else
				{
					return '<FONT COLOR=\'#FF000000\'><B>Something went wrong Generating Random String</B></FONT>';
				}
		}


	/*
	Add Post to SQL DB
		Use:
			addPost (Title, Content, New Thread (1/0), ID);
		Notes:
			* If New = 1 then the ID is that of the sectionID, however if New = 0 then the ID is that of the threadID
			* The content must have more than 2 characters
		Returns:
			* true - Post adding succeeded
			* false - Post adding failed
	*/
	function addPost ($title, $content, $new, $id)
		{
			global $c, $c;

			if (strlen ($content) > 0)
				{
					if ($new == 1)			// new thread, so ID is forumID
						{
							if (strlen ($title) == 0)
									return false;
						}

					elseif ($new == 0)		// not new thread, so ID is threadID to attach to
						{
							if (strlen ($title) == 0)
								{
									$getPost = getPost ($id);
									$title = 'RE: ' . $getPost['title'];
								}
						}

					else					// neither case - the input was wrong
							return false;


					$cols = 'poster, datetime, title, content';
					$values = "'" . mysql_escape_string ($c['user']) . "', '" . time () . "', '" . mysql_escape_string ($title) . "', '" . mysql_escape_string ($content) . "'";

					if ($new == 1)			// new thread, so ID is sectionID
						{
							$cols .= ', section';
							$values .= ", '$id'";
							$returnSectionLevel = returnSectionLevel ($id);
							$section = getSection ($id);
							if ($c['level'] > $returnSectionLevel['wlevel'] && !in_array ($c['user'], $section['moderators']))
									return false;
						}

					elseif ($new == 0)		// not new thread, so ID is threadID to attach to
						{
							$cols .= ', thread';
							$values .= ", '$id'";
							$returnPostLevel = returnPostLevel ($id);
							$section = getSection (returnPostSection ($id));
							if ($c['level'] > $returnPostLevel['wlevel'] && !in_array ($c['user'], $section['moderators']))
									return false;
						}


					if ($c['user'] != false)
						{
							$db = new extended_sqlObject;
							$db->query ("INSERT INTO {$db->tablePrefix}_posts ($cols) VALUES ($values)");
							return true;
						}
				}

			return false;
		}


	/*
	Return User Group ID's
		Use:
			returnUserGroups ();
		Returns:
			* array (id1, id2, etc.)
			* false
	*/
	function returnUserGroups ()
		{
			$db = new extended_sqlObject;
			$db->query ("SELECT id, level FROM {$db->tablePrefix}_usergroups ORDER BY 'level' ASC");

			$userGroups = array ();
			while ($db->nextRecord ())
					array_push ($userGroups, $db->record['id']);

			return $userGroups;
		}


	/*
	Return User ID's for specified User Group
		Use:
			returnSections (SectionGroupID);
		Returns:
			* array (user1, user2, etc.)
			* false
	*/
	function returnUsers ($id)
		{
			if (is_numeric ($id))
				{
					$db = new extended_sqlObject;
					$db->query ("SELECT user FROM {$db->tablePrefix}_users WHERE groupn='$id' ORDER BY 'user' ASC");

					$users = array ();
					while ($db->nextRecord ())
							array_push ($users, $db->record['user']);

					return $users;
				}

			return false;
		}


	/*
	Return Section Group ID's
		Use:
			returnSectionGroups ();
		Returns:
			* array (id1, id2, etc.)
			* false
	*/
	function returnSectionGroups ()
		{
			$db = new extended_sqlObject;
			$db->query ("SELECT id, sort FROM {$db->tablePrefix}_sectiongroups ORDER BY 'sort' ASC");

			$sectionGroups = array ();
			while ($db->nextRecord ())
					array_push ($sectionGroups, $db->record['id']);

			return $sectionGroups;
		}


	/*
	Return Section ID's for specified Section Group
		Use:
			returnSections (SectionGroupID);
		Returns:
			* array (id1, id2, etc.)
			* false
	*/
	function returnSections ($id)
		{
			if (is_numeric ($id))
				{
					$db = new extended_sqlObject;
					$db->query ("SELECT id, sort FROM {$db->tablePrefix}_sections WHERE groupn='$id' ORDER BY 'sort' ASC");

					$sections = array ();
					while ($db->nextRecord ())
							array_push ($sections, $db->record['id']);

					return $sections;
				}

			return false;
		}


	/*
	Return Thread ID's for specified Section
		Use:
			returnThreads (threadID, startThreadNum);
		Returns:
			* array (id1, id2, etc.)
			* false
	*/
	function returnThreads ($id)
		{
			global $c;

			if (is_numeric ($id))
				{
					$returnSectionLevel = returnSectionLevel ($id);
					if ($c['level'] <= $returnSectionLevel['rlevel'])
						{
							$db = new extended_sqlObject;
							$db->query ("SELECT id FROM {$db->tablePrefix}_posts WHERE section='$id' ORDER BY 'id'");

							$threads = array ();
							while ($db->nextRecord ())
									array_push ($threads, $db->record['id']);

							return $threads;
						}
				}

			return false;
		}


	/*
	Return last post ID from a thread
		Use:
			returnLastPostID (#)
		Returns:
			* ID
			* false
	*/
	function returnLastPostID ($id)
		{
			global $c;

			$getPost = getPost ($id);

			if ($getPost['section'])
				{
					$db = new extended_sqlObject;
					$db->query ("SELECT id FROM {$db->tablePrefix}_posts WHERE thread='$id'");

					$returnThreads = array ();
					while ($db->nextRecord ())
							array_push ($returnThreads, $db->record['id']);

					rsort ($returnThreads);
					return $returnThreads[0];
				}

			return false;
		}


	/*
	Count posts on a thread
		Use:
			countPosts (threadID);
		Returns:
			* #
			* false
	*/
	function countPosts ($id)
		{
			if (is_numeric ($id))
				{
					$getPost = getPost ($id);
					if (($getPost['section']) && (!$getPost['thread']))
						{
							$db = new extended_sqlObject;
							$db->query ("SELECT COUNT(*) FROM {$db->tablePrefix}_posts AS rowcount WHERE thread='$id'");

							while ($db->nextRecord ())
									$count = $db->record[0];

							return $count;
						}
				}

			return false;
		}


	/*
	Count threads on a section
		Use:
			countThreads (sectionID);
		Returns:
			* #
			* false
	*/
	function countThreads ($id)
		{
			if (is_numeric ($id))
				{
					$db = new extended_sqlObject;
					$db->query ("SELECT COUNT(*) FROM {$db->tablePrefix}_posts AS rowcount WHERE section='$id'");

					while ($db->nextRecord ())
							$count = $db->record[0];

					return $count;
				}

			return false;
		}


	/*
	Print Thread and all Posts on that thread
		Use:
			printThread (threadID, startPostNum, order);
		Returns:
			* true
			* false
		Notes:
			Page is zero referenced
	*/
	function printThread ($id, $page, $order)
		{
			global $c;

			if (!(($order == 'asc') || ($order == 'desc')))
					return false;

			if ($getPost = getPost ($id))
				{
					$returnPostLevel = returnPostLevel ($id);
					if ((is_numeric ($id)) && (is_numeric ($page)) && ($c['level'] <= $returnPostLevel['rlevel']))
						{
							$page++;

							$countPosts = countPosts ($id);
							$postsPerPage = 10;												// POSTS PER PAGE
							$pages = intval (($countPosts / $postsPerPage) + 1);			// +1 because the number of pages has to be rounded *upwards* and intval rounds *downwards*
							$start = (($page - 1) * $postsPerPage);
							if ($order == 'asc')
									$start--;

							if (($page == 1) && ($order == 'asc'))
								{
									printPost ($id);
									$postsPerPage--;
									$start = 0;
								}

							$db = new extended_sqlObject;
							$db->query ("SELECT id FROM {$db->tablePrefix}_posts WHERE thread='$id' ORDER BY 'id' $order LIMIT $start, $postsPerPage");

							while ($db->nextRecord ())
									printPost ($db->record['id']);

							if (($page == $pages) && ($order == 'desc'))
									printPost ($id);

							if ($pages > 1)
								{
									echo 'Page: ';
									for ($i = 1; $i <= $pages; $i++)
										{
											if ($i == $page)
												{
													if ($i == 1)
															echo $i;

													else
															echo ', ' . $i;
												}

											else
												{
													if ($i == 1)
															echo "<A HREF='./?t=$id&p=" . ($i - 1) . "'>$i</A>";

													else
															echo ", <A HREF='./?t=$id&p=" . ($i - 1) . "'>$i</A>";
												}
										}
									echo '<P>';
								}

							if (countThreads ($getPost['section']) > 1)
									echo "<A HREF='./?s={$getPost['section']}' TARGET='_self'>:: Back to Section Overview ::</A>";

							return true;
						}

					actionLog (30);
					include ('./modules/error.php');
					return false;
				}

			echo 'Ho hum, doesn\'t look like that thread exists.';
			return false;
		}


	/*
	Print Post from SQL DB
		Use:
			printPost (ID#);
		Notes:
			* Users with a level of 3 are Global Mods and can change any post they please
	*/
	function printPost ($id)
		{
			global $templateDir, $c;

			$returnPostLevel = returnPostLevel ($id);
			if ($c['level'] <= $returnPostLevel['rlevel'])
				{
					$getPost = getPost ($id);
					if (!$getPost['title'])
						{
							$getThreadTitle = getPost ($getPost['thread']);
							$getPost['title'] = 'RE: ' . $getThreadTitle['title'];
						}

					$edited = explode (',', $getPost['edit']);

					$c['module'] = returnModule ('p', $id);

					$contents = fileRead ($templateDir . $c['module'] . '.html');

					preg_match ('/{post}(.+){\/post}/is', $contents, $matches);
					$contents = $matches[1];

					$search = array
						(
							'/{title}/i',
							'/{date}/i',
							'/{time}/i',
							'/{poster}/i',
							'/{content}/i',
							'/{pquote}/i',
							'/{id}/i',
							'/{edited-poster}/i',
							'/{edited-date}/i',
							'/{edited-time}/i',
							'/{edit}/i',
							'/{delete}/i'
						);

					$replace = array
						(
							$getPost['title'],
							$getPost['date'],
							$getPost['time'],
							$getPost['poster'],
							parse ('code', $getPost['content']),
							"<A HREF='?i=post&q=$id'>::&nbsp;Quote&nbsp;::</A>",
							$id,
							$edited[0],
							date ('j/m/Y', $edited[1]),
							date ('H:i:s', $edited[1]),
							"<A HREF='./?i=edit&id=$id' TARGET='_self'>Edit</A>",
							"<A HREF='./?i=postManip&a=delete&id=$id' TARGET='_self' onClick='return confirmSubmit()'>Delete</A>"
						);

					$contents = preg_replace ($search, $replace, $contents);

					if ((preg_match ('/{edited}(.+){\/edited}/i', $contents, $matches)) && ($getPost['edit']))
							$contents = str_replace ($matches[0], $matches[1], $contents);

					else
						{
							preg_match ('/{edited}(.+){\/edited}/i', $contents, $matches);
							$contents = str_replace ($matches[0], '', $contents);
						}

					$section = getSection (returnPostSection ($id));
					if
						(
							preg_match ('/{manip}(.+){\/manip}/is', $contents, $matches)
							&&
							$returnPostLevel
							&&
								(
										(
											$c['level'] <= $returnPostLevel['wlevel']
											&&
											$c['level'] <= 3
										)
									||
									$c['user'] == $getPost['poster']
									||
										(
											in_array ($c['user'], $section['moderators'])
											&&
											$c['user'] != 'x'
										)
								)
						)
							$contents = str_replace ($matches[0], $matches[1], $contents);

					else
						{
							preg_match ('/{manip}(.+){\/manip}/is', $contents, $matches);
							$contents = str_replace ($matches[0], '', $contents);
						}

					echo $contents;

					return true;
				}

			else
					return false;
		}



	/*
	Create User
		Use:
			$createUser = createUser (user, pass, email);
		Returns:
			* 'created'
			* Error String
	*/
	function createUser ($user, $pass, $email, $groupn)
		{
			$return = false;

			$db = new extended_sqlObject;
			$db->query ("SELECT user, email FROM {$db->tablePrefix}_users");

			$emails = array ();
			$users = array ();
			while ($db->nextRecord ())
				{
					array_push ($users, $db->record['user']);
					array_push ($emails, $db->record['email']);
				}

			if (in_array ($user, $users))
					$return = 'Username already taken.';

			if (in_array ($email, $emails))
					$return = 'That email address is already registered.';

			if (!preg_match ('/^[a-zA-Z0-9]{3,12}$/', $user) && $return == false)
					$return = 'Username did not fill requirements.';

			if (!preg_match ('/^[a-zA-Z0-9-]{6,25}$/', $pass) && $return == false)
					$return = 'Password did not fill requirements.';

			if ($user == $pass)
					$return = 'Password cannot be the same as Username.';

			if (
					!preg_match ('/^[\w\.-]+@[a-zA-Z0-9\.-]+$/', $email)
				||
					(
						(strlen ($email) < 7)
					||
						(strlen ($email) > 50)
					)
				&&
					($return == false)
				)
					$return = 'Email did not fill requirements.';

			if ($return == false)
				{
					if ($db->query ("INSERT INTO {$db->tablePrefix}_users (user, email, groupn, pass, datetime) VALUES ('" . mysql_escape_string ($user) . "', '" . mysql_escape_string ($email) . "', '" . mysql_escape_string ($groupn) . "', '" . md5 ($pass) . "', '" . time () . "')"))
						{
							actionLog (50);
							$return = 'created';
						}
				}

			return $return;
		}


	/*
	Verify User
		Use:
			$verifyUser = verifyUser (user, pass);
		Returns:
			* false - if auth failed for *any* reason
			* array(user,level) - if auth succeeded

		NOTE: ALREADY PREPARED FOR MULTIPLE GROUP ENTIRES SEPERATED BY COMMAS - RETURNS LOWEST GROUP LEVEL
	*/
	function verifyUser ($user, $pass)
		{
			$getUser = getUser ($user);
			$groups = explode (',', $getUser['groupn']);
			$levels = array ();
			foreach ($groups as $group)
				{
					$getUserGroup = getUserGroup ($group);
					array_push ($levels, $getUserGroup['level']);
				}

			sort ($levels);

			if ($levels[0] > 5)
					$levels[0] = 5;

			if ($getUser['pass'] == md5 ($pass))
				{
					return array
						(
							'user' => $getUser['user'],
							'level' => $levels[0]
						);
				}
		}


	/*
	Check User Cookie
		Use:
			$checkUserCookie = checkUserCookie ();
		Returns:
			* false - if auth failed for *any* reason
			* array(user,level) - if auth succeeded
	*/
	function checkUserCookie ()
		{
			return verifyUser ($_COOKIE['userUser'], $_COOKIE['userPass']);
		}


	/*
	Something went wrong Report
		Use:
			errorReport ('oh no!', $helpfulVarOrArray);
		Notes:
			* If it's passed an array it'll print out each index and value
	*/
	function errorReport ($error, $var)
		{
			global $buffering;
			echo "<B>ERROR:</B> $error.<BR>";
			if (is_array ($var))
				{
					if ($buffering)
							ob_end_clean ();

					echo '<B>VARIABLES PASSED:</B><BR>';
					print_r ($var);
					die ('.<P>Script Halted');
				}

			elseif (strlen ($var) > 0)
					if ($buffering)
							ob_end_clean ();

					echo "<B>VARIABLE PASSED:</B> $var.<BR>";
					die ('<P><B>Script Halted.</B>');
		}


	function postCheckReferer ()
		{
			global $HTTP_REFERER, $siteAddr;
			$formattedSiteAddr = preg_replace ('/^http:\/\/(www.)?(.+)\/$/i', '\\2', $SiteAddr);
			if (preg_match ('/' . parse ('regexp', $formattedsiteAddr) . '/i', $HTTP_REFERER))
					return true;
			else
					errorReport ('Posted material from other sites is not accepted', parse ('safe', $HTTP_REFERER));
		}


	/*
	Parser
		Use: echo parse (method (safe/code), string);
	*/
	function parse ($method, $string)
		{
			global $templateDir, $c;

			if ($method != 'safe' && $method != 'code' && $method != 'regexp')
					return false;

			if ($method == 'safe')
				{
					$htmlBreakerSearch = array
						(
							'<',
							'>',
							"'",
							'"'
						);

					$htmlBreakerReplace = array
						(
							'&lt;',
							'&gt;',
							'&#39;',
							'&quot;'
						);

					return stripslashes (str_replace ($htmlBreakerSearch, $htmlBreakerReplace, $string));
				}

			elseif ($method == 'regexp')
				{
					$regexpCharSearch = array ('\\', '^', '$', '.', '?', '*', '+', '{', '}', '(', ')', '[', ']', '|', '/');
					$regexpCharReplace = array ('\\\\', '\^', '\$', '\.', '\?', '\*', '\+', '\{', '\}', '\(', '\)', '\[', '\]', '\|', '\/');

					return str_replace ($regexpCharSearch, $regexpCharReplace, stripslashes ($string));
				}

			elseif ($method == 'code')
				{
					$string = parse ('safe', $string);

					$string = ' ' . $string . ' ';

					$specialCharSearch = array
						(
							'/\t/'
						);

					$specialCharReplace = array
						(
							'&nbsp;&nbsp;&nbsp;'
						);

					$oneOffSearch = array
						(
							'/\n/',
							'/\r/',
							'/\[\*\]/',
							'/(?<!http:\/\/)www\./i'
						);

					$oneOffReplace = array
						(
							'<BR>',
							'',
							'<LI>',
							'http://www.'
						);

					$basicSearch = array
						(
							'/\[b\](.+)\[\/b\]/iU',
							'/\[i\](.+)\[\/i\]/iU',
							'/\[u\](.+)\[\/u\]/iU',
							'/\[list\](.+)\[\/list\]/iU',
							'/\[nlist\](.+)\[\/nlist\]/iU',
							// '/\[pre\](.+)\[\/pre\]/iU',
							'/\[heading\]([^\n]+)\[\/heading\]/iU',
							'/\[left\](.+)\[\/left\]/iU',
							'/\[center\](.+)\[\/center\]/iU',
							'/\[centre\](.+)\[\/centre\]/iU',
							'/\[right\](.+)\[\/right\]/iU'
						);

					$basicReplace = array
						(
							'<B>\\1</B>',
							'<I>\\1</I>',
							'<U>\\1</U>',
							'<UL>\\1</UL>',
							'<OL>\\1</OL>',
							// '<HR><DIV CLASS=\'smallVerdana\'>Preformatted Text</DIV><BR><PRE>\\1</PRE><HR>',
							'<H3>\\1</H3>',
							'<DIV ALIGN=\'left\'>\\1</DIV>',
							'<DIV ALIGN=\'center\'>\\1</DIV>',
							'<DIV ALIGN=\'center\'>\\1</DIV>',
							'<DIV ALIGN=\'right\'>\\1</DIV>'
						);

					$advancedSearch = array
						(
							'/\[img\]((http:\/\/[a-zA-Z0-9\.\/-]+(\.gif|\.png|\.jpg)))\[\/img\]/iU',	// [img=]
							'/\[url=(http:\/\/[a-zA-Z0-9\.:-]+[\w\.&\?=#%\/-]+)\](.+)\[\/url\]/iU',		// [url=]
							'/\[iurl=([\w\.&\?=#%\/:-]+)\](.+)\[\/iurl\]/iU',							// [iurl=]
							'/\[email=([a-zA-Z0-9\._-]+@[\w\.-]+)\](.*)\[\/email\]/iU',					// [email=]
							'/\[colour=([a-zA-Z0-9\#]+)\](.*)\[\/colour\]/iU',							// [colour=]
							'/\[color=([a-zA-Z0-9\#]+)\](.*)\[\/color\]/iU'								// [color=]
						);

					$advancedReplace = array
						(
							'<IMG SRC=\'\\1\'>',														// [img=]
							'<A HREF=\'\\1\' TARGET=\'_blank\'>\\2</A>',								// [url=]
							'<A HREF=\'\\1\' TARGET=\'_self\'>\\2</A>',									// [iurl=]
							'<A HREF=\'mailto:\\1\'>\\2</A>',											// [email=]
							'<FONT COLOR=\'\\1\'>\\2</FONT>',											// [colour=]
							'<FONT COLOR=\'\\1\'>\\2</FONT>'											// [color=]
						);

					$finalSearch = array
						(
							'/(?<!\')(http:\/\/([a-zA-Z0-9\.:-]+[\w\.&\?=#%\/-]+))/i',					// http://
							'/(?<=\s|\>)([a-zA-Z0-9\._-]+@[\w\.-]+)/i',									// hide@address.com
						);

					$finalReplace = array
						(
							'<A HREF=\'\\1\' TARGET=\'_blank\'>\\2</A>',								// http://
							'<A HREF=\'mailto:\\1\'>\\1</A>',											// hide@address.com
						);

					// get quote template, or substitute default template
					if (is_file ($templateDir . $c['module'] . '.html'))
							$contents = fileRead ($templateDir . $c['module'] . '.html');
					else
							$contents = '';
					
					if (!preg_match ('/{quote}(.+){\/quote}/is', $contents, $matches))
							$quoteTemplate = '<HR><DIV CLASS=\'smallVerdana\'><B>|Quote|</B> Originally Posted By: {Poster}</DIV><BR>{Content}<HR>';
					else
							$quoteTemplate = $matches[1];
					//

					$string = preg_replace ($oneOffSearch, $oneOffReplace, $string);

					while (preg_match ('/\[quote=([a-zA-Z0-9]{3,12})\](.+)\[\/quote\]/iU', $string, $matches))	// done this way as it provides better nesting (as opposed to substituting \\\\1 etc. in the above template extraction, and then using preg_replace, which does it rather craply :)
						{
							$quoteTemplateSearch = array
								(
									'/{poster}/i',
									'/{content}/i'
								);

							$quoteTemplateReplace = array
								(
									$matches[1],
									$matches[2]
								);

							$quoteReplace = preg_replace ($quoteTemplateSearch, $quoteTemplateReplace, $quoteTemplate);
							$string = str_replace ($matches[0], $quoteReplace, $string);
						}

					// $string = preg_replace ('/\[pre\]^.*(.{50})$.*\[\/pre\]/isU', '[PRE]\\1[/PRE]', $string);

					$string = preg_replace ($basicSearch, $basicReplace, $string);
					$string = preg_replace ($advancedSearch, $advancedReplace, $string);
					$string = preg_replace ($finalSearch, $finalReplace, $string);

					$getSmilies = getSmilies ();
					$string = preg_replace ($getSmilies['regexp'], $getSmilies['img'], $string);	// Replace Smilies

					// my l33t regexp to parse complex urls (actually it's bugged if in use on more basic url's but there we are :))
					// /(?<!\')(http:\/\/[\w\.-]+)([\w\.\/-]*\/)([\w\.\/-]+)([\w\.&\?=#\/-]+)/i	array ( [0] => everything, ofc [1] => http://hostname [2] => /dir/tree/ [3] => file [4] GET vars )

					$string = wrap ($string);

					$string = preg_replace ($specialCharSearch, $specialCharReplace, $string);

					return stripslashes (trim ($string));
				}

			else
					return false;
		}


	/*
	Get Smiley code and image refs from file
		Use:
			$getSmilies = getSmilies ();
		Returns:
			* array (array (smileyCodes), array (sensitivity), array (formattedSmilies))
			* false
	*/
	function getSmilies ()
		{
			global $smileyDir;

			$contents = fileRead ('./smilies.txt');

			$contents = str_replace ("\r", '', $contents);
			$smilies = explode ("\n", $contents);

			$smileyCode = array ();
			$smileyRegexp = array ();
			$smileyImg = array ();
			for ($i = 0; $i < sizeof ($smilies); $i++)
				{
					if (preg_match ('/^([^\s]+)\s+(i|s)\s+([\w\.]+)$/i', $smilies[$i], $matches))
						{
							if (sizeof ($matches) == 4)
								{
									$smileySearchRegexp = parse ('regexp', $matches[1]);	// escape special regexp chars in smilies to ensure valid regexps
									$smileySearchRegexp = '/' . $smileySearchRegexp . '/';
									if ($matches[2] == 'i')
											$smileySearchRegexp .= 'i';			// check for sensitivity

									$replace = "<IMG SRC='{$smileyDir}{$matches[3]}' BORDER='0' ALT='$matches[1]'>";
									array_push ($smileyCode, $matches[1]);
									array_push ($smileyRegexp, $smileySearchRegexp);
									array_push ($smileyImg, $replace);
								}
						}
				}

			return array ('code' => $smileyCode, 'regexp' => $smileyRegexp, 'img' => $smileyImg);
		}


	/*
	Wrap output text
		Use:
			$newString = wrap ($string);
		Returns:
			* new string
		Notes:
			Only inserts &shy; in long words, and skips tags
	*/
	function wrap ($string)
		{
			for ($i = 0; $i < strlen ($string); $i++)
				{
					$char = substr ($string, $i, 1);

					if (($char == ' ') || ($char == '<') || ($char == '>'))
							$count = 0;

					else
							$count++;

					if ($char == '<')
							$inTag = true;

					if ($char == '>')
							$inTag = false;

					if (!$inTag)
						{
							if ($count < 26)
									$newString .= $char;

							else
								{
									$newString .= '&shy;' . $char;
									$count = 0;
								}
						}

					else
							$newString .= $char;
				}

			return $newString;
		}


	function actionLog ($action)
		{
			global $loggingLevel, $loggingLimit, $HTTP_REFERER, $HTTP_USER_AGENT, $HTTP_VIA, $REMOTE_ADDR, $SCRIPT_NAME, $_POST, $_GET, $c;

			if (!is_integer ($action))
					return false;

			$db = new extended_sqlObject;

			if (($loggingLevel != 0) && $loggingLevel)
				{
					$columns = 'user, datetime, actionid, ip, script, post, get';

					$values = "'{$c['user']}', '" . time () . "', '" . addslashes ($action) . "', '" . mysql_escape_string ($REMOTE_ADDR) . "', '" . mysql_escape_string ($SCRIPT_NAME) . "', '" . mysql_escape_string (serialize ($_POST)) . "', '" . mysql_escape_string (serialize ($_GET)) . "'";

					if ($loggingLevel > 1)
						{
							$columns .= ', host, proxy';
							$values .= ", '" . mysql_escape_string (gethostbyaddr($REMOTE_ADDR)) . "', '" . mysql_escape_string ($HTTP_VIA) . "'";
						}

					if ($loggingLevel > 2)
						{
							$columns .= ', referer, browser';
							$values .= "'" . mysql_escape_string ($HTTP_REFERER) . "', '" . mysql_escape_string ($HTTP_USER_AGENT) . "'";
						}

					$db->query ("INSERT INTO {$db->tablePrefix}_actionlog ($columns) VALUES ($values)");
				}
		}

	/*
	Get list of actions
		Use:
			$getActions = getActions ();
		Returns:
			* array (id => array, description => array)
	*/
	function getActions ()
		{
			$db = new extended_sqlObject;
			$db->query ("SELECT * FROM {$db->tablePrefix}_actions");

			$actions = array
				(
					'id' => array (),
					'description' => array ()
				);

			while ($db->nextRecord ())
				{
					array_push ($actions['id'], $db->record['id']);
					array_push ($actions['description'], $db->record['description']);
				}

			return $actions;
		}


	/*
	Get log of actions from db where you know the action id
		Use:
			$getActionLog = getActionLog (#);
		Returns:
			* array (see below fs)
	*/
	function getActionLog ($id)
		{
			$db = new extended_sqlObject;
			$db->query ("SELECT * FROM {$db->tablePrefix}_actionlog WHERE actionid='$id'");

			$actionLog = array
				(
					'id' => array (),
					'user' => array (),
					'datetime' => array (),
					'actionid' => array (),
					'ip' => array (),
					'script' => array (),
					'post' => array (),
					'get' => array (),
					'host' => array (),
					'proxy' => array (),
					'referer' => array (),
					'browser' => array ()
				);

			while ($db->nextRecord ())
				{
					array_push ($actionLog['id'], $db->record['id']);
					array_push ($actionLog['user'], $db->record['user']);
					array_push ($actionLog['datetime'], $db->record['datetime']);
					array_push ($actionLog['actionid'], $db->record['actionid']);
					array_push ($actionLog['ip'], $db->record['ip']);
					array_push ($actionLog['script'], $db->record['script']);
					array_push ($actionLog['post'], unserialize ($db->record['post']));
					array_push ($actionLog['get'], unserialize ($db->record['get']));
					array_push ($actionLog['host'], $db->record['host']);
					array_push ($actionLog['proxy'], $db->record['proxy']);
					array_push ($actionLog['referer'], $db->record['referer']);
					array_push ($actionLog['browser'], $db->record['browser']);
				}

			return $actionLog;
		}


	function trafficLog ()
		{
			global $c, $HTTP_USER_AGENT, $HTTP_REFERER;

			$db = new extended_sqlObject;

			$db->query ("INSERT INTO {$db->tablePrefix}_trafficlog VALUES ('" . time () . "', '{$c['user']}', '" . mysql_escape_string ($HTTP_REFERER) . "', '" . mysql_escape_string ($HTTP_USER_AGENT) . "', '{$c['section']}')");
		}


	/*
	Get log of traffic
		Use:
			$getTrafficLog = getTrafficLog ();
		Returns:
			* array ('datetime' => array, 'referer' => array, 'browser' => array)
	*/
	function getTrafficLog ()
		{
			$db = new extended_sqlObject;
			$db->query ("SELECT * FROM {$db->tablePrefix}_trafficlog");

			$trafficLog = array
				(
					'datetime' => array (),
					'user' => array (),
					'referer' => array (),
					'browser' => array ()
				);

			while ($db->nextRecord ())
				{
					array_push ($trafficLog['datetime'], $db->record['datetime']);
					array_push ($trafficLog['user'], $db->record['user']);
					array_push ($trafficLog['referer'], $db->record['referer']);
					array_push ($trafficLog['browser'], $db->record['browser']);
				}

			return $trafficLog;
		}


	function fileRead ($file)
		{
			if (!$fopen = fopen ($file, 'r'))
				{
					echo "Error opening $file";
					return false;
				}

			if (!$contents = fread ($fopen, filesize ($file)))
				{
					echo "Error reading $file";
					return false;
				}

			if (!fclose ($fopen))
				{
					echo "Error closing $file";
					return false;
				}

			return $contents;
		}

	function fileAppend ($file, $string)
		{
			if (!$fopen = fopen ($file, 'a'))
				{
					echo "Error opening $file";
					return false;
				}

			if (!fwrite ($fopen, $string))
				{
					echo "Error writing to $file";
					return false;
				}

			return true;
		}

	function fileWrite ($file, $string)
		{
			if (!$fopen = fopen ($file, 'w'))
				{
					echo "Error opening $file";
					return false;
				}

			if (!fwrite ($fopen, $string))
				{
					echo "Error writing to $file";
					return false;
				}

			return true;
		}
?>
Return current item: PhabCMS