Location: PHPKode > projects > BugIn and Ticketing System > bugin-0.65/lib/bugin.inc.php
<?php
/* global definitions {{{1 */
/* User Options {{{2 */
define ("OPTION_FRAMES", 1);
define ("OPTION_NOTIFY", 2);
define ("OPTION_POPUP", 4);
define ("OPTION_REFRESH_LIST", 8);
define ("OPTION_LIST_SORT_REVERSE", 16);
define ("OPTION_SHORT_NOTIFICATION_NOTIFY", 32);
define ("OPTION_NO_PAGING", 64);

// ADMIN user options
define ("OPTION_NOT_LDAP_DEPENDANT", 256);
define ("OPTION_DISABLED", 512);
/* User Options }}}2 */

/* Admin User IDs {{{2 */
define ("USER_SYSTEM", -1);
define ("USER_SCHEDULER", -2);
/* Admin User IDs }}}2 */

define ("PROJECT_NO_SEARCH_NOT_IN_GROUP", 1);
define ("PROJECT_NO_ADD_NOT_IN_GROUP", 2);

/* Message Types (for buginError) {{{2 */
define ("MESSAGE_ERROR", 0); // Error Message
define ("MESSAGE_DEBUG", 1); // Debug Message
define ("MESSAGE_INFO", 2); // Notification Message
/* Message Types (for buginError) }}}2 */

/* ACL Bit Flags {{{2 */
define("ACL_READ", 1); // ACL flag read
define("ACL_ADD", 2); // ACL flag modify
define("ACL_MODIFY", 4); // ACL flag modify
/* ACL Bit Flags }}}2 */
/* global definitions }}}1 */

function getBaseString($value, $base) 
{
    $baseChars = array('0', '1', '2', '3', '4', '5',
                       '6', '7', '8', '9', 'a', 'b',
                       'c', 'd', 'e', 'f', 'g', 'h',
                       'i', 'j', 'k', 'l', 'm', 'n',
                       'o', 'p', 'q', 'r', 's', 't',
                       'u', 'v', 'w', 'x', 'y', 'z'
                     );

    $remainder = 0;
    $newval = "";
    
    while ( $value > 0 ) 
    {
        $remainder = $value % $base;
        $value = ( ($value - $remainder)/ $base );
        $newval .= $baseChars[$remainder];
    }
    
    return strrev($newval);
}


// Ticket functions {{{1
/* function isValidOwner($userinfo, $validOwners) {{{2
 Checks to see if $userInfo is in the list of $validOwners */
function isValidOwner($userinfo, $validOwners) {
	if (count($validOwners)) {
		while (list($key, $value) = each($validOwners)) {
			if ($value['uid'] == $userinfo['uid'])
				return 1;
		}
	}
	return 0;
}
/* }}}2 */

/* function buginError($message, $debugMsg = 0)  {{{2
	For displaying errors, etc.... */
function buginError($message, $debugMsg = MESSAGE_ERROR, $returnError = 0) {
	global $options;
	static $errors = "";

	switch ($debugMsg) {
		case MESSAGE_DEBUG:
			if ($options['debug']) {
				$err = "<span class=\"buginDebug\">Debug:</span> <span class=\"buginDebugMessage\">{$message}</span>";
			}
			else {
				return;
			}
			break;
		case MESSAGE_INFO:
			$err = "<span class=\"buginInfo\">Info:</span> <span class=\"buginInfoMessage\">{$message}</span>";
			break;
		case MESSAGE_ERROR:
			$err = "<span class=\"buginError\">Error:</span> <span class=\"buginErrorMessage\">{$message}</span>";
			break;
		default:
			break;
	}

	$errors .= $err . "\n";
	if ($returnError)
		return($err);
	else
		echo $err."<br />\n";


}
/* }}}2 */

/* function ticketByShortDesc($short_desc) {{{2
	Find an open ticket based upon the short description */
function ticketByShortDesc($short_desc) {
	global $options;
	global $bugDatabase;
	$ticketList = $bugDatabase->getTicketList("!(STATUS IN ({$options['closedNum']}))");

	while (list($key, $value) = each($ticketList)) {
		if ($value['short_desc'] == $short_desc) {
			return $value['id'];
		}
	}
	return NULL;
}
/* }}}2 */

/* function getACL($ticket) {{{2
	gets the ACL for a ticket, returns flag for current user */
function getACL($ticket) {
	global $userinfo;
	global $bugDatabase;
	global $options;

	$flag = 0;

	if ($options['anonTicketAccess'])
		$flag |= ACL_READ;
	
	if ($ticket['creator'] == $_SESSION['userinfo']['uid']) {
		$flag |= ACL_READ;
		$flag |= ACL_ADD;
		$flag |= ACL_MODIFY;
	}

	if ($bugDatabase->lists['project'][$ticket['project']]['acl'][$userinfo['uid']] & ACL_READ) {
		$flag |= ACL_READ;
	}

	if ($bugDatabase->lists['project'][$ticket['project']]['acl'][$userinfo['uid']] & ACL_ADD) {
		$flag |= ACL_ADD;
	}

	if ($bugDatabase->lists['project'][$ticket['project']]['acl'][$userinfo['uid']] & ACL_MODIFY) {
		$flag |= ACL_MODIFY;
	}

	return $flag;
}

/* }}}2 */
/* Ticket Functions }}}1 */

// SQL Functions {{{1
/* function sqlAdd (&$string, $add, $sql, $end = 0) {{{2
     For adding ADD to a SQL statement that has multiple conditions... */
function sqlAdd (&$string, $add, $sql, $end = 0) {
	if (!strlen($string) && !$end) {
		$string = "AND (".$add;
		buginError("Beginning new AND statement <i>$string</i>", MESSAGE_DEBUG);
	}
	elseif ($end == 1) {
		$string .= ")";
		buginError("Ended AND statement <i>$string</i>", MESSAGE_DEBUG);
	}
	elseif (strlen($string)) {
		$string .= " $sql ".$add;
		buginError("Appending AND statement <i>$string</i>", MESSAGE_DEBUG);
	}
}
/* }}}2 */
/* SQL Functions }}}1 */

// User Functions {{{1
/* function isUserThere($user, $userList) {{{2
	Find a user inside the user list. */
function isUserThere($user, $userList) {
	while (list($key, $value) = each($userList)) {
		if ($value['username'] == $user) {
			return 1;
		}
	}
	return 0;
}

/* }}}2 */

/* function searchUserList($email) {{{2
		Searches the user list for the user ID that has a specific e-mail address. */
function searchUserList($email) {
	global $bugDatabase;

	reset($bugDatabase->lists['user']);
	while (list($key, $value) = each($bugDatabase->lists['user'])) {
		if ($value['email'] == $email) {
			return $value['uid'];
		}
	}
	return -1;
}

/* }}}2 */

/* function signupUser($name, $email,  $pass, $pass2, $phone) {{{2
	signes up a user */
function signupUser($uname, $fname, $email, $pass, $pass2, $phone, $lang) {
	global $bugDatabase;
	global $options;
	global $verbage;

	if (empty($lang)) {
		$lang = $options['defaultLanguage'];
	}


	if (strlen($uname) < $options['unameMinLength']) {
		$signup['errors']['uname'] = "*";
		$signup['errors']['text'] .= "{$verbage['err_usr_length']}<br>\n";
	}
	elseif (isUserThere($uname, $bugDatabase->lists['user'])) {
		$signup['errors']['uname'] = "*";
		$signup['errors']['text'] .= "{$verbage['err_usr_exists']}.<br>\n";
	}

	if (strlen($pass) < $options['passMinLength']) {
		$signup['errors']['pass'] = "*";
		$signup['errors']['text'] .= "{$verbage['err_pwd_length']}<br>\n";
	}

	if ($pass != $pass2) {
		$signup['errors']['passmatch'] = "*";
		$signup['errors']['text'] .= "{$verbage['err_pwd_not_match']}<br>\n";
	}

	if (!eregi($options['emailEreg'], $email)) {
		$signup['errors']['email'] = "*";
		$signup['errors']['text'] .= "{$verbage['err_invalid_email']}<br>\n";
	}

	// Made ereg for phone # setable.
	if (!eregi($options['phoneEreg'], $phone)) {
		$signup['errors']['phone'] = "*";
		$signup['errors']['text'] .= "{$verbage['err_invalid_phone']}\n";
	}

	if (isset($signup['errors'])) {
		return ($signup['errors']);
	}
	else {
		// We're going to update a DB here, you know?
		buginError("Signing up user <b>{$uname}</b>", MESSAGE_INFO);
		$upNum = 0;

		$upNumField = 0;

		$update[0]['action'] = "add";
		$update[0]['tableName'] = "users";
		$update[0]['modify'][0]['fieldName'] = "username";
		$update[0]['modify'][0]['fieldValue'] = $bugDatabase->db->qstr($uname);
		$update[0]['modify'][1]['fieldName'] = "pass";
		$update[0]['modify'][1]['fieldValue'] = $bugDatabase->db->qstr(md5($pass));
		$update[0]['modify'][2]['fieldName'] = "name";
		$update[0]['modify'][2]['fieldValue'] = $bugDatabase->db->qstr($fname);
		$update[0]['modify'][3]['fieldName'] = "email";
		$update[0]['modify'][3]['fieldValue'] = $bugDatabase->db->qstr($email);
		$update[0]['modify'][4]['fieldName'] = "phone";
		$update[0]['modify'][4]['fieldValue'] = $bugDatabase->db->qstr($phone);
		$update[0]['modify'][5]['fieldName'] = "user_group";
		$update[0]['modify'][5]['fieldValue'] = $bugDatabase->db->qstr($options['defaultGroups']);
		$update[0]['modify'][6]['fieldName'] = "lang";
		$update[0]['modify'][6]['fieldValue'] = $lang;

		$bugDatabase->alterDb($update);

		// Update the user list...
		$bugDatabase->getUserList();

	}

}

/* }}}2 */

/* function checkUser() {{{2
	checks the udb for an e-mail address */
function checkUser() {
	global $options;
	global $bugDatabase;

	$error = 0;

	if ($_REQUEST['email']) {
		$_SESSION['email'] = $_REQUEST['email'];
	}

	$email = $_SESSION['email'];

	if (!isset($email) || ($email == "")) {
		echo "You must supply your e-mail address.";
		return 0;
	}
	else {

		if ( $options['ldapEnable'] ) {
			include_once("{$options['buginLibBase']}ldap.inc.php");
			if (!$info = ldapGetUserByEmail($email)) {
				$_SESSION['message'] = "Could not find {$email} in database.";
				$error = 1;
			}
			else {
				$name = $info['name'];
				$uname = $info['username'];
				$phone = $info['phone'];
				$email = $info['email'];
			}
		}

		// If the user does not exist in the system....
		if (!$error && ($uid = searchUserList($email)) == -1) {
			if (!$options['ldapEnable'] ) {
				$name = $email;
				$unameext = "";
				$phone = "0000";
				$lang = $options['defaultLanguage'];
				// Sign up the user...
				$uname = ereg_replace("(.*)(@.*)", "\\1", $email);
				// Get a new username...
				while(isUserThere($uname.$unameext, $bugDatabase->lists['user'])) {
					$unameext += 1;
				}
			}

			if (!$error) {
				$pass = getPass(8);
				// Sign up the new user....
				signupUser($uname.$unameext, $name, $email, $pass, $pass, $phone, $lang);

				// Refresh the user list...
				$bugDatabase->getUserList();

				// Set userinfo...
				$userinfo = $bugDatabase->getUser($uname.$unameext);
				
				if (!$options['ldapEnable']) {
					$notify = str_replace("%UNAME%", $uname, str_replace("%PASS%", $pass, str_replace("%BASE_URL%", $options['baseURL'], str_replace("%SYSTEM_NAME%", $options['systemName'], $options['signupEmailTemplate']))));
					mail($email, "Welcome to {$options['systemName']}!", $notify, "From: {$options['systemName']} <{$options['modEmail']}>\r\nX-Mailer: BugIn' {$buginVersion}");
				}

			}
			else {
				echo "Error: $error\n\n";
			}
		}
		else {
			echo "UID: $uid\n";
			return $bugDatabase->lists['user'][$uid];
		}
	}
	return ($bugDatabase->lists['user'][$userinfo['uid']]);

}

/* }}}2 */
/* User Functions }}}1 */

// Misc. Functions {{{1
/* function bugin_eval($one, $two) {{{2
		Evaluates two strings, removing newline differences. */

function bugin_eval($one, $two) {
	$ibe = str_replace("\r\n", "\n", $one);
	$rqi = str_replace("\r\n", "\n", $two);
	if ($ibe != $rqi)
		return 1;
	else
		return 0;
}
/* }}}2 */
/* function getPass($len) {{{2
		Used to create passwords.  duh. */
function getPass($len = 8) {

	$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!.{}()&*@#$%^-_+/\.,\';=|?~`<>";

	$file = fopen ("/dev/urandom", "r");
	
	$pw = "";
	$l = strlen($chars);
	$t = 256 % $l;
	for ($i=0; $i<$len; $i++) {
		$c = fread($file, 1);

		while (ord($c) < $t) {
			$c = fread($file, 1);
		}
		$pw .= substr($chars, ord($c) % $l, 1);
	}
	return $pw;

}

/* }}}2 */

  /* Function: DateSelector {{{2
  ** Version v2.0
  ** Last Updated: 2000-05-01
  ** Author: Leon Atkinson <hide@address.com>
  ** Creates three form fields for get month/day/year
  ** Input: Prefix to name of field, default date
  ** Output: HTML to define three date fields
  */
function DateSelector($inName, $useDate=0) {
	//create array so we can name months
	$monthName = array(1=> "January",  "February",  "March",
		"April",  "May",  "June",  "July",  "August",
		"September",  "October",  "November",  "December");

	//if date invalid or not supplied, use current time
	if($useDate == 0) {
		$useDate = Time();
	}

	/*
	** make month selector
	*/
	print("<select name=" . $inName .  "[month]>\n");
	for($currentMonth = 1; $currentMonth <= 12; $currentMonth++) {
		printf("<option value=\"%02d\"", $currentMonth);
		if(intval(date( "m", $useDate))==$currentMonth) {
		print(" selected");
		}
		print(">" . $monthName[$currentMonth] .  "</option>\n");
	}
	print("</select>");


	/*
	** make day selector
	*/
	print("<select name=" . $inName .  "[day]>\n");
	for($currentDay=1; $currentDay <= 31; $currentDay++) {
		printf("<option value=\"%02d\"", $currentDay);
		if(intval(date( "d", $useDate))==$currentDay) {
			print(" selected");
		}
		print(">$currentDay</option>\n");
	}
	print("</select>");


	/*
	** make year selector
	*/
	print("<select name=" . $inName .  "[year]>\n");
	$startYear = date( "Y", $useDate);
	for($currentYear = $startYear - 5; $currentYear <= $startYear+5;$currentYear++) {
		print("<option value=\"$currentYear\"");
		if(date( "Y", $useDate)==$currentYear) {
			print(" selected");
		}
		print(">$currentYear</option>\n");
	}
	print("</select>");
}

/* }}}2 */

/* function validateMod(mod) {{{2
	takes a variable and validates the content */
function validateMod($mod) {
	global $bugDatabase;
	$strMods = array();
	$intMods = array();
	$arrayMods = array();
	switch($_REQUEST['area']) {
		case "add_submit":
		case "cc_add_submit":
		case "modify":
		 	$strMods = array('modification', 'short_desc', 'long_desc');
			$intMods = array('owner', 'project', 'category', 'priority', 'status', 'num', 'creator');
			$arrayMods = array();
			if (count($bugDatabase->lists['field'])) {
				while (list($key, $value) = each($bugDatabase->lists['field'])) {
					switch ($value['type']) {
						case "select":
							array_push($intMods, $value['field_name']);
							break;
						case "multi_select":
							array_push($arrayMods, $value['field_name']);
							break;
						case "datetime":
							array_push($strMods, $value['field_name']);
							break;
					}
				}
			}
			break;
		case "search":
			$strMods = array('short_desc', 'long_desc');
			$arrayMods = array('category', 'status', 'project', 'priority', 'owner', 'creator');
			break;
		case "admin":
			switch($_REQUEST['action']) {
				case "oedit":
					$strMods = array('systemName', 'ticketName', 'modEmail', 'baseURL', 'footerText', 'formMethod', 'defaultOwner',
					                 'defaultUID', 'errorTicketAge', 'ldapEnable', 'ldapDomain', 'ldapReadServer', 'colorBg', 'colorText',
					                 'colorLink', 'colorALink', 'colorVLink', 'colorErrorText', 'colorMessageText', 'colorTableHeaderBg',
					                 'colorTableHeaderText', 'colorTableBgAlt1', 'colorTableTextAlt1', 'colorTableBgAlt2', 'colorTableTextAlt2',
					                 'notification', 'signup_email', 'notify_subj', 'notifyByName',
					                 'debug', 'norefresh', 'dateFormat');
					$intMods = array('closedNum', 'defaultAddCategory', 'defaultAddProject', 'defaultAddPriority', 'signupEnable', 'noSignupTicketEnable',
					                 'listRefresh', 'changelogRefresh', 'noEmail', 'anonCLAccess', 'defaultLanguage', 'anonTicketAccess');
					$arrayMods = array('closedNum', 'defaultGroups');
					break;
				case "uedit":
					$strMods = array('name', 'passwd1', 'passwd2', 'email', 'phone', 'lang', 'comment');
					$arrayMods = array('user_group', 'flags');
					break;
				case "uadd":
					$strMods = array('name', 'username', 'pass', 'email', 'phone', 'comment');
					$arrayMods = array('user_group', 'flags');
					break;
				case "gedit":
					$strMods = array('group_name');
					break;
				case "gadd":
					$strMods = array('group_name');
					break;
				case "pedit":
					$strMods = array('name', 'email', 'proj_desc');
					break;
				case "padd":
					$strMods = array('name', 'email', 'proj_desc');
					break;
				case "sedit":
					$strMods = array('name', 'descr');
					break;
				case "sadd":
					$strMods = array('name', 'descr');
					break;
				case "cadd":
					$strMods = array('name');
					break;
				case "cedit":
					$strMods = array('name');
					break;
				case "pradd":
					$strMods = array('name', 'color');
				case "predit":
					$strMods = array('name', 'color');
					break;
				case "acladd":
					$mod['flags'] = 0;
					$mod['flags'] += ($mod['f']['read'] ? ACL_READ : 0);
					$mod['flags'] += ($mod['f']['add'] ? ACL_ADD : 0);
					$mod['flags'] += ($mod['f']['modify'] ? ACL_MODIFY : 0);
					$mod['id_tag'] = $mod['id_tag_'.$mod['acl_type']];
					$intMods = array('project', 'flags', 'id_tag');
					$strMods = array('acl_type');
					break;
				default:
					echo "<pre>\t\t\t\tcase \"{$_REQUEST['action']}\":\n";
					$ints = "";
					$strs = "";
					reset($mod);
					if ($mod) {
						while (list($key, $value) = each($mod)) {
							if (intval($value)) {
								if ($ints) {
									$ints .= ", '$key'";
								}
								else
									$ints = "'$key'";
							}
							else {
								if ($strs)
									$strs .= ", '$key'";
								else
									$strs = "'$key'";
							}
						}
						echo <<< EOT
\t\t\t\t\t\$strMods = array($strs);
\t\t\t\t\t\$intMods = array($ints);
\t\t\t\t\tbreak;
					</pre>
EOT;
					}
			}
			break;
	}

	// Filter all int and string values....
	reset($strMods);
	reset($intMods);
	reset($arrayMods);
	while (list($key, $value) = each($strMods)) {
		if (isset($mod[$value]))
			$clean[$value] = $mod[$value];
	}

	while (list($key, $value) = each($intMods)) {
		if (isset($mod[$value]))
			$clean[$value] = intval($mod[$value]);
	}

	while (list($key, $value) = each($arrayMods)) {
		if (isset($mod[$value]))
			$clean[$value] = $mod[$value];
	}
	return $clean;

}

/* }}}2 */

/* function eregImageMatch(&$text, $noreplace = 0) {{{2
     Replaces text with images.*/
// Image matching for changelog and modifications in view...
function eregImageMatch(&$text, $noreplace = 0) {
	//echo $text;
	global $eregImages;
	global $options;
	$images = "";
	reset($eregImages);
	$image = "dot.png";
	while (list($key, $value) = each($eregImages)) {
		if (ereg($value['ereg'], $text)) {
			$image = $value['image'];
			$images .= <<<EOT
<img src="{$options['baseURL']}/gfx/{$image}" border="0" width="10" height="10" />
EOT;
			if (!$noreplace) {
				$text = eregi_replace($value['ereg'], $value['replace'], $text);
			}
		}
	}
	if ($images == "") {
		$images .= <<<EOT
<img src="{$options['baseURL']}/gfx/dot.png" border="0" width="10" height="10" />
EOT;
	}
	return $images;
}
/* }}}2 */

/* function generateOptionList($arrayList, $selectArrayVarName, $select) {{{2
     Generates an option list from an array.*/
function generateOptionList($arrayList, $selectArrayVarName = "id", $select = -1, $name = "name", $showId = 0) {
	$options = "";
	while (list($key, $value) = each($arrayList)) {
		$htmlName = htmlentities($value[$name]);
		if ($showId) {
			$htmlName  = "({$value['id']}) ".$htmlName;
		}
		if (($select != -1) && ($value[$selectArrayVarName] == $select)) {
				buginError("-Option-Selected {$value[$name]}", MESSAGE_DEBUG);
				$options .= "<option value=\"{$value[$selectArrayVarName]}\" selected>{$htmlName}</option>\n";
		}
		else {
				$options .= "<option value=\"{$value[$selectArrayVarName]}\">{$htmlName}</option>\n";
		}
	}
	return $options;
}

/* }}}2 */

/*  function printVar($var) {{{2
   Print out a var.  Ued when debugging. */
function printVar($var) {
	echo "<pre>";
	var_dump($var);
	echo "</pre>";
}
/* }}}2 */
/* Misc. Functions }}}1 */

?>
Return current item: BugIn and Ticketing System