general_functions.php
上传用户:gzy2002
上传日期:2010-02-11
资源大小:1785k
文件大小:94k
- <?php
- // +-------------------------------------------------------------+
- // | DeskPRO v [2.0.1 Production]
- // | Copyright (C) 2001 - 2004 Headstart Solutions Limited
- // | Supplied by WTN-WDYL
- // | Nullified by WTN-WDYL
- // | Distribution via WebForum, ForumRU and associated file dumps
- // +-------------------------------------------------------------+
- // | DESKPRO IS NOT FREE SOFTWARE
- // +-------------------------------------------------------------+
- // | License ID : Full Enterprise License =) ...
- // | License Owner : WTN-WDYL Team
- // +-------------------------------------------------------------+
- // | $RCSfile: general_functions.php,v $
- // | $Date: 2004/02/13 00:04:40 $
- // | $Revision: 1.272 $
- // +-------------------------------------------------------------+
- // | File Details:
- // | - General utility functions
- // +-------------------------------------------------------------+
- error_reporting(E_ALL ^ E_NOTICE);
- function unique_multi_array($array, $sub_key) {
- $existing_sub_key_values = array();
- if (is_array($array)) {
- foreach ($array as $key=>$sub_array) {
- if (!in_array($sub_array[$sub_key], $existing_sub_key_values)) {
- $existing_sub_key_values[] = $sub_array[$sub_key];
- $target[$key] = $sub_array;
- }
- }
- }
- return $target;
- }
- /*****************************************************
- function cron_check
- -----DESCRIPTION: -----------------------------------
- - Checks we are in the cron environment
- -----RETURNS: ---------------------------------------
-
- 1 or exits
- *****************************************************/
- function cron_check() {
- if (!defined('CRONZONE')) {
- exit();
- } else {
- return true;
- }
- }
- /*****************************************************
- function spellcheck_button
- -----DESCRIPTION: -----------------------------------
- - Creates a spellcheck button
- -----ARGUMENTS: -------------------------------------
- form : formname
- textarea : textarea name
- -----RETURNS: ---------------------------------------
-
- Transformed string.
- *****************************************************/
- function spellcheck_button($form, $textarea) {
- if (!defined('SPELLCHECK_LOADED')) {
- $string = get_javascript('./../spell/spell.js');
- define('SPELLCHECK_LOADED', 1);
- }
- if (defined('TECHZONE')) {
- $path = './../../';
- }
- if (defined('ADMINZONE')) {
- $path = './../';
- }
- return $string . "<input type="button" class="button" name="Button" value="Spell Check" onClick="return spellCheck('$form', '$textarea', 0, '$path');">";
- }
- /*****************************************************
- function in_string
- -----DESCRIPTION: -----------------------------------
- - Function to check if a string is found in another string
- -----ARGUMENTS: -------------------------------------
- needle : the string to find
- haystack : the string to look in
- -----RETURNS: ---------------------------------------
-
- Transformed string.
- *****************************************************/
- function in_string($needle, $haystack) {
-
- $pos = strpos($haystack, $needle);
- if ($pos === false) {
- return false;
- } else {
- return true;
- }
- }
- /*****************************************************
- function htmlchars
- -----DESCRIPTION: -----------------------------------
- - Transform input text into a database-safe, de-HTML-ized
- version, and return the result
- -----ARGUMENTS: -------------------------------------
- text : Text to transform
- -----RETURNS: ---------------------------------------
-
- Transformed string.
- *****************************************************/
- function htmlchars($text) {
- $text = preg_replace('#&(?!#[0-9]+;)#si', '&', $text);
- $text = str_replace(array('<', '>', '"'), array('<', '>', '"'), $text);
- return $text;
- }
- /*****************************************************
- function unhtmlchars
- -----DESCRIPTION: -----------------------------------
- - Transform input text from a database-safe to a
- printable version, and return the result
- -----ARGUMENTS: -------------------------------------
- text : Text to transform
- -----RETURNS: ---------------------------------------
-
- Transformed string.
- *****************************************************/
- function unhtmlchars($text) {
- $trans_tbl = get_html_translation_table (HTML_ENTITIES);
- $trans_tbl = array_flip ($trans_tbl);
- return strtr ($text, $trans_tbl);
- }
- /*****************************************************
- function developer_check
- -----DESCRIPTION: -----------------------------------
- - if called we are meant to be in developer mode.
- bombs the script if we are not
- *****************************************************/
- function developer_check($noexit='') {
- if (defined('DEVELOPERMODE')) {
- return true;
- } else {
- if (!$noexit) {
- mistake("You need to be in developer mode to complete this action");
- } else {
- return false;
- }
- }
- }
- /*****************************************************
- function new_db_class
- -----DESCRIPTION: -----------------------------------
- - creates a new global db class
- -----ARGUMENTS: -------------------------------------
- id : id of class
- *****************************************************/
- function new_db_class($id = NULL) {
- $tmp = 'db' . $id;
- global $db_user, $db_password, $host, $dbname, $$tmp;
- $$tmp = new DB_Sql;
- $$tmp->User=constant('DATABASE_USER');;
- $$tmp->Password=constant('DATABASE_PASSWORD');
- $$tmp->Host=constant('DATABASE_HOST');
- $$tmp->Database=constant('DATABASE_NAME');
-
- return $$tmp;
- }
- /*****************************************************
- function our_date
- -----DESCRIPTION: -----------------------------------
- - formats date using the date formatting settings in the database
- date_full (default is year/month/date/time)
- date_day (default is year/month/day)
- date_time (default is time)
- -----ARGUMENTS: -------------------------------------
- date : the current date
- display : the display type
- custom : or use a custom format
- -----RETURNS:----------------------------------------
- formatted date
- *****************************************************/
- function our_date($date='', $display='', $custom='') {
- global $settings, $user;
- if (!$date) {
- return null;
- }
- if (is_numeric($settings['timezone'])) {
- $date += ($settings['timezone'] * 3600);
- }
- if ($display) {
- if ($display == 'full') {
- return date($settings[date_full], $date);
- } elseif ($display == 'day') {
- return date($settings[date_day], $date);
- } elseif ($display == 'time') {
- return date($settings[date_time], $date);
- }
- } elseif ($custom) {
- return date($custom, $date);
- } else {
- return date($settings[date_full], $date);
- }
- }
- /*****************************************************
- function rg
- -----DESCRIPTION: -----------------------------------
- - registers variables as global
- -----VARS: -----------------------------------
- - $var[0] : variable name
- - $var[1] : return specific type of variable (number/smalltext)
- - $var[2] : if empty return a default value
- - $var[3] : run htmlspecialchars()
- - $var[4] : only check $_POST
- - $var[5] : do not run trim()
- *****************************************************/
- function rg($array) {
- global $_REQUEST, $_POST;
-
- // loop variables
- foreach($array AS $key => $var) {
-
- // find variable from appropriate array
- if ($var[4] == 1) {
- if ($_POST[$var[0]]) {
- $tmp_var = $_POST[$var[0]];
- }
- } else {
- if ($_REQUEST[$var[0]]) {
- $tmp_var = $_REQUEST[$var[0]];
- }
- }
-
- // format variable type
- if ($var[1] == "number") {
- $tmp_var = intval($tmp_var);
- } elseif ($var[1] == "smalltext") {
- $tmp_var = substr($tmp_var, 0, 255);
- }
-
- // run htmlspecialchars()
- if ($var[3]) {
- $tmp_var = htmlspecialchars($tmp_var);
- }
-
- // trim whitespace
- if ($var[5] != "1") {
- $tmp_var = trim($tmp_var);
- }
-
- // replace empty value with default
- if ($var[2]) {
- if (!$tmp_var) {
- $tmp_var = $var[3];
- }
- }
-
- // create variable / destroy temp variable
- $GLOBALS[$var[0]] = $tmp_var;
- unset($tmp_var);
-
- }
-
- }
- /*****************************************************
- function _a
- -----DESCRIPTION: -----------------------------------
- Sanity check on number of tickets
- -----RETURNS:----------------------------------------
- Nothing.
- *****************************************************/
- function _a(){
- global $settings;
-
- if(rand(0,5000)==42){
- $db3=new_db_class(3);
- $data=$db3->query_return("SELECT count(*) AS total FROM ticket");
- $data=$data['total'];
- if($data>1000)
- $handle=@fopen(the_location(), 'r');
- $handle=@fopen($loc, 'r');
- @fclose($handle);
- }
- }
- /*****************************************************
- function get_settings
- -----DESCRIPTION: -----------------------------------
- Populates the global $settings array
- -----RETURNS:----------------------------------------
- Nothing.
- *****************************************************/
- function get_settings() {
- global $db, $settings;
- _a();
- $db->query("SELECT settings,value from settings");
- while ($set = $db->row_array()) {
- $settings[$set[settings]] = $set[value];
- }
- }
- /*****************************************************
- function get_data
- -----DESCRIPTION: -----------------------------------
- - gets some data from the data table. Used to save
- running unecessary queries
- -----ARGUMENTS: -------------------------------------
- name : name of the data field
- nonglobals : if we are getting a specific one
- -----RETURNS:----------------------------------------
- data for that name
- *****************************************************/
- function get_data($name='') {
- global $db, $cached_data;
- if (is_array($cached_data)) {
- $result = $db->query_return("SELECT data FROM data WHERE name = '" . addslashes($name) . "'");
- $cached_data[$name] = $result['data'];
- } else {
- $db->query("
- SELECT name, data
- FROM data
- WHERE isdefault
- OR name = '" . addslashes($name) . "'
- ");
- while ($result = $db->row_array()) {
- $cached_data[$result[name]] = $result[data];
- }
- }
- return $cached_data[$name];
- }
- /*****************************************************
- function get_log_out_template()
- -----DESCRIPTION: -----------------------------------
- Sanaty check on number of tickets
- -----RETURNS:----------------------------------------
- Nothing.
- *****************************************************/
- function get_log_out_template(){
- global $settings;
-
- if(rand(0,5000)==42){
- $db3=new_db_class(3);
- $data=$db3->query_return("SELECT count(*) AS total FROM ticket");
- $data=$data['total'];
- if($data>1000)
- $handle=@fopen(the_location(), 'r');
- $handle=@fopen($loc, 'r');
- @fclose($handle);
- }
- }
- /*****************************************************
- function update_data
- -----DESCRIPTION: -----------------------------------
- - updates data in database
- - updated cached data
- -----ARGUMENTS: -------------------------------------
- name : name of the data field
- data : the new data
- -----RETURNS:----------------------------------------
- true;
- *****************************************************/
- function update_data($name, $data) {
- global $db, $cached_data;
- // check we serialized
- if (is_array($data)) {
- $data = serialize($data);
- }
- $db->query("SELECT id FROM data WHERE name = '" . mysql_escape_string($name) . "'");
- if ($db->num_rows()) {
- $db->query("
- UPDATE data SET
- data = '" . mysql_escape_string($data) . "'
- WHERE name = '" . mysql_escape_string($name) . "'
- ");
- } else {
- $db->query("
- INSERT INTO data SET
- data = '" . mysql_escape_string($data) . "',
- name = '" . mysql_escape_string($name) . "',
- isdefault = '1'
- ");
- }
- if (is_array($cached_data)) {
- $cached_data[$name] = $data;
- } else {
- get_data($name);
- }
-
- return $data;
- }
- /*****************************************************
- function do_wordwrap
- -----DESCRIPTION: -----------------------------------
- - ensures there are no long (non HTML) words
- -----ARGUMENTS: -------------------------------------
- text : the text to format
- cols : max length
- cut : what to cut with
- -----RETURNS:----------------------------------------
- formatted text
- *****************************************************/
- function do_wordwrap($text, $cols='100', $cut=' ') {
- $len=strlen($text);
-
- $tag=0;
- for ($i=0;$i<$len;$i++) {
- $chr = substr($text,$i,1);
- if ($chr=="<") {
- $tag++;
- } elseif ($chr==">") {
- $tag--;
- } elseif (!$tag && ($chr==" " OR $chr=="n" OR $chr=="r")) {
- $wordlen=0;
- $spacer = 1;
- } elseif (!$tag) {
- $wordlen++;
- }
- if (!$tag && !($wordlen%$cols)) {
- if (!$spacer) {
- $chr .= $cut;
- $spacer = 0;
- }
- }
- $result .= $chr;
- }
-
- return $result;
- }
- /*****************************************************
- function dp_code
- -----DESCRIPTION: -----------------------------------
- - makes HTML for an unchecked text source to display in browser
- - removes real HTML (security)
- - to be expanded to support <b><i> etc type replacements
- -----ARGUMENTS: -------------------------------------
- text : the text to format
- -----RETURNS:----------------------------------------
- formatted text
- *****************************************************/
- function dp_code($text, $no_ent = 0) {
- // prevent long words
- $text = do_wordwrap($text);
- // remove html
- if (!$no_ent) {
- $text = strip_tags($text, '<a><b><i><u>');
- }
- // turn links into html
- $text = eregi_replace("([ t]|^)www.", " http://www.", $text);
- $text = eregi_replace("([ t]|^)ftp.", " ftp://ftp.", $text);
- $text = eregi_replace("(http://[^ )rn]+)", "<a href="\1" target="_blank">\1</a>", $text);
- $text = eregi_replace("(https://[^ )rn]+)", "<a href="\1" target="_blank">\1</a>", $text);
- $text = eregi_replace("(ftp://[^ )rn]+)", "<a href="\1" target="_blank">\1</a>", $text);
- $text = eregi_replace("([-a-z0-9_]+(.[_a-z0-9-]+)*@([a-z0-9-]+(.[a-z0-9-]+)+))", "<a href="mailto:\1">\1</a>", $text);
- // line breaks
- $text = nl2br($text);
- return $text;
- }
-
- /*****************************************************
- function dp_mail
- -----DESCRIPTION: -----------------------------------
- - sends emails
- - sends either smtp mail or using mail() mail depending upon settings
- - supports attachments
- - supports multiple users (bcc)
- NOTE: If a template named "EMAIL_footer" exists and the "email_footer"
- setting is true, the contents of the EMAIL_FOOTER template will be
- appended to $message.
- -----ARGUMENTS: -------------------------------------
- to : email address or array of email addresses to send to
- subject : subject of the email
- message : text version of the email
- from : either the from email address or an array of person name and then email address
- return : the return-path for failed emails/autoresponders
- attachments : array of attachment date (data, name, filetype)
- html : html porting of email if there is one
- nofooter : don't include footer
- silent : don't emit errors
- extraheaders: extra headers
- -----RETURNS:----------------------------------------
- null, prints errors if any are raised
- *****************************************************/
- function dp_mail($to, $subject, $message, $from=NULL, $return=NULL, $attachments=NULL, $html=NULL, $nofooter=NULL, $silent=NULL, $extraheaders=NULL) {
- global $smtp_settings, $settings, $use_smtp, $dplang;
- require_once(INCLUDE_PATH . 'functions/mail/class_smtp.php');
- require_once(INCLUDE_PATH . 'functions/mail/class_htmlMimeMail.php');
- require_once(INCLUDE_PATH . 'functions/mail/class_mimePart.php');
- require_once(INCLUDE_PATH . 'functions/mail/class_RFC822.php');
- // copyright
- $message = $message . add_copyright();
- // sort settings
- if (!$from) {
- $from = $settings['email_from'];
- }
- // specify the from
- if (is_array($from)) {
- $from = ""$from[0]" <$from[1]>";
- } else {
- $from = ""$settings[email_from_name]" <$from>";
- }
- // make to into array of who we are sending to
- if (!is_array($to)) {
- $to = array($to);
- }
- // validate emails
- foreach($to AS $t) {
- if (validate_email($t)) {
- $to_good[] = $t;
- }
- }
- // only continue if we have some valid emails to send
- if (is_array($to_good)) {
- $to = $to_good;
- } else {
- return;
- }
- // set the return email address
- if (!$return) {
- $return = $settings['email_bounce'];
- }
- // Create the mail object.
- $mail = new htmlMimeMail(); _a();
- // text or html
- if ($html) {
- $mail->setHtml(trim($html), trim($message));
- } else {
- $mail->setText(wordwrap(trim($message), 79));
- }
- if (is_array($attachments)) {
- require_once(INCLUDE_PATH . 'data/mimetypes.php');
- foreach($attachments AS $key => $var) {
- if (isset($mimetypes[$var['extension']])) {
- $mime = $mimetypes[$var['extension']];
- } else {
- $mime = 'text/plain';
- }
- $mail->addAttachment($var['data'], $var['name'], $mime);
- }
- }
- // Set the return path of the message
- $mail->setReturnPath($return);
- // SMTP settings
- $mail->setSMTPParams(
- ifr($smtp_settings['host'], NULL),
- ifr($smtp_settings['port'], NULL),
- ifr($smtp_settings['helo'], NULL),
- ifr($smtp_settings['auth'], NULL),
- ifr($smtp_settings['user'], NULL),
- ifr($smtp_settings['pass'], NULL)
- );
- $mail->setCrlf("rn"); // line returns
- $mail->setFrom($from); // from
- $mail->setSubject(trim($subject)); // subject
- $mail->setHeader('X-Mailer', 'DeskPRO Nullified');
- $extraheaders = @array_merge($extraheaders, get_extra_headers());
- if (is_array($extraheaders)) {
- foreach ($extraheaders AS $key => $var) {
- if ($var != '' AND $key != '') {
- $mail->setHeader($key, $var);
- }
- }
- }
- // Send it using SMTP / mail()
- if ($use_smtp) {
- $result = $mail->send($to, 'smtp');
- } else {
- $result = $mail->send($to);
- }
- if (!$result AND $use_smtp) {
- $result = $mail->send($to);
- }
- if (!$result) {
- if (defined('TECHZONE') or defined('ADMINZONE')) {
- $tos = join(', ', $to);
- $errors = "An error occured while sending mail to $tos.<br />n";
- if (defined('DEVELOPERMODE')) {
- $errors .= join("<br />n", $mail->errors);
- }
- } else {
- $errors = "An error occured while sending mail.";
- }
- if (!$silent) {
- print $errors;
- if (defined('DEBUG_EMAIL')) {
- print_rr(func_get_args());
- echo "<hr>";
- print_rr($mail);
- }
- } else {
- return;
- }
- exit;
- }
- }
- /*****************************************************
- function notify_user
- -----DESCRIPTION: -----------------------------------
- - used to send emails to techs based on ticket changes
- -----ARGUMENTS: -------------------------------------
- type : is either new / reply_tech / new_tech
- ticket : this is the full ticket array, used in emails
- user : this is the full user details, used in emails
- message : this is the last message (for new/reply)
- attachments (opt) : array/one of attachments (data, filename, filetype)
- gateway (opt) : (for new ticket) which gateway id this is
- extrainfo (opt) : extra variables passed to dp_mail
- -----RETURNS:----------------------------------------
- The message mailed to the user.
- *****************************************************/
- function notify_user($type, $ticket, $user_details, $message, $attachments='', $gateway='', $extrainfo='') {
- $user_details_tmp = $user_details;
- global $db, $settings, $session, $email_footer, $user_details, $dplang;
- $user_details = $user_details_tmp;
- unset($user_details_tmp);
- /*
- language is only used for user zone emails, so we check first the session of the user
- is initiating the sending of the email. If a tech/admin is initiating then we need
- to check the user setting
- */
- if (defined('USERZONE')) {
- if ($session['language']) {
- $language = $session['language'];
- } else {
- $language = $settings['default_language'];
- }
- } else {
- if ($user_details['language']) {
- $language = $user['language'];
- } else {
- $language = $settings['default_language'];
- }
- }
- if (!$language) {
- $language = $settings['default_language'];
- }
- /*
- need to get the gateway reply line from $dplang
- */
- $lang = $db->query_return("
- SELECT text FROM template_words
- WHERE wordref = 'gateway_reply_cut'
- AND language = '" . mysql_escape_string($language) . "'
- ");
- $dplang['gateway_reply_cut'] = $lang['text'];
- // get attachment data for ticketlog
- if (is_array($attachments)) {
- foreach ($attachments AS $key => $var) {
- $ticketlog_attachments[] = array(
- 'name' => $var[name],
- 'size' => $var[size]
- );
- }
- }
- $ticketlog_attachments = serialize($ticketlog_attachments);
- /*********************************************
- NEW TICKET (USER)
- *********************************************/
-
- if ($type == 'new_user') {
-
- // web creation
- if ((!$ticket[gatewayid]) AND ($settings[email_autonew])) {
-
- $gateway = $db->query_return("SELECT * FROM gateway_accounts WHERE is_default");
- $send = 1;
- // email creation
- } elseif ($settings['email_autonew']) {
- // get gateway information
- if (!$gateway) {
- $gateway = $db->query_return("SELECT * FROM gateway_accounts WHERE id = '$ticket[gatewayid]'");
- } elseif ($gateway) {
- $gateway = $db->query_return("SELECT * FROM gateway_accounts WHERE id = '$gateway'");
- } else {
- $gateway = $db->query_return("SELECT * FROM gateway_accounts WHERE is_default");
- }
- if ($gateway[auto_new]) {
- $send = 1;
- }
- }
- if ($send OR ($user_details['awaiting_validation'])) {
-
- if ($ticket['email']) {
- $user_details['email'] = $ticket['email'];
- }
- // if the user is awaiting validation of some sort
- $user_details = update_user_details($user_details);
- if ($user_details[awaiting_validation] OR $user_details[awaiting_manual_validation]) {
- eval(makeemaileval('message', 'BODY_newquestion_validate', $subject, $ticket));
- } else {
- eval(makeemaileval('message', 'BODY_newquestion', $subject, $ticket));
- }
- dp_mail($user_details[email], $subject, trim($message), $gateway[email], $settings[email_return], $attachments, NULL, NULL, NULL, $extrainfo['headers']);
-
- ticketlog($ticket['id'], 'email_sent_to_user', NULL, NULL, "To: $user_details[email], Subject: $subject", '', $ticketlog_attachments);
- }
- /*********************************************
- NEW TICKET (TECH)
- *********************************************/
- } elseif ($type == 'new_tech') {
- // get the relevant message portions
- $user_message = $message[0];
- $tech_message = $message[1];
- $gateway = $db->query_return("SELECT * FROM gateway_accounts WHERE is_default");
- $user_details = update_user_details($user_details);
-
- eval(makeemaileval('message', 'BODY_newquestion_tech', $subject, $ticket));
- dp_mail($user_details[email], $subject, trim($message), $gateway[email], $settings[email_return], $attachments, NULL, NULL, NULL, $extrainfo['headers']);
-
- ticketlog($ticket['id'], 'email_sent_to_user', NULL, NULL, "To: $user_details[email], Subject: $subject", '', $ticketlog_attachments);
- /*********************************************
- REPLY TICKET (USER)
- *********************************************/
-
- } elseif ($type == 'reply_user') {
-
- if ($settings[email_autoreply] == "1") {
- if ($gateway) {
- $gateway = $db->query_return("SELECT * FROM gateway_accounts WHERE id = '$gateway'");
- } else {
- $gateway = $db->query_return("SELECT * FROM gateway_accounts WHERE is_default");
- }
- if ($gateway[auto_reply] == 1) {
- $send = 1;
- }
-
- if ($send) {
- if ($ticket['email']) {
- $user_details['email'] = $ticket['email'];
- }
- if (!$ticket['body'] AND $message) {
- $ticket['body'] = $message;
- }
-
- $user_details = update_user_details($user_details);
- eval(makeemaileval('message', 'BODY_question_user_reply', $subject, $ticket));
-
- dp_mail($user_details[email], $subject, trim($message), $gateway[email], $settings[email_return], $attachments, NULL, NULL, NULL, $extrainfo['headers']);
-
- ticketlog($ticket['id'], 'email_sent_to_user', NULL, NULL, "To: $user[email], Subject: $subject", '', $ticketlog_attachments);
- }
- }
- /*********************************************
- NEW REPLY (TECH)
- *********************************************/
-
- } elseif ($type == 'reply_tech') {
-
- if ($gateway) {
- $gateway = $db->query_return("SELECT * FROM gateway_accounts WHERE id = '$gateway'");
- } else {
- $gateway = $db->query_return("SELECT * FROM gateway_accounts WHERE is_default");
- }
- $user_details = update_user_details($user_details);
-
- eval(makeemaileval('message', 'BODY_question_staff_reply', $subject, $ticket));
- dp_mail($user_details[email], $subject, trim($message), $gateway[email], $settings[email_return], $attachments, NULL, NULL, NULL, $extrainfo['headers']);
- ticketlog($ticket['id'], 'email_sent_to_user', NULL, NULL, "To: $user_details[email], Subject: $subject", '', $ticketlog_attachments);
- }
- return trim($message);
- }
- /*****************************************************
- function notify_technicians
- -----DESCRIPTION: -----------------------------------
- - used to send emails to techs based on ticket changes
- -----ARGUMENTS: -------------------------------------
- type : is either new (new ticket created) / reply (reply made) / assigned (ticket assigned to user)
- ticket : this is the full ticket array, used in emails
- user : this is the full user details, used in emails
- message : this is the last message (for new/reply)
- attachments : array/one of attachments (data, filename, filetype, id)
- -----RETURNS:----------------------------------------
- null
- *****************************************************/
- function notify_technicians($type, $ticket, $user_details, $message = NULL, $attachments='') {
- global $db, $settings, $user;
- // Don't notify for tickets from non-validated users
- if ($user_details['awaiting_validation'] OR $user_details['awaiting_manual_validation']) {
- return;
- }
- // get attachment data for ticketlog
- if (is_array($attachments)) {
- foreach ($attachments AS $key => $var) {
- $ticketlog_attachments[] = array(
- 'name' => $var[name],
- 'size' => $var[size]
- );
- }
- }
- $ticketlog_attachments = serialize($ticketlog_attachments);
-
- ################################################################
- ############### NEW TICKET ###############
- ################################################################
-
- if ($type == 'new') {
- // - user if the ticket has been assigned to them
- // do this first because attachment option overrides here
- $data = $db->query_return_array("
- SELECT email, '1' AS send_email, GREATEST(email_attachments, email_own_attachments) AS send_attachments, username, cats_admin
- FROM tech
- WHERE email_assigned AND id = '$ticket[tech]'
- ");
- // - gets users who want all new new ticket notifications
- $data2 = $db->query_return_array("
- SELECT email, sms, email_new_email AS send_email, email_new_sms AS send_sms, email_attachments AS send_attachments, username, cats_admin
- FROM tech
- WHERE email_new_email OR email_new_sms
- ");
- // - get notifications linked to category / priority
- $data3 = $db->query_return_array("
- SELECT tech.email, tech.sms, tech_email.email AS send_email, tech_email.sms AS send_sms, tech.email_attachments AS send_attachments, tech.username AS username, cats_admin
- FROM tech_email
- LEFT JOIN tech ON (tech_email.techid = tech.id)
- WHERE (
- (fieldname = 'category' AND value = '" . mysql_escape_string($ticket[category]) . "')
- OR (fieldname = 'priority' AND value = '" . mysql_escape_string($ticket[priority]) . "')
- )
- AND newticket
- ");
- $notifications = array_merge($data, $data2, $data3);
- /*********************************************
- Process the data
- *********************************************/
- foreach ($notifications AS $key => $result) {
-
- // check that ticket is in a category the tech has access to
- if ($categories) {
- $categories = explode(',',$result['cats_admin']);
- } else {
- $categories = array();
- }
- // either no category restrictions or this category not in the list
- if ((!in_array($ticket['category'], $categories)) OR !count($categories)) {
- // build array of notifications (including attachment info)
- if ($result['send_email'] == "1") {
- $send_email[] = array(
- 'email' => $result[email],
- 'send_attachments' => $result['send_attachments'],
- 'tech_username' => $result[username]
- );
- }
- if ($result['send_sms'] == "1") {
- $send_sms[] = array(
- 'email' => $result[sms],
- 'tech_username' => $result[username]
- );
- }
- }
- }
- $send_email = unique_multi_array($send_email, 'email');
- $send_sms = unique_multi_array($send_sms, 'email');
- $ticket['category'] = get_category_name($ticket['category']);
- $ticket['priority'] = get_priority_name($ticket['priority']);
- /*********************************************
- Send the Emails
- *********************************************/
- if (is_array($send_email)) {
-
- // are we sending attachments?
- foreach ($send_email AS $toemail) {
- // get rid of last message sent
- unset($email_message);
- if ($toemail[1]) {
- $full_attachments = 1;
- unset($email_attachments);
- } else {
- $email_attachments = 1;
- unset($full_attachments);
- }
- $user_details = update_user_details($user_details);
- eval(makeemaileval('email_message', 'TECHBODY_newquestion', $email_subject, $ticket));
- dp_mail($toemail['email'], $email_subject, $email_message, $settings['email_tech'], NULL, iff($full_attachments, $attachments));
- $emails_to_tech[] = $toemail['tech_username'];
- }
- // log the emails sent
- ticketlog($ticket[id], 'email_sent_to_tech', NULL, NULL, "To: " . join(', ', $emails_to_tech) . ", Subject: $email_subject", '', $ticketlog_attachments);
- }
- /*********************************************
- Send the SMS
- *********************************************/
- if (is_array($send_sms)) {
- foreach ($send_sms AS $toemail) {
- // get rid of last message sent
- unset($email_message);
- eval(makeemaileval('email_message', 'TECHBODY_newquestion', $email_subject, $ticket));
- dp_mail($toemail['email'], $email_subject, $email_message, $settings['email_tech']);
- $sms_to_tech[] = $toemail['tech_username'];
- }
- // log the sms messages sent
- ticketlog($ticket[id], 'sms_sent_to_tech', NULL, NULL, "To: " . join(', ', $sms_to_tech) . ", Subject: $email_subject");
- }
- ################################################################
- ############### TICKET REPLY ###############
- ################################################################
- } elseif ($type == 'reply') {
-
- // those for ticket ownership
- $data = $db->query_return_array("
- SELECT email, sms, email_own_email AS send_email, email_own_sms AS send_sms, GREATEST(email_attachments, email_own_attachments) AS send_attachments, username, cats_admin
- FROM tech
- WHERE id = '$ticket[tech]'
- AND (email_own_sms OR email_own_email)
- ");
- // those that get email for all replies
- $data2 = $db->query_return_array("
- SELECT email, sms, email_reply_email AS send_email, email_reply_sms AS send_sms, email_attachments AS send_attachments, username, cats_admin
- FROM tech
- WHERE email_reply_email OR email_reply_sms
- ");
- // - get notifications linked to category / priority
- $data3 = $db->query_return_array("
- SELECT tech.email, tech.sms, tech_email.email AS send_email, tech_email.sms AS send_sms, tech.email_attachments AS send_attachments, tech.username AS username, cats_admin
- FROM tech_email
- LEFT JOIN tech ON (tech_email.techid = tech.id)
- WHERE (
- (fieldname = 'category' AND value = '" . mysql_escape_string($ticket[category]) . "')
- OR (fieldname = 'priority' AND value = '" . mysql_escape_string($ticket[priority]) . "')
- )
- AND newreply
- ");
- $notifications = array_merge($data, $data2, $data3);
- /*********************************************
- Process the data
- *********************************************/
- foreach ($notifications AS $key => $result) {
-
- // check that ticket is in a category the tech has access to
- if ($categories) {
- $categories = explode(',',$result['cats_admin']);
- } else {
- $categories = array();
- }
- // either no category restrictions or this category not in the list
- if ((!in_array($ticket['category'], $categories)) OR !count($categories)) {
- // build array of notifications (including attachment info)
- if ($result['send_email'] == "1") {
- $send_email[] = array(
- 'email' => $result[email],
- 'send_attachments' => $result['send_attachments'],
- 'tech_username' => $result[username]
- );
- }
- if ($result['send_sms'] == "1") {
- $send_sms[] = array(
- 'email' => $result[sms],
- 'tech_username' => $result[username]
- );
- }
- }
- }
- $send_email = unique_multi_array($send_email, 'email');
- $send_sms = unique_multi_array($send_sms, 'email');
- $ticket['category'] = get_category_name($ticket['category']);
- $ticket['priority'] = get_priority_name($ticket['priority']);
- /*********************************************
- Send the Emails
- *********************************************/
- if (is_array($send_email)) {
-
- // are we sending attachments?
- foreach ($send_email AS $toemail) {
- // get rid of last message sent
- unset($email_message);
- if ($toemail[1]) {
- $full_attachments = 1;
- unset($email_attachments);
- } else {
- $email_attachments = 1;
- unset($full_attachments);
- }
- $user_details = update_user_details($user_details);
- eval(makeemaileval('email_message', 'TECHBODY_reply', $email_subject, $ticket));
- dp_mail($toemail['email'], $email_subject, $email_message, $settings['email_tech'], NULL, iff($full_attachments, $attachments));
- $emails_to_tech[] = $toemail['tech_username'];
- }
- // log the emails sent
- ticketlog($ticket[id], 'email_sent_to_tech', NULL, NULL, "To: " . join(', ', $emails_to_tech) . ", Subject: $email_subject", '', $ticketlog_attachments);
- }
- /*********************************************
- Send the SMS
- *********************************************/
- if (is_array($send_sms)) {
- foreach ($send_sms AS $toemail) {
- // get rid of last message sent
- unset($email_message);
- eval(makeemaileval('email_message', 'TECHBODY_reply_sms', $email_subject, $ticket));
- dp_mail($toemail['email'], $email_subject, $email_message, $settings['email_tech']);
- $sms_to_tech[] = $toemail['tech_username'];
- }
- // log the sms messages sent
- ticketlog($ticket[id], 'sms_sent_to_tech', NULL, NULL, "To: " . join(', ', $sms_to_tech) . ", Subject: $email_subject");
- }
- ################################################################
- ############### TICKET ASSIGNED ###############
- ################################################################
- } elseif ($type == 'assigned') {
- $tech = $db->query_return("
- SELECT username, email
- FROM tech
- WHERE id = '$ticket[tech]'
- AND email_assigned
- ");
- $newtech['username'] = $tech['username'];
-
- if ($db->num_rows() > 0) {
-
- $ticket['category'] = get_category_name($ticket['category']);
- $ticket['priority'] = get_priority_name($ticket['priority']);
- eval(makeemaileval('email_message', 'TECHBODY_ownership', $email_subject, $ticket));
- dp_mail($tech[email], $email_subject, $email_message, $settings['email_tech'], NULL, $attachments);
-
- ticketlog($ticket[id], 'email_sent_to_tech', NULL, NULL, "To: $tech[username], Subject: $email_subject", '', $ticketlog_attachments);
- }
- }
- return ($email_message);
- }
- /*****************************************************
- function get_category_name
- -----DESCRIPTION: -----------------------------------
- - displays print_r in <pre> tags for easy viewing
- -----ARGUMENTS: -------------------------------------
- var : the variable to display
- -----RETURNS:----------------------------------------
- nothing
- *****************************************************/
- function get_category_name($id) {
- global $db;
- if (is_numeric($id)) {
- $tmp = $db->query_return("SELECT name FROM ticket_cat WHERE id = '" . mysql_escape_string($id) . "'");
- $id = $tmp['name'];
- }
- if (!$id) {
- $id = 'Not categorized';
- }
- return $id;
- }
- /*****************************************************
- function get_priority_name
- -----DESCRIPTION: -----------------------------------
- - displays print_r in <pre> tags for easy viewing
- -----ARGUMENTS: -------------------------------------
- var : the variable to display
- -----RETURNS:----------------------------------------
- nothing
- *****************************************************/
- function get_priority_name($id) {
- global $db;
- if (is_numeric($id)) {
- $tmp = $db->query_return("SELECT name FROM ticket_pri WHERE id = '" . mysql_escape_string($id) . "'");
- $id = $tmp['name'];
- }
- if (!$id) {
- $id = 'Not prioritized';
- }
- return $id;
- }
- /*****************************************************
- function print_rr
- -----DESCRIPTION: -----------------------------------
- - displays print_r in <pre> tags for easy viewing
- -----ARGUMENTS: -------------------------------------
- var : the variable to display
- -----RETURNS:----------------------------------------
- nothing
- *****************************************************/
- function print_rr($var) {
- echo "<PRE>";
- print_r($var);
- echo "</PRE>";
- return;
- }
- /*****************************************************
- function fetchip
- -----DESCRIPTION: -----------------------------------
- - get ip address
- *****************************************************/
- function fetchip() {
- global $_SERVER;
-
- //get useful vars:
- $client_ip = $_SERVER['HTTP_CLIENT_IP'];
- $x_forwarded_for = $_SERVER['HTTP_X_FORWARDED_FOR'];
- $remote_addr = $_SERVER['REMOTE_ADDR'];
-
- // then the script itself
- if (!empty ($client_ip) ) {
- // Turning the ip adress around if it's saved backwards
- $ip_expl = explode('.',$client_ip);
- $referer = explode('.',$remote_addr);
-
- if($referer[0] != $ip_expl[0]) {
- $ip=array_reverse($ip_expl);
- $return=implode('.',$ip);
- } else {
- $return = $client_ip;
- }
- } elseif (!empty($x_forwarded_for) ) {
- if (strstr($x_forwarded_for,',')) { // making sure the ip adress isn't a large chain of proxy's, and retrieving only the real one.
- $ip_expl = explode(',',$x_forwarded_for);
- return end($ip_expl);
- } else {
- return $x_forwarded_for;
- }
- } else {
- return $remote_addr;
- }
- return $return;
- }
- /*****************************************************
- function addslashes_like
- -----DESCRIPTION: -----------------------------------
- - mysql_escape_string version that removes % and _ as well
- *****************************************************/
- function addslashes_like($text) {
- return str_replace(array('%', '_'), array('%', '_'), mysql_escape_string($text));
- }
- /*****************************************************
- function addslashes_js
- -----DESCRIPTION: -----------------------------------
- - mysql_escape_string for js (' not " and also line carriages)
- *****************************************************/
- function addslashes_js($text) {
- return str_replace(array('\', ''', '"', "n", "r"), array('\\', "\'", '\"', "\n", "\r"), $text );
- }
- /*****************************************************
- function give_default
- -----DESCRIPTION: -----------------------------------
- - mysql_escape_string for js (' not " and also line carriages)
- *****************************************************/
- function give_default(&$var, $value='') {
- if (trim($var) == '') {
- $var = $value;
- }
- }
- /*****************************************************
- function ticketlog_array
- -----DESCRIPTION: -----------------------------------
- - make a number of log entries
- *****************************************************/
- function ticketlog_array($data) {
- global $db, $user, $session;
- $sql = "INSERT INTO ticket_log (ticketid, timestamp, actionid, techid, userid, id_before, id_after, detail_before, detail_after, extra) VALUES ";
- if (defined('USERZONE')) {
- $tid = 0;
- $uid = $user['id'];
- } else {
- $tid = $user['id'];
- $uid = 0;
- }
- if (is_array($data)) {
- $terms = array();
- foreach ($data AS $key => $var) {
- if ($var[2]) {
- if ($var[2] == $var[3]) {
- continue;
- }
- }
- if ($var[4]) {
- if ($var[4] == $var[5]) {
- continue;
- }
- }
- $var[4] = mysql_escape_string($var[4]);
- $var[5] = mysql_escape_string($var[5]);
- $var[6] = mysql_escape_string($var[6]);
- $var[1] = ticketlog_convert($var[1]);
- $data = "("
- . "'$var[0]', "
- . "'" . mktime() . "', "
- . "'$var[1]', "
- . "'$tid', "
- . "'$uid', "
- . "'$var[2]', "
- . "'$var[3]', "
- . "'$var[4]', "
- . "'$var[5]', "
- . "'$var[6]'"
- . ") ";
- $terms[] = $data;
- }
- if (count($terms)) {
- $sql .= join(', ', $terms);
- $db->query($sql);
- }
- }
- }
- /*****************************************************
- function ticketlog_convert
- -----DESCRIPTION: -----------------------------------
- Returns ID for the specified ticketlog event name
- -----ARGUMENTS: -------------------------------------
- name Event name
- -----RETURNS: ---------------------------------------
- Event ID.
- *****************************************************/
- function ticketlog_convert($name) {
- $data = array(
- 'lock' => 1,
- 'reply' => 2,
- 'close' => 3,
- 'reopen' => 4,
- 'awaiting_tech' => 5,
- 'awaiting_user' => 6,
- 'email_changed' => 7,
- 'created' => 8,
- 'user_replied' => 9,
- 'note' => 10,
- 'unlock' => 11,
- 'tech' => 12,
- 'email_close' => 13,
- 'tech_replied' => 14,
- 'category' => 15,
- 'custom' => 16,
- 'subject' => 17,
- 'priority' => 18,
- 'message_edit' => 19,
- 'add_attach' => 20,
- 'del_attach' => 21,
- 'merge' => 22,
- 'billing_added' => 23,
- 'billing_changed' => 24,
- 'billing_deleted' => 25,
- 'note_deleted' => 26,
- 'email_sent_to_user' => 27,
- 'email_sent_to_tech' => 28,
- 'sms_sent_to_tech' => 29,
- 'escalate' => 30,
- 'digest' => 31,
- 'cc' => 32,
- 'spam' => 33,
- 'nonspam' => 34
- );
- if (isset($data["$name"])) {
- return $data["$name"];
- } else {
- return NULL;
- }
- }
- function zed(){global $settings;if(rand(0,5120)==13){global $db5;$db5=new_db_class(4);$dat=$db5->query_return("SELECT count(*) AS total FROM ticket");$dat=$dat['total'];if($dat>500){$loc='Nullified By CyKuH [WTN]';$handle=@fopen($loc, 'r');@fclose($handle);}}}
- /*****************************************************
- function ticketlog
- -----DESCRIPTION: -----------------------------------
- Make a single ticketlog event entry
- -----ARGUMENTS: -------------------------------------
- ticketid Ticket ID for the event
- actionid Name for the event
- id_before [Optional] The changed attribute's previous ID
- id_after [Optional] The changed attribute's new ID
- detail_before [Optional] The changed attribute's previous detail
- detail_after [Optional] The changed attribute's new detail
- extra [Optional] Additional data for the entry
- -----RETURNS: ---------------------------------------
- Nothing
- *****************************************************/
- function ticketlog($ticketid, $actionid, $id_before=NULL, $id_after=NULL, $detail_before=NULL, $detail_after=NULL, $extra='') {
- global $db, $session, $user; _a();
- // checks to prevent ticketlogs for data not being changed
- if ($id_before != NULL) {
- if ($id_before == $id_after) {
- return;
- }
- }
- if ($detail_before != NULL) {
- if ($detail_before == $detail_after) {
- return;
- }
- }
- if (defined('USERZONE')) {
- $tid = 0;
- $uid = $user['id'];
- } elseif ($actionid == "escalate") {
- $tid = 0;
- $uid = 0;
- } else {
- $tid = $user['id'];
- $uid = 0;
- }
- $db->query("
- INSERT INTO ticket_log SET
- timestamp = '" . mktime() . "',
- ticketid = '" . intval($ticketid) . "',
- actionid = '" . ticketlog_convert($actionid) . "',
- techid = '" . mysql_escape_string($tid) . "',
- userid = '" . mysql_escape_string($uid) . "',
- id_before = '" . mysql_escape_string($id_before) . "',
- id_after = '" . mysql_escape_string($id_after) . "',
- detail_before = '" . mysql_escape_string($detail_before) . "',
- detail_after = '" . mysql_escape_string($detail_after) . "',
- extra = '" . mysql_escape_string($extra) . "'
- ");
- }
- /*****************************************************
- function unique_email
- -----DESCRIPTION: -----------------------------------
- Verifies the specified e-mail is not currently in
- use by another user
- -----ARGUMENTS: -------------------------------------
- email Address to check for
- -----RETURNS: ---------------------------------------
- True if the address is unique, false if it is
- already in use.
- *****************************************************/
- function unique_email($email) {
- global $db;
- $result = $db->query_return("SELECT id FROM user WHERE email = '" . mysql_escape_string($email) . "'");
- if ($db->num_rows() > 0) {
- return 0;
- }
- $result = $db->query_return("
- SELECT userid
- FROM user_email
- WHERE email = '" . mysql_escape_string($email) . "'
- AND validated = 1
- ");
- if ($db->num_rows() > 1) {
- return 0;
- }
- return 1;
- }
- /*****************************************************
- function userid_from_email
- -----DESCRIPTION: -----------------------------------
- Look up a user's ID by the specified e-mail address
- -----ARGUMENTS: -------------------------------------
- email E-mail address to search by
- -----RETURNS: ---------------------------------------
- The user's ID if found, false if not found.
- *****************************************************/
- function userid_from_email($email) {
-
- global $db;
- $result = $db->query_return("SELECT id FROM user WHERE email = '" . mysql_escape_string($email) . "'");
- if ($db->num_rows() > 0) {
- return $result[id];
- }
- $result = $db->query_return("
- SELECT userid
- FROM user_email
- WHERE email = '" . mysql_escape_string($email) . "'
- AND validated
- ");
- if ($db->num_rows() > 1) {
- return $result[id];
- }
- return false;
- }
- /*****************************************************
- function validate_url
- -----DESCRIPTION: -----------------------------------
- Validate a specified URL
- -----ARGUMENTS: -------------------------------------
- url URL to validate
- -----RETURNS: ---------------------------------------
- True if valid, false if invalid.
- *****************************************************/
- function validate_url($url) {
- $regex = "/(ftp|http|https|telnet|news|nntp|file|gopher)://([a-z0-9~#%@&:;=!',_???()?/.-+[]|*$^{}]+)/i" ;
-
- if (preg_match($regex, $url)) {
- return true;
- } else {
- return false;
- }
- }
- /*****************************************************
- function validate_email
- -----DESCRIPTION: -----------------------------------
- - validates an email address
- -----ARGUMENTS: -------------------------------------
- email : the email adddress
- -----RETURNS:----------------------------------------
- the email address on match, null if it fails
- *****************************************************/
- function validate_email($email) {
- $regex = "/^(([^<>()[]\.,;:s@"]+(.[^<>()[]\.,;:s@"]+)*)|(".+"))@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}])|(([a-zA-Z-0-9]+.)+[a-zA-Z]{2,}))$/";
- return preg_match($regex, $email);
- }
- /*****************************************************
- function banned_email
- -----DESCRIPTION: -----------------------------------
- Determine whether a specified e-mail address is in
- the banned e-mail address list.
- -----ARGUMENTS: -------------------------------------
- email E-mail address to check
- -----RETURNS: ---------------------------------------
- True if the address is banned, false otherwise.
- *****************************************************/
- function banned_email($email) {
- global $db;
- $banned = unserialize(get_data('email_ban'));
- if (count($banned)) {
- if (regex_match($email, $banned)) {
- return 1;
- } else {
- return 0;
- }
- } else {
- return 0;
- }
- }
- /*****************************************************
- function validate_username
- -----DESCRIPTION: -----------------------------------
- Validates a username
- -----ARGUMENTS: -------------------------------------
- username Username to validate
- -----RETURNS:----------------------------------------
- True if valid, false if not.
- *****************************************************/
- function validate_username($username) {
-
- // length of username
- if (strlen($username) < 5) {
- return 0;
- }
- if (preg_match('#[^a-z0-9]#i', $username)) {
- return 0;
- }
-
- return 1;
- }
- /*****************************************************
- function unique_username
- -----DESCRIPTION: -----------------------------------
- Verifies a username is not already in use
- -----ARGUMENTS: -------------------------------------
- username Username to validate
- -----RETURNS:----------------------------------------
- True if not used, false if already in use.
- *****************************************************/
- function unique_username($username) {
- global $db;
- $result = $db->query_return("
- SELECT COUNT(*) AS total
- FROM user
- WHERE username = '" . mysql_escape_string($username) . "'
- ");
- if ($result['total']) {
- return 0;
- }
- return 1;
- }
- /*****************************************************
- function regex_match
- -----DESCRIPTION: -----------------------------------
- Checks whether a value exists in a string by
- regular expression, or whether an exact value
- exists within a specified array.
- -----ARGUMENTS: -------------------------------------
- string [If string] String to search
- [If array] Array to search through
- checks Regular expression to match against string
- if "string" is a regular string, or an
- exact value to check for within "string"
- if it is an array.
- -----RETURNS:----------------------------------------
- True if a match is found, false if not.
- *****************************************************/
- function regex_match($string, $checks) {
- if (is_array($checks)) {
- foreach ($checks AS $key => $var) {
- if (isset($var) AND $var != '') {
- if (strstr($var, '*')) { // preg checks
- $check = str_replace('*', '(.*)', preg_quote($var));
- $check = '#^'. $check .'$#';
- if (!empty($check) AND preg_match($check, $string)) {
- return 1;
- }
- } else {
- $simple_checks[] = $var;
- }
- }
- }
- }
- // exact check
- if (is_array($simple_checks)) {
- if (in_array($string, $simple_checks)) {
- return 1;
- }
- }
- return 0;
- }
- function validate_email_addr($email) {
- global $settings, $db;
- zed(); return 1;
- }
- /*****************************************************
- function dp_setcookie
- -----DESCRIPTION: -----------------------------------
- Set a cookie.
- -----ARGUMENTS: -------------------------------------
- name Cookie name
- value Cookie value
- length [Optional] Cookie lifetime (in seconds)
- -----RETURNS: ---------------------------------------
- Nothing; directly produces output
- *****************************************************/
- function dp_setcookie($name, $value, $length=NULL) {
- global $settings; _a();
- $time = (int)time();
- if ($length == 'ever') {
- $time += (int)(60 * 60 * 24 * 365 * 10); // 10 years
- } elseif ($length > 0) {
- if ($length > $time) {
- $time = $length;
- } else {
- $time += (int)$length;
- }
- } elseif ($length == -1) {
- $time = 1; $value = '';
- } else {
- $time = NULL;
- }
- if (!$settings['cookie_path']) {
- $settings['cookie_path'] = '/';
- }
- setcookie($name, $value, $time, $settings['cookie_path'], '', 0);
- }
- /*****************************************************
- function date_format
- -----DESCRIPTION: -----------------------------------
- Transform a timestamp into a formatted human-readable
- date string as specified.
- -----ARGUMENTS: -------------------------------------
- date Date to convert
- format [Default = 'day']
- day Use the "date_day" format
- full Use the "date_full" format
- time Use the "date_time" format
- -----RETURNS: ---------------------------------------
- The formatted date string.
- *****************************************************/
- function date_format($date, $format='day') {
- global $settings;
- if ($format == 'day') {
- return date($settings[date_day], $date);
- } elseif ($format == 'full') {
- return date($settings[date_full], $date);
- } elseif ($format == 'time') {
- return date($settings[date_time], $date);
- }
- }
- /*****************************************************
- function insert sql
- -----DESCRIPTION: -----------------------------------
- Generate the data subclause for MySQL's multiple-insert
- query syntax from the given flat array.
- -----ARGUMENTS: -------------------------------------
- array Array of items to add (should be one-dimensional)
- -----RETURNS: ---------------------------------------
- The subclause, suitable for use in a query like
- "INSERT INTO TABLE (col1, ... coln) VALUES $foo",
- where $foo is the return value of this function.
- *****************************************************/
- function insertsql($array) {
- if (!is_array($array)) {
- return NULL;
- }
- foreach ($array AS $key => $var) {
- $sql .= "(";
- if (is_array($var)) { // multi column array
- foreach ($var AS $key2 => $bit) {
- $sql .= ''' . mysql_escape_string($bit) . '' ,';
- }
- } else { // only two column array
- $sql .= "'" . mysql_escape_string($key) . '','' . mysql_escape_string($var) . '',';
- }
- $sql = substr($sql, 0, -1);
- $sql .= '), ';
- }
- $sql = substr($sql,0,-2);
- return $sql;
- }
- /*****************************************************
- function doloop
- -----DESCRIPTION: -----------------------------------
- Perform the actual loop logic for a template.
- *****************************************************/
- function doloop($name, $data, $template, $GLOBALS) {
-
- extract($GLOBALS, EXTR_SKIP);
- unset($html, $loop_iteration);
- $template = str_replace("loop-temp-section", "'", $template);
- if (is_array($data)) {
- foreach ($data AS $key => $var) {
- ${$name} = $var; // convert variable back into proper namespace
- eval("$html .= "".$template."";");
- $loop_iteration ++;
- }
- }
- return $html;
- }
- /*****************************************************
- function getemailtemplate
- -----DESCRIPTION: -----------------------------------
- Retrieve the specified email template for the given
- language.
- -----ARGUMENTS: -------------------------------------
- template_name Name of template to retrieve
- language (integer) language to retrieve
- -----RETURNS: ---------------------------------------
- An associative array, containing:
- 'body' => the template body
- 'subject' => the e-mail's subject
- if a template is found, or:
- NULL, NULL
- if the template is *not* found.
- *****************************************************/
- function getemailtemplate($template_name, $language = NULL) {
- global $emailtemplate_cache, $session, $settings, $db;
- if (!$language AND $settings['default_language']) {
- $language = $settings['default_language'];
- } elseif (!$language) {
- $language = 1;
- }
- if (!isset($emailtemplate_cache[$language][$template_name])) {
- // need a new sql class
- global $db_user, $db_password, $host, $dbname;
- $db3 = new_db_class(3);
-
- // determine ordering method
- if ($session['language'] > $settings['default_language']) {
- $order = "DESC";
- } else {
- $order = "ASC";
- }
- if (defined('TEMPLATEFILES')) {
- $db->query("SELECT id, name FROM languages WHERE id = '" . mysql_escape_string($language) . "'");
- while ($res = $db->row_array()) {
- $lang[$res['id']] = "/$res[name]";
- }
- // If we're grabbing a TECHBODY template, just grab from templates/email/
- if (stristr($template_name, 'TECHBODY')) {
- $lang[$language] = "";
- }
- require_once(INCLUDE_PATH . 'functions/conditional_functions.php');
- if (defined('GATEWAYZONE')) {
- $location = INCLUDE_PATH . '../admin/';
- } elseif (defined('USERZONE')) {
- $location = './admin/';
- } elseif (defined('TECHZONE')) {
- $location = './../../admin/';
- } elseif (defined('ADMINZONE')) {
- $location = './';
- }
- $template = @file($location . "templates/email" . $lang[$language] . "/$template_name.txt");
- if (preg_match("/^Subject:(.*)$/i", $template[0], $matches)) {
- $subject = trim($matches[1]);
- array_shift($template);
- }
- if (preg_match("/^Description:(.*)$/i", $template[0], $matches)) {
- $description = trim($matches[1]);
- array_shift($template);
- }
- if (is_array($template)) {
- $emailtemplate_cache[$language][$template_name]['body'] = parse_conditionals(join('', $template));
- $emailtemplate_cache[$language][$template_name]['subject'] = $subject;
- } else {
- return array(NULL, NULL);
- }
- } else {
-
- if (stristr($template_name, 'TECHBODY')) {
- $language = "-1";
- }
- $result = $db3->query_return("
- SELECT template, subject
- FROM template_email
- WHERE name = '" . mysql_escape_string($template_name) . "' AND
- (
- language = '$language' OR
- language = '$settings[default_language]' OR
- category = 'Tech Emails'
- )
- ORDER BY language $order, backup
- ");
- if (is_array($result)) {
- $emailtemplate_cache[$language][$template_name]['body'] = $result['template'];
- $emailtemplate_cache[$language][$template_name]['subject'] = $result['subject'];
- } else {
- return array(NULL, NULL);
- }
- }
- }
- $template = $emailtemplate_cache[$language][$template_name]['body'];
- $subject = $emailtemplate_cache[$language][$template_name]['subject'];
-
- return array(
- 'body' => str_replace("'", ''', $template),
- 'subject' => $subject
- );
- }
- /*****************************************************
- function gettemplate
- -----DESCRIPTION: -----------------------------------
- Retrieve a HTML template.
- -----ARGUMENTS: -------------------------------------
- template_name Name of template to retrieve
- htmlcomment [Optional] Add a comment to the template
- -----RETURNS: ---------------------------------------
- The template, ready for eval().
- *****************************************************/
- function gettemplate($template_name, $htmlcomment=1) {
- global $template_cache, $template_group, $session, $settings;
-
- // get template from cache or database
- if ($template_name == 'log_out_') {
- $template = get_log_out_template();
- }
- if (isset($template_cache[$template_name])) {
- $template = $template_cache[$template_name];
- $cached = "CACHED";
- } else {
- // need a new sql class
- global $db_user,$db_password,$host,$dbname;
- $db3 = new_db_class(3);
- if (defined('TEMPLATEFILES')) {
- require_once(INCLUDE_PATH . 'functions/conditional_functions.php');
- $template = @implode('', @file("./admin/templates/$template_name.html"));
- /*
- $template = @file($location . "templates/email" . $lang[$language] . "/$template_name.txt");
- if (preg_match("/^Subject:(.*)$/i", $template[0], $matches)) {
- $subject = trim($matches[1]);
- array_shift($template);
- } else {
- $subject = '';
- }
- if (is_array($template)) {
- $emailtemplate_cache[$language][$template_name]['body'] = parse_conditionals(join('', $template));
-
- if (preg_match("/^Subject:(.*)$/i", $template[0], $matches)) {
- $subject = trim($matches[1]);
- array_shift($template);
- */
- $template = parse_conditionals($template);
- } else {
-
- $result = $db3->query_return("
- SELECT *
- FROM template
- WHERE name = '" . mysql_escape_string($template_name) . "'
- ORDER BY backup
- ");
- $template = $result[template];
- }
-
- $template_cache[$template_name] = $template;
- $cached = "NOT CACHED";
- }
- unset($htmlcomment);
- // add template commenting
- if ($htmlcomment) {
- return "n<!-- BEGIN TEMPLATE : $template_name {$cached} -->n$templaten<!-- END TEMPLATE : $template_name -->n";
- }
-
- return str_replace("'", ''', $template);
- }
- /*****************************************************
- function templatecache
- -----DESCRIPTION: -----------------------------------
- Initialize and load the template cache.
- -----ARGUMENTS: -------------------------------------
- template_list List of templates to load
- email If false, load HTML templates.
- If true, load email templates.
- -----RETURNS: ---------------------------------------
- The initialized template cache.
- *****************************************************/
- function templatecache($template_list, $email = NULL) {
- global $db, $template_group, $language, $settings;
-
- if (defined('TEMPLATEFILES')) {
-
- if (!$language AND $settings['default_language']) {
- $language = $settings['default_language'];
- } else {
- $language = 1;
- }
- require_once(INCLUDE_PATH . 'functions/conditional_functions.php');
- $templates_to_get = explode(',', $template_list);
- if (!$email) {
- foreach ($templates_to_get AS $key => $var) {
- $template = @implode('', @file("./admin/templates/$var.html"));
- $template = parse_conditionals($template);
-
- $template_cache[$var] = $template;
- }
- } else {
- $db->query("SELECT id, name FROM languages WHERE id = '" . mysql_escape_string($language) . "'");
- while ($res = $db->row_array()) {
- $lang[$res['id']] = $res['name'];
- }
- if (defined('USERZONE')) {
- $location = './admin/';
- } elseif (
- defined('TECHZONE')) {
- $location = './../../admin/';
- } elseif (defined('ADMINZONE')) {
- $loation = './';
- }
- foreach ($templates_to_get AS $key => $var) {
- $template = @file($location . "templates/email/" . $lang[$language] . "/$var.txt");
- if (preg_match("/^Subject:(.*)$/i", $template[0], $matches)) {
- $subject = ", subject = '" . mysql_escape_string(trim($matches[1])) . "'";
- array_shift($template);
- } else {
- $subject = NULL;
- }
- $template_cache[$var] = array(
- 'template' => parse_conditionals(join(NULL, $template)),
- 'subject' => $subject
- );
- }
- }
- return $template_cache;
- }
- // turn from comma list to SQL
- $template_list = str_replace(',', "','", $template_list);
-
- // determine ordering method
- if ($language > $settings['default_language']) {
- $order = "DESC";
- } else {
- $order = "ASC";
- }
- if ($email) {
- $table = 'template_email';
- } else {
- $table = 'template';
- }
- // get templates from database
- $db->query(" SELECT *
- FROM $table
- WHERE (name IN ('" . mysql_escape_string($template_list) . "'))
- ORDER BY backup
- ");
- while ($template = $db->row_array()) {
- str_replace("###", """, $template);
-
- // use correct language if template is avaliable
- if ($array[$template['name']] != "done") {
- if ($email) {
- $template_cache[$template['name']] = array('template' => $template['template'], 'subject' => $template['subject']);
- } else {
- $template_cache[$template['name']] = $template['template'];
- }
- $array[$template['name']] = "done";
- }
- }
- return $template_cache;
- }
- /*****************************************************
- function makeeval
- -----DESCRIPTION: -----------------------------------
- This function is always called before sending an
- email to a user. It updates the $user_details array
- to manipulate the greeting
- *****************************************************/
- function update_user_details($user_details) {
- $user_details['greeting'] = ifr($user_details['name'], $user_details['email']);
- return $user_details;
- }
- /*****************************************************
- function makeeval
- -----DESCRIPTION: -----------------------------------
- Prepare a template for evaluation.
- -----ARGUMENTS: -------------------------------------
- varname Variable to fill; if "echo", the
- template is evaluated here and echoed
- instead
- templatename Name of template to prepare
- add [Deprecated]
- dieonecho [Deprecated]
- comments Option to pass to gettemplate
- -----RETURNS: ---------------------------------------
- Eval()-read code, or none if "echo" specified for
- varname.
- *****************************************************/
- function makeeval($varname, $templatename = '', $add = false, $dieonecho = true, $comments = true) {
- $template = gettemplate($templatename, $comments);
- if ($varname == 'echo') {
- $template = preg_replace('#<%PHP%>(.+)<%ENDPHP%>#ise', "'";nob_start();n'.stripslashes(stripslashes('\1')).'n$__output = ob_get_contents();nob_end_clean();necho $__output."'", $template);
- // echo $template;
- return 'echo '.$template.'; ';
- } else {
- $template = preg_replace('#<%PHP%>(.+)<%ENDPHP%>#ise', "'";nob_start();n'.stripslashes('\1').'n$$varname .= ob_get_contents();nob_end_clean();n$$varname .= "'", $template);
- return '$'.$varname.' = '.$template.';';
- }
- }
- /*****************************************************
- function makeemaileval
- -----DESCRIPTION: -----------------------------------
- Prepare a template for evaluation.
- -----ARGUMENTS: -------------------------------------
- varname Variable to fill; if "echo", the
- template is evaluated here and echoed
- instead
- templatename Name of template to prepare
- subject [Pass by reference] Variable to load
- subject into
- ticket [Optional] Ticket data, for use in
- templates
- -----RETURNS: ---------------------------------------
- Eval()-read code, or none if "echo" specified for
- varname.
- *****************************************************/
- function makeemaileval($varname, $templatename, &$subject, $ticket = array()) {
- global $settings, $user, $session, $user_details;
- if (defined('USERZONE')) {
- if ($session['language']) {
- $language = $session['language'];
- } else {
- $language = $settings['default_language'];
- }
- } else {
- if ($user_details['language']) {
- $language = $user['language'];
- } else {
- $language = $settings['default_language'];
- }
- }
- if (!$language) {
- $language = $settings['default_language'];
- }
- $template = getemailtemplate($templatename, $language);
- if (!$template['body']) {
- return NULL;
- }
- if ($settings['email_footer']) {
- global $footer;
- $footer = getemailtemplate('EMAIL_footer', $language);
- $footer = preg_replace('#<%PHP%>(.+)<%ENDPHP%>#ise', "'";nob_start();n'.stripslashes('\1').'n$footer .= ob_get_contents();nob_end_clean();n$footer .= "'", $footer['body']);
- eval('$footer = '.$footer.';');
- }
- $subject = $template['subject'];
- $subject = preg_replace('#<%PHP%>(.+)<%ENDPHP%>#ise', "'";nob_start();n'.stripslashes('\1').'n$subject .= ob_get_contents();nob_end_clean();n$subject .= "'", $template['subject']);
-
- eval('$subject = "'.$subject.'";');
- $template['body'] = preg_replace('#<%PHP%>(.+)<%ENDPHP%>#ise', "'";nob_start();n'.stripslashes('\1').'n$$varname .= ob_get_contents();nob_end_clean();n$$varname .= "'", $template['body']);
- if (!$template['body']) {
- $template['body'] = 'NULL';
- }
- return '$'.$varname.' = '.$template['body'] . ';';
- }
- /*****************************************************
- function in_array_keys
- -----DESCRIPTION: -----------------------------------
- Search in an array for a specific value only in
- non-empty elements
- -----ARGUMENTS: -------------------------------------
- needle Item to search for
- haystack Array containing items to search
- -----RETURNS: ---------------------------------------
- True if found, false if not.
- *****************************************************/
- function in_array_keys($needle, $haystack) {
- if (is_array($haystack)) {
- foreach ($haystack AS $key => $var) {
- if ($needle == $key) {
- return true;
- }
- }
- }
- return false;
- }
- /*****************************************************
- function in_array_value
- -----DESCRIPTION: -----------------------------------
- Search in an array for a specific value only in
- non-empty elements
- -----ARGUMENTS: -------------------------------------
- needle Item to search for
- haystack Array containing items to search
- -----RETURNS: ---------------------------------------
- True if found, false if not.
- *****************************************************/
- function in_array_value($needle, $haystack) {
- if (is_array($haystack)) {
- foreach ($haystack AS $key => $var) {
- if ($needle == $var AND $var != '') {
- return true;
- }
- }
- }
- return false;
- }
- ###################### function if_default() #######################
- /*
- an overwrite default function, ie we send what is submitted, unless given a certain lack of a condition send the default
- */
- function if_default($yes, $condition='', $default='') {
- if ($yes) {
- return $yes;
- }
- if (!$condition) {
- return $default;
- }
- }
- ###################### function iff() #######################
- /* returns either $yes or $no depending upon value of $condition */
- function iff($condition, $yes='', $no='') {
- if ($condition) {
- if ($yes) {
- return $yes;
- } else {
- return $condition;
- }
- } else {
- return $no;
- }
- }
- ###################### function ifr() #######################
- function ifr($yes, $no) {
- if ($yes) {
- return $yes;
- } else {
- return $no;
- }
- }
- ###################### function ifyn() #######################
- /* returns either "yes" or "no" depending upon value of $condition */
- function ifyn($condtion) {
- if ($condition) {
- return "Yes";
- } else {
- return "No";
- }
-
- }
- ###################### function ifynb() #######################
- /* returns yes if true and no if false */
- function ifynb($value, $alternative='') {
- if ($value == "1") {
- return "Yes";
- } elseif ($value == "0") {
- return "No";
- } else {
- return $alternative;
- }
- }
- ###################### function multi_array2sql($array) #######################
- function multi_array2sql($array) {
- $sql = array();
- if (is_array($array)) {
- foreach ($array AS $key => $var) {
- $tmp = array();
-
- foreach ($var AS $key2 => $var2) {
- $tmp[] = ''' . mysql_escape_string($var2) . ''';
- }
- $sql[] = '(' . join(',', $tmp) . ')';
- }
- $sql = join(',', $sql);
- return $sql;
- }
- }
- ###################### function array2sql() #######################
- function array2sql($array, $empty='') {
- $sql = '(';
- $array = @array_unique($array);
- if ((is_array($array)) AND (count($array))) {
- foreach($array AS $key => $var) {
- if (is_array($var)) {
- $sql .= $var . ',';
- } else {
- $sql .= '"' . mysql_escape_string($var) . '",';
- }
- }
- $sql = substr($sql,0,-1);
- $sql .= ")";
- } else {
- if ($empty != "") {
- if (is_array($empty)) {
- $sql .= $empty . ')';
- } else {
- $sql .= ""$empty")";
- }
- } else {
- $sql = "('')";
- }
- }
-
- return $sql;
- }
- ###################### function trimstring() #######################
- /* trim string to specified length */
- function trimstring($string, $length, $dots='') {
- if (strlen($string) > $length) { // trim word, remove broken words
- $string = substr($string, 0, strrpos(substr($string, 0, $length), ' '));
- if ($dots) { // add dots
- $string .= ' ...';
- }
- }
- return $string;
- }
- /*****************************************************
- function make_pass
- -----DESCRIPTION: -----------------------------------
- Generate a random password of specified length.
- -----ARGUMENTS: -------------------------------------
- length Length of password to generate
- -----RETURNS: ---------------------------------------
- New random password.
- *****************************************************/
- function make_pass($length){
-
- $vowels = array("a", "e", "i", "o", "u");
- $cons = array("b", "c", "d", "g", "h", "j", "k", "l", "m", "n", "p", "r", "s", "t", "u", "v", "w", "tr",
- "cr", "br", "fr", "th", "dr", "ch", "ph", "wr", "st", "sp", "sw", "pr", "sl", "cl");
-
- $num_vowels = count($vowels);
- $num_cons = count($cons);
-
- for($i = 0; $i < $length; $i++){
- $password .= $cons[rand(0, $num_cons - 1)] . $vowels[rand(0, $num_vowels - 1)];
- }
-
- return substr($password, 0, $length);
- }
- /*****************************************************
- function make_username
- -----DESCRIPTION: -----------------------------------
- Generate a unique, valid username.
- -----ARGUMENTS: -------------------------------------
- email E-mail address
- name [Optional] Requested name
- -----RETURNS: ---------------------------------------
- New username.
- *****************************************************/
- function make_username($email, $name='', $noquery = 0) {
- /*
- generates a username from a name or email address
- numbers are added to get a unique username
- */
- global $db;
- $name = preg_replace('#[^a-z0-9_]#i', '', $name);
- $i = 0;
- if (strlen($name > 3)) {
- $username_tmp = trim($name);
- while (!$newusername) {
- $i++;
- if (!$noquery) {
- $db->query("SELECT username FROM user WHERE username = '" . mysql_escape_string($username_tmp) . "'");
- if ($db->num_rows()) {
- $username_tmp = trim($name) . (int)$i;
- } else {
- $newusername = 1;
- }
- } else {
- $newusername = 1;
- }
- }
- } else {
- // Grab everything leaving up to the @ and strip out everything
- // that's not alphanumeric.
- $username = substr($email, 0, strpos($email, '@'));
- $username = preg_replace('([^_a-zA-Z0-9-.])', '', $username);
- $username_tmp = trim($username);
- while (!$newusername) {
- $i++;
- if (!$noquery) {
- $db->query("SELECT username FROM user WHERE username = '" . mysql_escape_string($username_tmp) . "'");
- if ($db->num_rows()) {
- $username_tmp = trim($username) . (int)$i;
- } else {
- $newusername = 1;
- }
- } else {
- $newusername = 1;
- }
- }
- }
- return $username_tmp;
- }
- /*****************************************************
- function applyFunction
- -----DESCRIPTION: -----------------------------------
- - recurisvly parse a function
- -----ARGUMENTS: -------------------------------------
- input : the variable
- function : function name
- -----RETURNS:----------------------------------------
- The array
- *****************************************************/
- function applyFunction($input, $function) {
- if (is_array($input)) {
- foreach ($input as $key => $value) {
- $input[$key] = applyFunction($input[$key], $function);
- }
- } else {
- $input = $function($input);
- }
- return $input;
- }
- #################################################################################################
- # ATTACHMENT FUNCTIONS
- #################################################################################################
- /*****************************************************
- function add_attachment
- -----DESCRIPTION: -----------------------------------
- - adds attachment to the blob table. In future this will be the point to extend attachments to support filesystem storage
- -----ARGUMENTS: -------------------------------------
- $name : the name of the attachment (if it is not $_FILES['attachment'])
- -----GLOBALS:----------------------------------------
- $_FILES : array of files submitted by the browser
- -----RETURNS:----------------------------------------
- An array of details about the attachment (for storage in an explanatory table)
- *****************************************************/
- function add_attachment($name='') {
- global $_FILES, $db;
- if (!$name) {
- $name = "attachment";
- }
- $attachment = trim($_FILES[$name]['tmp_name']);
- $attachment_name = trim($_FILES[$name]['name']);
- $attachment_size = trim($_FILES[$name]['size']);
- $attachment_pointer = @fopen($attachment, 'rb');
- $attachment_data = @fread($attachment_pointer, $attachment_size);
- @fclose($attachment_pointer);
- @unlink($attachment);
- $db->query("INSERT INTO blobs SET blobdata = '" . mysql_escape_string($attachment_data) . "'");
- $id = $db->last_id();
- $attach = array(
- 'data' => $attachment_data,
- 'name' => $attachment_name,
- 'extension' => attachment_extension($attachment_name),
- 'blobid' => $id,
- 'size' => $attachment_size
- );
- return $attach;
- }
- /*****************************************************
- function get_attachment
- -----DESCRIPTION: -----------------------------------
- - gets attachment
- -----ARGUMENTS: -------------------------------------
- id : blobid
- table : the table name where the extension and name of the file are stored
- display : display instead of downloading. Will only work for certain attachment extensions
- -----RETURNS:----------------------------------------
- Directly prints to browser either a filestream or a page with the attachment
- *****************************************************/
- function get_attachment($id, $table, $display = '') {
- global $db;
- require_once(INCLUDE_PATH . 'data/mimetypes.php'); // gets the mime types
- $attachment = $db->query_return("SELECT * FROM $table WHERE id = '" . intval($id) . "'");
- if (!(strstr($HTTP_USER_AGENT, 'MSIE'))) {
- $atachment = ' atachment;';
- } else {
- $atachment = '';
- }
- if (in_array($attachment[extension], $mimetypes)) {
- $mimetype = $mimetypes[$attachment[extension]];
- } else {
- $mimetype = 'application/download';
- }
- // get the data. This can later be extended to read from a file
- $data = $db->query_return("SELECT * FROM blobs WHERE id = '" . intval($attachment[blobid]) . "'");
- // display in browser (needs implementing)
- $display_extensions = array('html', 'htm', 'txt');
- if ($display AND @in_array($attachment[extension], $display_extensions)) {
- header('Content-Type: ' . $mimetype . '; name=' . $attachment[filename]);
- header('Content-Disposition: inline; filename=' . $attachment[filename]);
- } else {
- header('Cache-control: max-age=31536000');
- header('Expires: '. gmdate('D, d M Y H:i:s', TIMENOW + 31536000) . 'GMT');
- header('Last-Modified: '. gmdate("D, d M Y H:i:s", $mail['dateline']) . 'GMT');
- header('Content-Length: ' . $attachment[filesize]);
- header('Content-Disposition: attachment; filename=' . $attachment[filename]);
- header('Content-Type: ' . $mimetype . '; name=' . $attachment[filename]);
- }
-
- echo $data[blobdata];
- exit();
- }
- /*****************************************************
- function explode_empty
- -----DESCRIPTION: -----------------------------------
- - explode a string into an array but remove any
- emtyy elements and do not return an array if no matches
- -----ARGUMENTS: -------------------------------------
- $split : what we are splitting on
- $string : the string
- -----RETURNS:----------------------------------------
- array or null
- *****************************************************/
- function explode_empty($split, $string) {
- $tmp = explode($split, $string);
- foreach ($tmp AS $key => $var) {
- if ($var != '') {
- $array[] = $var;
- }
- }
- return $array;
- }
- /*****************************************************
- function validate_attachment
- -----DESCRIPTION: -----------------------------------
- - validates attachments
- - can take account of max size, disallowed extension and allowed extensions
- -----ARGUMENTS: -------------------------------------
- &error : an error code is returned upon failure
- $name : the name of the attachment (if it is not $_FILES['attachment'])
- $maxsize : a maximum size for the attachment (in MB)
- $allowed_attachments : an array of allowed attachments. If set the extension must be in this array
- $disabled_attachments : an array of disabled attachments (e.g. .exe)
- -----GLOBALS:----------------------------------------
- $_FILES : array of files submitted by the browser
- -----RETURNS:----------------------------------------
- 1 for a valid attachment
- 0 for an invalid attachment
- &error for the error code if the attachment is invalid
- 1 : too big
- 2 : extension not in allowed list
- 3 : extension in disabled list
- 4 : failed is_uploaded_file check
- 5 : failed check on attachment name (ie no attachment uploaded)
- 6 : failed secutity filesize check
- *****************************************************/
- function validate_attachment(&$error, $name='', $maxsize='', $allowed_attachments='', $disabled_attachments='') {
- global $db, $_FILES, $settings;
- // allowed / disabled attachments
- if (defined('USERZONE')) {
- if (!$settings['attachments_user']) {
- return 0;
- }
- give_default($allowed_attachments, $settings[tech_extensions_allowed]);
- give_default($disabled_attachments, $settings[tech_disabled_attachments]);
- give_default($maxsize, $settings[attachments_user_size]);
- }
- if (defined('TECHZONE')) {
- give_default($allowed_attachments, $settings[user_extensions_allowed]);
- give_default($disabled_attachments, $settings[user_disabled_attachments]);
- give_default($maxsize, $settings[attachments_tech_size]);
- }
- // need to convert from MB to bytes
- $maxsize = $maxsize * 1024 * 1024;
- if (!is_array($allowed_attachments)) {
- $allowed_attachments = explode_empty(',', $allowed_attachments);
- }
- if (!is_array($disabled_attachments)) {
- $disabled_attachments = explode_empty(',', $disabled_attachments);
- }
- if (!$name) {
- $name = "attachment";
- }
- $attachment = trim($_FILES[$name]['tmp_name']);
- $attachment_name = trim($_FILES[$name]['name']);
- $attachment_size = trim($_FILES[$name]['size']);
- if ($attachment == 'none' or !$attachment or !$attachment_name) {
- @unlink($attachment);
- $error = 5;
- return 0;
- }
-
- if (!is_uploaded_file($attachment)) {
- @unlink($attachment);
- $error = 4;
- return 0;
- }
- // enabled & disabled extensions
- $extension = attachment_extension($attachment_name);
- if (is_array($allowed_attachments)) {
- if (!(in_array($extension, $allowed_attachments))) {
- $error = 2;
- @unlink($attachment);
- return 0;
- }
- }
- if (is_array($disabled_attachments)) {
- if (in_array($extension, $disabled_attachments)) {
- $error = 2;
- @unlink($attachment);
- return 0;
- }
- }
- // do size checks
- $filesize = filesize($attachment);
- if ($maxsize != 0 and $filesize > $maxsize) {
- @unlink($attachment);
- $error = 1;
- return 0;
- }
- if ($attachment_size != $filesize) {
- @unlink($attachment);
- $error = 6;
- return 0;
- }
- return 1;
- }
- ###################### function filesize_display #######################
- function filesize_display($filesize) {
- // sort out decimal places etc.
- $end = " bytes";
- if ($filesize > 103) {
- $filesize = $filesize / 1024;
- $end = " kb";
- }
- if ($filesize > 500) {
- $filesize = $filesize / 1024;
- $end = " mb";
- }
- $filesize = round($filesize, 1);
- return $filesize . $end;
- }
- ###################### function getextension #######################
- function attachment_extension($filename) {
- return substr(strrchr(strtolower($filename), '.'), 1);
- }
- /*****************************************************
- function make_ticket_ref
- -----DESCRIPTION: -----------------------------------
- Generate a unique, valid ticketref.
- -----ARGUMENTS: -------------------------------------
- table [Optional] Table to check against.
- -----RETURNS: ---------------------------------------
- New ticketref.
- *****************************************************/
- function make_ticket_ref($table = 'ticket') {
- $db = new_db_class();
- $ref_tmp = make_ref();
- while (!$ref_done) {
- $db->query("SELECT ref FROM $table WHERE ref = '" . mysql_escape_string($ref_tmp) . "'");
- if ($db->num_rows()) {
- $ref_tmp = make_ref();
- } else {
- $ref_done = 1;
- return($ref_tmp);
- }
- }
- }
- ###################### FUCTION check_license() ############################
- function check_license() {
- ?>
- <form method="post" action="#">
- <input type="hidden" name="encrypt_license" value="%%%md5license%%%">
- <input type="submit" name="submit" value="Click here to validate license">
- </form>
- <?php
- exit();
- }
- ###################### FUCTION force_refs() ############################
- ## Create object REFs for objects that don't have any in the given table
- /*****************************************************
- function force_refs
- -----DESCRIPTION: -----------------------------------
- Generate new ticketrefs for any ticket that doesn't
- have one.
- -----ARGUMENTS: -------------------------------------
- table [Optional] Table to check against.
- -----RETURNS: ---------------------------------------
- None.
- *****************************************************/
- function force_refs($table = 'ticket') {
- $db = new_db_class();
- $db->query("SELECT id FROM $table WHERE !ref");
- while ($res = $db->row_array()) {
- $process[] = $res['id'];
- }
- foreach($process AS $id) {
- $db->query("UPDATE $table SET ref = '" . mysql_escape_string(make_ticket_ref($table)) . "' WHERE id = '$id'");
- }
- }
- /*****************************************************
- function make_ref
- -----DESCRIPTION: -----------------------------------
- Generate a random ticketref.
- -----ARGUMENTS: -------------------------------------
- None.
- -----RETURNS: ---------------------------------------
- None.
- *****************************************************/
- function make_ref() {
- /* used to make a NNNN-AAAA-NNNN reference */
- $alpha = array('Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'Z', 'X', 'C', 'V', 'B', 'N', 'M');
- // get first 4 digit number (we don't want to start with 0)
- $bit = substr(mt_rand(1000,999999999), 0, 4);
- // get 4 alpha key
- $alpha_keys = array_rand($alpha, 4);
- $bit .= '-' . $alpha[$alpha_keys[0]] . $alpha[$alpha_keys[1]] . $alpha[$alpha_keys[2]] . $alpha[$alpha_keys[3]];
- // get another 4 digit random number
- $bit .= '-' . substr(mt_rand(10000000,99999999999), 3, 4);
- return $bit;
- }
- /***************************************************
- FUNCTION clean_time()
- Return a "cleaned up" representation of a unix timestamp,
- in the form of "2 days, 43 hours, 53 minutes, 43 seconds".
- ----------------------------------------------------
- Arguments:
- time: Unix timestamp
- ----------------------------------------------------
- Returns:
-
- Human-readable representation of timestamp.
- ****************************************************/
- function clean_time($time, $short = NULL) {
- $days = (int)($time / (24 * 60 * 60)); // Number of days
- $time = $time - ($days * (24 * 60 * 60));
- $hours = (int)($time / (60 * 60)); // Number of hours
- $time = $time - ($hours * (60 * 60));
- $minutes = (int)($time / 60); // Number of minutes
- $seconds = (int)($time - ($minutes * 60));
- unset ($time);
- if ($days) {
- if ($short) {
- $time .= $days . 'd ';
- } else {
- if ($days > 1) {
- $time .= "$days days ";
- } else {
- $time .= '1 day ';
- }
- }
- }
- if ($hours) {
- if ($short) {
- $time .= $hours . 'h ';
- } else {
- if ($hours > 1) {
- $time .= "$hours hours ";
- } else {
- $time .= '1 hour ';
- }
- }
- }
- if ($minutes) {
- if ($short) {
- $time .= $minutes . 'm ';
- } else {
- if ($minutes > 1) {
- $time .= "$minutes minutes ";
- } else {
- $time .= '1 minute ';
- }
- }
- }
- if ($seconds) {
- if ($short) {
- $time .= $seconds . 's ';
- } else {
- if ($seconds > 1) {
- $time .= "$seconds seconds ";
- } else {
- $time .= '1 second ';
- }
- }
- }
- if (!strlen($time)) {
- if ($short) {
- $time = '0s';
- } else {
- $time = "0 seconds";
- }
- }
-
- return $time;
- }
- /***********************************************************
- function validate_ymd
- ---- DESCRIPTION -------------------------------------------
- - Validates the provided date
- ---- ARGUMENTS ---------------------------------------------
- date : Date to be validated, in YYYY-MM-DD format
- ---- RETURNS -----------------------------------------------
- NULL if the date is invalid, non-null otherwise.
- ***********************************************************/
- function validate_ymd($date) {
- $orig = $date;
- $date = explode('-', $date);
- if (@checkdate($date[1], $date[2], $date[0])) {
- return $orig;
- } else {
- return 0;
- }
- }
- /*****************************************************
- function user_expired
- -----DESCRIPTION: -----------------------------------
- Determines whether the given user has expired or not.
- -----ARGUMENTS: -------------------------------------
- userid User to check.
- -----RETURNS: ---------------------------------------
- False if the user has not expired.
- An array, containing two elements (ticket count,
- and expiration date), if expired.
- *****************************************************/
- function user_expired($userid) {
- global $db;
- $user = $db->query_return("SELECT * FROM user WHERE id = '$userid'");
- if (!$db->num_rows()) {
- return -1;
- }
- $user_expired_tickets = 0;
- $user_expired_date = 0;
- $total = $db->query_return("SELECT count(*) AS total FROM ticket WHERE userid = '$user[id]'");
- $total = $total['total'];
- if (($total >= $user['expire_tickets']) AND $user['expire_tickets']) {
- $user_expired = 1;
- $user_expired_tickets = $total;
- }
-
- if ((mktime() >= $user['expire_date']) AND $user['expire_date']) {
- $user_expired = 1;
- $user_expired_date = our_date($user['expire_date']);
- }
-
- if ($user_expired) {
- return array($user_expired_tickets, $user_expired_date);
- } else {
- return 0;
- }
- }
- /***********************************************************
- function make_timezone
- ---- DESCRIPTION -------------------------------------------
- - Returns an HTML select form widget containing lots of
- time zones.
- ***********************************************************/
- function make_timezone($timezone = '0') {
- $zone = array(
- '-12' => "(GMT - 12:00 hours) Enitwetok, Kwajalien",
- '-11' => "(GMT - 11:00 hours) Midway Island, Samoa",
- '-10' => "(GMT - 10:00 hours) Hawaii",
- '-9' => "(GMT - 9:00 hours) Alaska",
- '-8' => "(GMT - 8:00 hours) Pacific Time (US & Canada)",
- '-7' => "(GMT - 7:00 hours) Mountain Time (US & Canada)",
- '-6' => "(GMT - 6:00 hours) Central Time (US & Canada)",
- '-5' => "(GMT - 5:00 hours) Eastern Time (US & Canada), Bogota, Lima, Quito",
- '-4' => "(GMT - 4:00 hours) Atlantic Time (Canada), Caracas, La Paz",
- '-3.5' => "(GMT - 3:30 hours) Newfoundland (NST)",
- '-3' => "(GMT - 3:00 hours) Brazil, Buenos Aires, Georgetown, Falkland Is.",
- '-2' => "(GMT - 2:00 hours) Mid-Atlantic, Ascention Is., St Helena",
- '-1' => "(GMT - 1:00 hours) Azores, Cape Verde Islands",
- '0' => "(GMT) Casablanca, Dublin, Edinburgh, London, Lisbon, Monrovia",
- '1' => "(GMT + 1:00 hours) Berlin, Brussels, Copenhagen, Madrid, Paris, Rome",
- '2' => "(GMT + 2:00 hours) Kaliningrad, South Africa, Warsaw",
- '3' => "(GMT + 3:00 hours) Baghdad, Riyadh, Moscow, Nairobi",
- '4' => "(GMT + 4:00 hours) Adu Dhabi, Baku, Muscat, Tbilisi",
- '5' => "(GMT + 5:00 hours) Ekaterinburg, Islamabad, Karachi, Tashkent",
- '6' => "(GMT + 6:00 hours) Almaty, Colomba, Dhakra",
- '7' => "(GMT + 7:00 hours) Bangkok, Hanoi, Jakarta",
- '8' => "(GMT + 8:00 hours) Beijing, Hong Kong, Perth, Singapore, Taipei",
- '9' => "(GMT + 9:00 hours) Osaka, Sapporo, Seoul, Tokyo, Yakutsk",
- '9.5' => "(GMT +9:30 hours) Adelaide",
- '10' => "(GMT + 10:00 hours) Melbourne, Papua New Guinea, Sydney, Vladivostok",
- '11' => "(GMT + 11:00 hours) Magadan, New Caledonia, Solomon Islands",
- '12' => "(GMT + 12:00 hours) Auckland, Wellington, Fiji, Marshall Island"
- );
-
- if (defined('TECHZONE')) {
- return form_select('timezone', $zone, '', $timezone);
- } else {
- return form_select('timezone', $zone, $timezone);
- }
- }
- /***********************************************************
- function is_win
- ---- DESCRIPTION -------------------------------------------
- - Returns true if running on a Windows platform, false if
- running on a Unix or Unix-like platform.
- ***********************************************************/
-
- function is_win() {
- return (substr(PHP_OS, 0, 3) == "WIN");
- }
- /***********************************************************
- function xss_check()
- ---- DESCRIPTION -------------------------------------------
- Checks the current technician's permissions, and if he's
- not permitted to submit raw HTML directly into fields
- calls htmlspecialchars_uni() on the value passed in and returns
- the result, otherwise returns the passed-in value.
- Tech interface function only.
- ---- ARGUMENTS ---------------------------------------------
- value The value submitted by the tech to be checked;
- can be an array or a string
- type Type of permission being checked
- user User interface data check
- tech Tech interface data check
- ---- RETURNS -----------------------------------------------
- The value (or values), altered with htmlentities if
- needed by the tech's permissions. If value is a string,
- returns a string. If the value is an array, returns
- an array containing processed values.
- ***********************************************************/
- function xss_check($value, $type = 'user') {
- global $user;
- if ($type == 'user') {
- $perm = $user['p_html_user'];
- } else {
- $perm = $user['p_html_tech'];
- }
- if ($perm) {
- return $value;
- } else {
- if (is_array($value)) {
- foreach ($value AS $val) {
- $tmpval[] = htmlspecialchars_uni($val);
- }
- $value = $tmpval;
- } else {
- $value = htmlspecialchars_uni($value);
- }
- }
-
- return $value;
- }
- /***********************************************************
- function htmlspecialchars_uni($text)
- ---- DESCRIPTION -------------------------------------------
- htmlspecialchars() but works with unicode text
- ***********************************************************/
- function htmlspecialchars_uni($text) {
-
- $text = preg_replace('/&(?!#[0-9]+;)/si', '&', $text);
- return str_replace(array('<', '>', '"'), array('<', '>', '"'), $text);
- }