Location: PHPKode > projects > ACollab > include/vitals.inc.php
<?php
/****************************************************************************************/
/* ACollab                                                                              */
/****************************************************************************************/
/* Copyright (c) 2002-2003  Adaptive Technology Resource Centre / University of Toronto */
/*                                                                                      */
/* http://atutor.ca/acollab                                                             */
/*                                                                                      */
/* This program is free software. You may redistribute it and/or                        */
/* modify it under the terms of the GNU General Public License                          */
/* as published by the Free Software Foundation; either version 2 of the License,       */
/* or (at your option) any later version.                                               */
/*                                                                                      */
/* This program is distributed in the hope that it will be useful, but                  */
/* WITHOUT ANY WARRANTY; without even the implied warranty of                           */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.                                 */
/* See the GNU General Public License for more details.                                 */
/*                                                                                      */
/* You may access the GNU General Public License at:                                    */
/* http://www.opensource.org/licenses/gpl-license.php                                   */
/*                                                                                      */
/* You may contact the Adaptive Technology Resource Centre at                           */
/* Robarts Library, University of Toronto                                               */
/* 130 St. George Street, Toronto, Ontario, Canada M5S 1A5                              */
/* Further contact information is available at http://www.utoronto.ca/atrc/             */
/****************************************************************************************/
/* Programmer:                                                                          */
/* Joel Kronenberg - ATRC                                                               */
/****************************************************************************************/

/* configuration options: */

error_reporting(E_ALL ^ E_NOTICE);

	error_reporting(0);
		include(AC_INCLUDE_PATH.'config.inc.php');
	error_reporting(E_ALL ^ E_NOTICE);
	if (!defined('AC_INSTALL') || !AC_INSTALL) {
		$relative_path = substr(AC_INCLUDE_PATH, 0, -strlen('include/'));
		echo 'ACollab does not appear to be installed. <a href="'.$relative_path.'install/">Continue on to the installation</a>.';
		exit;
	}

require(AC_INCLUDE_PATH.'lib/constants.inc.php');
require(AC_INCLUDE_PATH.'lib/date_functions.inc.php');
require(AC_INCLUDE_PATH.'lib/lang_constants.inc.php');

if (strpos(ini_get('arg_separator.input'), ';') !== false) {
	define('SEP', ';');
} else {
	define('SEP', '&');
}


/* User Types:	*/
define('USER_INVALID',		0);
define('USER_CLIENT',		1); // want to change this to USER_REGULAR
define('USER_GROUP_ADMIN',	2); // group admin
define('USER_ADMIN',		3); // want to change this to USER_SUPER_ADMIN
define('USER_RETURN_CHECK', 4); // return the status instead of bailing to a login page


/* Languages:	*/
define('LANG_EN',	1);
define('LANG_FR',	2);
/* add support for additional languages as needed */


/* valid date format_types:						*/
/* @see ./include/lib/date_functions.inc.php	*/
define('AT_DATE_MYSQL_DATETIME',	1); /* YYYY-MM-DD HH:MM:SS	*/
define('AT_DATE_MYSQL_TIMESTAMP_14',2); /* YYYYMMDDHHMMSS		*/
define('AT_DATE_UNIX_TIMESTAMP',	3); /* seconds since epoch	*/
define('AT_DATE_INDEX_VALUE',		4); /* 0-x, index into a date array */

define('AT_DATE_SHOW_DATES',		1); /* show day, month, year */
define('AT_DATE_SHOW_TIME',			2); /* show time fields */

/* forum regular member rights */
define('FORUM_NONE',  0);
define('FORUM_VIEW',  1);
define('FORUM_REPLY', 2);
define('FORUM_START', 4);

define('FILE_DRAFTING', 0);
define('FILE_LIBRARY',	1);

/* courtyard_priv privileges: */
define('COURTYARD_PRIV_CLIENT',				1);
define('COURTYARD_PRIV_GROUP_CREATE',		2);
define('COURTYARD_PRIV_GROUP_ACCESS',		3);
define('COURTYARD_PRIV_ADMIN',				4);
define('COURTYARD_PRIV_GROUP_ACCESS_CREATE',5);

/* _archive ? _comment ? */

	/* session variables */
	session_name('ATutorID');
	session_start();
	session_register('member_id');
	session_register('status');		/* 0=undefined, or one of USER_CLIENT or USER_ADMIN or USER_GROUP_ADMIN */
	session_register('lang');
	session_register('login');
	session_register('group_id');
	session_register('show_feedback');
	session_register('time_zone');	$_SESSION['time_zone'] = -5;
	session_register('courtyard_priv'); /* COURTYARD_PRIV_GROUP_CREATE | COURTYARD_PRIV_GROUP_ACCESS | COURTYARD_PRIV_CLIENT | COURTYARD_PRIV_ADMIN */

if ($_SESSION['course_id']) {
	define('MEMBERS_TABLE_PREFIX', AT_TABLE_PREFIX);
} else {
	define('MEMBERS_TABLE_PREFIX', TABLE_PREFIX);
}


/* database connection */
if (AT_INCLUDE_PATH !== 'NULL') {
	$db = @mysql_connect(DB_HOST . ':' . DB_PORT, DB_USER, DB_PASSWORD);
	if (!$db) {
		/* AT_ERROR_NO_DB_CONNECT */
		echo 'Unable to connect to db.';
		exit;
	}
	if (!mysql_select_db(DB_NAME, $db)) {
		echo 'DB connection established, but database "'.DB_NAME.'" cannot be selected.';
		exit;
	}

	/* development uses a common language db */
	if (file_exists(AC_INCLUDE_PATH.'cvs_development.inc.php')) {
		require(AC_INCLUDE_PATH.'cvs_development.inc.php');
	} else {
		define('TABLE_PREFIX_LANG', TABLE_PREFIX);
		define('AC_CVS_DEVELOPMENT', '');

		$lang_db =& $db;
	}
}


/* template language variables */
require(AC_INCLUDE_PATH.'lib/select_lang.inc.php');





function my_add_null_slashes( $string ) {
    return ( $string );
}

if (get_magic_quotes_gpc()==1) {
	$addslashes = 'my_add_null_slashes';
} else {
	$addslashes = 'addslashes';
}

/* Force a specific bit(pattern) to ON */ 
function set_bit( &$bitfield, $bit ) { 
	$bitfield |= $bit; 
} 

/* Return true or false, depending on if the bit is set */ 
function query_bit( $bitfield, $bit ) {	
	return ( $bitfield & $bit ) ? true : false;
} 

function authenticate() {
	$num_args = func_num_args();
	$args 	  = func_get_args();

	$auth = false;
	
	if ($_SESSION['status'] == USER_ADMIN) {
		$auth = true;
	}

	for ($i=0; $i < $num_args; $i++) {
		if ($args[$i] == USER_RETURN_CHECK) {
			$return_check = true;
		} else {
			if ($_SESSION['status'] == $args[$i]) {
				$auth = true;
			}
		}
	}

	if (!$auth) {
		if ($return_check) {
			return false;
		}
		/**
		//debug($_SESSION);
		echo 'you are being redirect to the sign in page. what happened?';
		exit;
		/***/
		global $_base_href;
		header('Location: '.$_base_href.'sign_in.php');
		exit;
	}


	/* we can assume that $return_check is true, but doesn't really matter either way */
	return true;
}

function addd_user_online() {
	if ($_SESSION['member_id'] == 0 || $_SESSION['group_id'] == 0) {
		return;
	}
	global $db;

    $expiry = time() + 900; // 15min
    $sql    = "REPLACE INTO ".TABLE_PREFIX."users_online VALUES ($_SESSION[member_id], $_SESSION[group_id], $expiry)";
    $result = mysql_query($sql, $db);

	/* garbage collect and optimize the table every so often */
	mt_srand((double) microtime() * 1000000);
	$rand = mt_rand(1, 20);
	if ($rand == 1) {
		$sql = 'DELETE FROM '.TABLE_PREFIX.'users_online WHERE expiry<'.time();
		$result = @mysql_query($sql, $db);

		$sql = 'OPTIMIZE TABLE '.TABLE_PREFIX.'users_online';
		$result = @mysql_query($sql, $db);
	}
}

/****************************************************/
/* update the user online list						*/
	if ($_SESSION['group_id']) {
		$new_minute1 = time()/60;
		$diff1       = abs($_SESSION['last_updated_acollab'] - $new_minute1);
		if ($diff1 > ONLINE_UPDATE) {
			addd_user_online();
			$_SESSION['last_updated_acollab'] = $new_minute1;
		}
	}


function debug($value) {
	echo '<pre style="border: 1px black solid; padding: 0px; margin: 10px;">';

	ob_start();
	print_r($value);
	$str = ob_get_contents();
	ob_clean();

	$str = str_replace('<',		'&lt;', $str);
	$str = str_replace('[',		'<span style="color: red; font-weight: bold;">[', $str);
	$str = str_replace(']',		']</span>', $str);
	$str = str_replace('=>',	'<span style="color: blue; font-weight: bold;">=></span>', $str);
	$str = str_replace('Array', '<span style="color: purple; font-weight: bold;">Array</span>', $str);
	echo $str;
	echo '</pre>';
}

function getMessage($codes) {
	/* this is where we want to get the msgs from the database inside a static variable */
	static $_msgs;

	if (!isset($_msgs)) {
		global $lang_db;

		/* get $_msgs from the DB */
		if ($_SESSION['lang'] == 'en') {
			$sql	= "SELECT * FROM ".TABLE_PREFIX_LANG."lang_base WHERE variable='feedback'";
		} else {
			$sql	= "SELECT * FROM ".TABLE_PREFIX_LANG."lang2 WHERE variable='feedback' AND lang='$_SESSION[lang]'";
		}
		$result	= mysql_query($sql, $lang_db);
		while ($row = @mysql_fetch_assoc($result)) {
			$_msgs[constant($row['key'])] = $row['text'];
		}
	}

	if (is_array($codes)) {
		/* this is an array with terms to replace */
		$code		= array_shift($codes);
		$message	= $_msgs[$code];
		$terms		= $codes;

		/* replace the tokens with the terms */
		foreach ($terms as $index => $term) {
			$search[] = '%'.($index + 1);
		}
		$message = str_replace($search, $terms, $message);
	} else {
		$message = $_msgs[$codes];

		if ($message == '') {
			$message = 'NO LANG '.$codes;
		}
		$code = $codes;
	}
	return $message;
}

function print_errors( $errors ) {
	global $_template;
	if (empty($errors)) {
		return;
	}

	?>
	<table border="0" class="errbox" cellpadding="3" cellspacing="2" width="90%" summary="" align="center">
	<tr class="errbox">
	<td>
		<h3 class="err"><img src="images/bad.gif" align="top" alt="" class="img" /> <?php echo _AC('error'); ?></h3>
		<?php
			print_items($errors);
			$errors = NULL;
		?>
		</td>
	</tr>
	</table>
<?php
}


function print_warnings( $warnings ) {
	if (empty($warnings)) {
		return;
	}

	global $_base_path;

	?>	<br />
	<table border="0" class="wrnbox" cellpadding="3" cellspacing="2" width="90%" summary="" align="center">
	<tr class="wrnbox">
	<td>
		<h3><img src="images/warning_x.gif" align="top" class="menuimage5" alt="<?php echo _AC('warning'); ?>" /><?php echo _AC('warning'); ?></h3><hr />
		<?php

			print_items($warnings);


		?>
		</td>
	</tr>
	</table>
	<br />
<?php
}


function print_feedback( $feedback ) {
	if (empty($feedback)) {
		return;
	}
	if ($_SESSION['show_feedback'] == $_SERVER['PHP_SELF']) {
		return;
	}
	
	?>
	<table border="0" class="fbkbox" cellpadding="3" cellspacing="2" width="90%" summary="" align="center">
	<tr class="fbkbox">
	<td><h3 class="good"><img src="images/feedback.gif" align="top" alt="" class="img" /> <?php echo _AC('feedback'); ?></h3>
		<?php
			print_items($feedback);
		?></td>
	</tr>
	</table>
	<br />
<?php
}


function print_items( $items ) {
	if (!$items) {
		return;
	}

	$temp_items = intval($items);
	if (($temp_items >0) && ($temp_items == $items)) {
		$items = intval($items);
	}

	if (is_object($items)) {
		/* this is a PEAR::ERROR object.	*/
		/* for backwards compatability.		*/
		echo $items->getMessage();
		echo '.<p>';
		echo '<small>';
		echo $items->getUserInfo();
		echo '</small></p>';

	} else if (is_array($items)) {
		/* this is an array of errors */
		echo '<ul class="msg">';
		foreach($items as $e => $info){
			echo '<li>'.getMessage($info).'</li>';
		}
		echo'</ul>';
	} else if (is_int($items)){
		/* this is a single error not an array of errors */
		echo '<ul class="msg">';
		echo '<li>'.getMessage($items).'</li>';
		echo '</ul>';
	
	} else {
		/* not really sure what this is.. some kind of string.	*/
		/* for backwards compatability?							*/
		debug($items);
		echo '<ul>';
		echo '<li>'.$items.'</li>';
		echo'</ul>';
	}
}

	/*
		$args[0] = the key to the format string $_template[key]
		$args[1..x] = optional arguments to the formatting string 
	*/
	function & _AC( ) {
		static $_template;

		if (!isset($_template)) {
			global $lang_db;
			/* get $_template from the DB */
			if ($_SESSION['lang'] == 'en') {
				$sql	= "SELECT * FROM ".TABLE_PREFIX_LANG."lang_base WHERE variable='template'" . AC_CVS_DEVELOPMENT;
			} else {
				$sql	= "SELECT * FROM ".TABLE_PREFIX_LANG."lang2 WHERE variable='template' AND lang='$_SESSION[lang]'" . AC_CVS_DEVELOPMENT;
			}
			$result	= mysql_query($sql, $lang_db);
			while ($row = mysql_fetch_assoc($result)) {
				$_template[$row['key']] = $row['text'];
			}
		}

		$num_args = func_num_args();
		$args 	  = func_get_args();

		$format		= array_shift($args);

		$c_error	= error_reporting(0);
		$outString	= vsprintf($_template[$format], $args);
		if ($outString === false) {
			return ('[Error parsing language.'."\n".'Variable: '.$format.'. Value: '.$_template[$format].'. Language: '.$_SESSION['lang'].']');
		}
		error_reporting($c_error);

		if (empty($outString)) {
			return '['.$format.']';
			return ('[Error missing language.'."\n".'Variable: '.$format.'. Language: '.$_SESSION['lang'].']');
		}
		
		return $outString;
	}

function get_login($id){
	global $db;
	static $cached_logins = array();

	$id		= intval($id);

	if (!isset($cached_logins[$id])) {
		$sql	= "SELECT login FROM ".MEMBERS_TABLE_PREFIX."members WHERE member_id=$id";
		$result	= mysql_query($sql, $db);
		$row	= mysql_fetch_array($result);
		$cached_logins[$id] = $row['login'];
	}

	return $cached_logins[$id];
}

function get_forum_info($fid) {
    global $db;

    $sql    = "SELECT title, regular_rights FROM ".TABLE_PREFIX."forums WHERE forum_id=$fid AND group_id=$_SESSION[group_id]";
    $result = mysql_query($sql, $db);
    $row    = mysql_fetch_array($result);

	return $row;
}

function authenticate_forum($forum_status, $access) {
	if ($_SESSION['status'] == USER_GROUP_ADMIN) {
		return true;
	}

	return query_bit($forum_status, $access);
}

function & get_group($group_id) {
	return get_groups(true, true, $group_id);
}

function & get_groups($col, $order, $group_id = 0) {
    global $db;

	$rows	= array();

	if ($group_id) {
	    $sql    = "SELECT * FROM ".TABLE_PREFIX."groups WHERE group_id=$group_id AND course_id=$_SESSION[course_id]";
	} else {
		$sql    = "SELECT * FROM ".TABLE_PREFIX."groups WHERE course_id=$_SESSION[course_id] ORDER BY $col $order";
	}
	$result = mysql_query($sql, $db);
	while ($row = @mysql_fetch_assoc($result)) {
		$rows[] = $row;
	}
	if (count($rows) == 0) {
		return false;
	}

	if ($group_id) {
		return current($rows);
	}
	return $rows;
}

function & get_province($province_id) {
	return get_provinces(true, true, $province_id);
}

function & get_provinces($col, $order, $province_id = 0) {
    global $db;

	$rows	= array();

	if ($province_id) {
	    $sql    = "SELECT * FROM ".TABLE_PREFIX."provinces WHERE province_id=$province_id";
	} else {
		$sql    = "SELECT * FROM ".TABLE_PREFIX."provinces ORDER BY $col $order";
	}
	$result = mysql_query($sql, $db);
	while ($row = mysql_fetch_assoc($result)) {
		$rows[] = $row;
	}
	if (count($rows) == 0) {
		return false;
	}

	if ($province_id) {
		return current($rows);
	}
	return $rows;
}

/*
function get_folders($folder_id = 0, $course = false) {
    global $db;

	$rows	= array();
	if ($folder_id) {
	    $sql    = "SELECT * FROM ".TABLE_PREFIX."folders WHERE folder_id=$folder_id AND group_id=$_SESSION[group_id]";
	} else if (!$course) {
		$sql    = "SELECT * FROM ".TABLE_PREFIX."folders WHERE group_id=$_SESSION[group_id] ORDER BY member_id, title";
	} else {
		$sql    = "SELECT F.*, G.title AS g_title FROM ".TABLE_PREFIX."folders F INNER JOIN ".TABLE_PREFIX."groups G USING (group_id) WHERE G.course_id=$_SESSION[course_id] ORDER BY F.title";
	}
	$result = mysql_query($sql, $db);

	if (!$course) {
		$rows[0] = array('folder_id' => 0, 'member_id' => $_SESSION['member_id'], 'title' => _AC('your_personal_folder'));
	}

	while ($row = mysql_fetch_assoc($result)) {
		$rows[$row['folder_id']] = $row;
	}

	if (count($rows) == 0) {
		return array();
	}

	if ($cat_id) {
		return current($rows);
	}
	return $rows;
}
*/

function get_children($folder_id) {
	global $db;

	$sql    = "SELECT * FROM ".TABLE_PREFIX."folders WHERE group_id=$_SESSION[group_id] AND parent_folder_id=$folder_id ORDER BY member_id, title";
	$result = mysql_query($sql, $db);
	while ($row = mysql_fetch_assoc($result)) {
		$rows[$row['folder_id']] = $row;
	}

	if (count($rows) == 0) {
		return array();
	}

	return $rows;
}

function print_popup_help($help, $align = 'left') {
	return;
	if (!is_array($help)) {
		$text = _AC($help);
		$text = str_replace('"','&quot;',$text);
		$text = str_replace("'",'&#8217;',$text);
		$text = str_replace('`','&#8217;',$text);
		$text = str_replace('<','&lt;',$text);
		$text = str_replace('>','&gt;',$text);

		echo '<a href="popuphelp.php?h='.$help.'"   onfocus="this.className=\'highlight\'" onblur="this.className=\'\'" target="_'.$help.'" onmouseover="return overlib(\'&lt;small&gt;'.$text.'&lt;/small&gt;\', CAPTION, \''._AC('help').'\', RIGHT);" onmouseout="return nd();"><img src="images/help.gif" border="0" class="img2" alt="'._AC('help').'" /></a>&nbsp;';
	}
}

if (version_compare(phpversion(), '5.0') < 0) {
	function scandir($dirstr) {
		$files = array();
		$fh = opendir($dirstr);
		while (false !== ($filename = readdir($fh))) {
			array_push($files, $filename);
		}
		closedir($fh);
		return $files;
	} 
}

function urlencode_feedback($f) {
	if (is_array($f)) {
		return urlencode(serialize($f));
	}
	return $f;
}

/**
* Determines if user has notification for notifier_name enabled
* @example check_notification($row['notifications'], NOTFY_FORUM)
* @access  private
* @param   string $notfier_name				the name of the notifier
* @param   string $member_notifications		the notifications bits for the user
* @return  bool								enabled or disabled
* @author  Shozub Qureshi
*/
function check_notification($member_notifications, $notifier_name) {
	global $_nots;
	
	//obtain bits for notifier_name
	foreach ($_nots as $key => $not) {
		if ($key == constant($notifier_name)) {
			$notifier = $key;
		}
	}

	//determine if user has that privilege enabled
	$result = query_bit($member_notifications, $notifier);
	return $result;
}

function notify_subscribers($notifier_name) {
	global $db;

	$sql    = "SELECT notifications, member_id FROM ".TABLE_PREFIX."groups_members WHERE group_id=$_SESSION[group_id]";
	$result = mysql_query($sql, $db);

	
	while ($row = mysql_fetch_assoc($result)) {
		//if notiofcation enabled for this user 
		if (check_notification($row['notifications'], $notifier_name)) {
			$members[] = $row['member_id'];
		}
	}
	if ($members) {
		$users = implode($members, " OR member_id=");

		$sql1      = "SELECT email FROM ".TABLE_PREFIX."members WHERE member_id=($users)";
		$user_list = mysql_query($sql1, $db);
		return $user_list;
	}
	else {
		return false;
	}
}

?>
Return current item: ACollab