/** function buildTicket - Builds,and returns, the major structure of the ticket to be entered.
  *
  * @param $i mail ID
  * @param $options array options
  *
  * @return ticket fields array
  */
 function buildTicket($i, $options = array())
 {
     $play_rules = isset($options['play_rules']) && $options['play_rules'];
     $head = $this->getHeaders($i);
     // Get Header Info Return Array Of Headers
     // **Key Are (subject,to,toOth,toNameOth,from,fromName)
     $tkt = array();
     $tkt['_blacklisted'] = false;
     // Detect if it is a mail reply
     $glpi_message_match = "/GLPI-([0-9]+)\\.[0-9]+\\.[0-9]+@\\w*/";
     // Check if email not send by GLPI : if yes -> blacklist
     if (preg_match($glpi_message_match, $head['message_id'], $match)) {
         $tkt['_blacklisted'] = true;
         return $tkt;
     }
     // max size = 0 : no import attachments
     if ($this->fields['filesize_max'] > 0) {
         if (is_writable(GLPI_DOC_DIR . "/_tmp/")) {
             $_FILES = $this->getAttached($i, GLPI_DOC_DIR . "/_tmp/", $this->fields['filesize_max']);
         } else {
             logInFile('mailgate', GLPI_DOC_DIR . "/_tmp/ is not writable");
         }
     }
     //  Who is the user ?
     $tkt['_users_id_requester'] = User::getOrImportByEmail($head['from']);
     $tkt["_users_id_requester_notif"]['use_notification'] = 1;
     if (!$tkt['_users_id_requester']) {
         $tkt["_users_id_requester_notif"]['alternative_email'] = $head['from'];
     }
     // Add to and cc as additional observer if user found
     if (count($head['ccs'])) {
         foreach ($head['ccs'] as $cc) {
             if ($cc != $head['from'] && strcasecmp($cc, $this->fields['name']) && ($tmp = User::getOrImportByEmail($cc)) > 0) {
                 $tkt['_additional_observers'][] = array('users_id' => $tmp, 'use_notification' => 1);
             }
         }
     }
     if (count($head['tos'])) {
         foreach ($head['tos'] as $to) {
             if ($to != $head['from'] && strcasecmp($to, $this->fields['name']) && ($tmp = User::getOrImportByEmail($to, false)) > 0) {
                 $tkt['_additional_observers'][] = array('users_id' => $tmp, 'use_notification' => 1);
             }
         }
     }
     // Auto_import
     $tkt['_auto_import'] = 1;
     // For followup : do not check users_id = login user
     $tkt['_do_not_check_users_id'] = 1;
     $body = $this->getBody($i);
     // Do it before using charset variable
     $head['subject'] = $this->decodeMimeString($head['subject']);
     $tkt['_head'] = $head;
     if (!empty($this->charset) && !$this->body_converted) {
         $body = encodeInUtf8($body, $this->charset);
         $this->body_converted = true;
     }
     if (!seems_utf8($body)) {
         $tkt['content'] = encodeInUtf8($body);
     } else {
         $tkt['content'] = $body;
     }
     // Add message from getAttached
     if ($this->addtobody) {
         $tkt['content'] .= $this->addtobody;
     }
     // See In-Reply-To field
     if (isset($head['in_reply_to'])) {
         if (preg_match($glpi_message_match, $head['in_reply_to'], $match)) {
             $tkt['tickets_id'] = intval($match[1]);
         }
     }
     // See in References
     if (!isset($tkt['tickets_id']) && isset($head['references'])) {
         if (preg_match($glpi_message_match, $head['references'], $match)) {
             $tkt['tickets_id'] = intval($match[1]);
         }
     }
     // See in title
     if (!isset($tkt['tickets_id']) && preg_match('/\\[GLPI #(\\d+)\\]/', $head['subject'], $match)) {
         $tkt['tickets_id'] = intval($match[1]);
     }
     // Found ticket link
     if (isset($tkt['tickets_id'])) {
         // it's a reply to a previous ticket
         $job = new Ticket();
         // Check if ticket  exists and users_id exists in GLPI
         /// TODO check if users_id have right to add a followup to the ticket
         if ($job->getFromDB($tkt['tickets_id']) && $job->fields['status'] != 'closed' && ($tkt['_users_id_requester'] > 0 || Ticket_User::isAlternateEmailForTicket($tkt['tickets_id'], $head['from']))) {
             $content = explode("\n", $tkt['content']);
             $tkt['content'] = "";
             $first_comment = true;
             $to_keep = array();
             foreach ($content as $ID => $val) {
                 if (isset($val[0]) && $val[0] == '>') {
                     // Delete line at the top of the first comment
                     if ($first_comment) {
                         $first_comment = false;
                         if (isset($to_keep[$ID - 1])) {
                             unset($to_keep[$ID - 1]);
                         }
                     }
                 } else {
                     $to_keep[$ID] = $ID;
                 }
             }
             foreach ($to_keep as $ID) {
                 $tkt['content'] .= $content[$ID] . "\n";
             }
             // Do not play rules for followups : WRONG : play rules only for refuse options
             //$play_rules = false;
         } else {
             // => to handle link in Ticket->post_addItem()
             $tkt['_linkedto'] = $tkt['tickets_id'];
             unset($tkt['tickets_id']);
         }
     }
     $tkt['name'] = $this->textCleaner($head['subject']);
     if (!isset($tkt['tickets_id'])) {
         // Which entity ?
         //$tkt['entities_id']=$this->fields['entities_id'];
         //$tkt['Subject']= $head['subject'];   // not use for the moment
         // Medium
         $tkt['urgency'] = "3";
         // No hardware associated
         $tkt['itemtype'] = "";
         // Mail request type
     } else {
         // Reopen if needed
         $tkt['add_reopen'] = 1;
     }
     $tkt['requesttypes_id'] = RequestType::getDefault('mail');
     $tkt['content'] = clean_cross_side_scripting_deep(html_clean($tkt['content']));
     if ($play_rules) {
         $rule_options['ticket'] = $tkt;
         $rule_options['headers'] = $head;
         $rule_options['mailcollector'] = $options['mailgates_id'];
         $rule_options['_users_id_requester'] = $tkt['_users_id_requester'];
         $rulecollection = new RuleMailCollectorCollection();
         $output = $rulecollection->processAllRules(array(), array(), $rule_options);
         // New ticket : compute all
         if (!isset($tkt['tickets_id'])) {
             foreach ($output as $key => $value) {
                 $tkt[$key] = $value;
             }
         } else {
             // Followup only copy refuse data
             $tobecopied = array('_refuse_email_no_response', '_refuse_email_with_response');
             foreach ($tobecopied as $val) {
                 if (isset($output[$val])) {
                     $tkt[$val] = $output[$val];
                 }
             }
         }
     }
     $tkt = addslashes_deep($tkt);
     return $tkt;
 }
 function sendNotification($options = array())
 {
     global $LANG;
     $mmail = new self();
     $mmail->AddCustomHeader("Auto-Submitted: auto-generated");
     $mmail->SetFrom($options['from'], $options['fromname']);
     if ($options['replyto']) {
         $mmail->AddReplyTo($options['replyto'], $options['replytoname']);
     }
     $mmail->Subject = $options['subject'];
     if (empty($options['content_html'])) {
         $mmail->isHTML(false);
         $mmail->Body = $options['content_text'];
     } else {
         $mmail->isHTML(true);
         $mmail->Body = $options['content_html'];
         $mmail->AltBody = $options['content_text'];
     }
     $mmail->AddAddress($options['to'], $options['toname']);
     $mmail->MessageID = "<GLPI-" . $options["items_id"] . "." . time() . "." . rand() . "@" . php_uname('n') . ">";
     $messageerror = $LANG['mailing'][47];
     if (!$mmail->Send()) {
         $senderror = true;
         addMessageAfterRedirect($messageerror . "<br>" . $mmail->ErrorInfo, true);
     } else {
         logInFile("mail", $LANG['tracking'][38] . " " . $options['to'] . " : " . $options['subject'] . "\n");
     }
     $mmail->ClearAddresses();
     return true;
 }
/**
 * Specific error handler in Normal mode
 *
 * @param $errno integer: level of the error raised.
 * @param $errmsg string: error message.
 * @param $filename string: filename that the error was raised in.
 * @param $linenum integer: line number the error was raised at.
 * @param $vars array: that points to the active symbol table at the point the error occurred.
**/
function userErrorHandlerNormal($errno, $errmsg, $filename, $linenum, $vars)
{
    // Date et heure de l'erreur
    $errortype = array(E_ERROR => 'Error', E_WARNING => 'Warning', E_PARSE => 'Parsing Error', E_NOTICE => 'Notice', E_CORE_ERROR => 'Core Error', E_CORE_WARNING => 'Core Warning', E_COMPILE_ERROR => 'Compile Error', E_COMPILE_WARNING => 'Compile Warning', E_USER_ERROR => 'User Error', E_USER_WARNING => 'User Warning', E_USER_NOTICE => 'User Notice', E_STRICT => 'Runtime Notice', 4096 => 'Catchable Fatal Error', 8192 => 'Deprecated function', 16384 => 'User deprecated function');
    // Les niveaux qui seront enregistrés
    $user_errors = array(E_USER_ERROR, E_USER_NOTICE, E_USER_WARNING);
    $err = $errortype[$errno] . "({$errno}): {$errmsg}\n";
    if (in_array($errno, $user_errors)) {
        $err .= "Variables:" . wddx_serialize_value($vars, "Variables") . "\n";
    }
    if (function_exists("debug_backtrace")) {
        $err .= "Backtrace :\n";
        $traces = debug_backtrace();
        foreach ($traces as $trace) {
            if (isset($trace["file"]) && isset($trace["line"])) {
                $err .= $trace["file"] . ":" . $trace["line"] . "\t\t" . (isset($trace["class"]) ? $trace["class"] : "") . (isset($trace["type"]) ? $trace["type"] : "") . (isset($trace["function"]) ? $trace["function"] . "()" : "") . "\n";
            }
        }
    } else {
        $err .= "Script: {$filename}, Line: {$linenum}\n";
    }
    // sauvegarde de l'erreur, et mail si c'est critique
    logInFile("php-errors", $err . "\n");
    return $errortype[$errno];
}
Esempio n. 4
0
 /**
  * Execute a MySQL query
  *
  * @param $query Query to execute
  *
  * @return Query result handler
  **/
 function query($query)
 {
     global $CFG_GLPI, $DEBUG_SQL, $SQL_TOTAL_REQUEST;
     if ($_SESSION['glpi_use_mode'] == DEBUG_MODE && $CFG_GLPI["debug_sql"]) {
         $SQL_TOTAL_REQUEST++;
         $DEBUG_SQL["queries"][$SQL_TOTAL_REQUEST] = $query;
         $TIMER = new Timer();
         $TIMER->start();
     }
     $res = @mysql_query($query, $this->dbh);
     if (!$res) {
         $this->connect();
         $res = mysql_query($query, $this->dbh);
         if (!$res) {
             $error = "*** MySQL query error : \n***\nSQL: " . addslashes($query) . "\nError: " . mysql_error() . "\n";
             if (function_exists("debug_backtrace")) {
                 $error .= "Backtrace :\n";
                 $traces = debug_backtrace();
                 foreach ($traces as $trace) {
                     $error .= (isset($trace["file"]) ? $trace["file"] : "") . "&nbsp;:" . (isset($trace["line"]) ? $trace["line"] : "") . "\t\t" . (isset($trace["class"]) ? $trace["class"] : "") . (isset($trace["type"]) ? $trace["type"] : "") . (isset($trace["function"]) ? $trace["function"] . "()" : "") . "\n";
                 }
             } else {
                 $error .= "Script : ";
             }
             $error .= $_SERVER["SCRIPT_FILENAME"] . "\n";
             logInFile("sql-errors", $error . "\n");
             if ($_SESSION['glpi_use_mode'] == DEBUG_MODE && $CFG_GLPI["debug_sql"]) {
                 $DEBUG_SQL["errors"][$SQL_TOTAL_REQUEST] = $this->error();
             }
         }
     }
     if ($_SESSION['glpi_use_mode'] == DEBUG_MODE && $CFG_GLPI["debug_sql"]) {
         $TIME = $TIMER->getTime();
         $DEBUG_SQL["times"][$SQL_TOTAL_REQUEST] = $TIME;
     }
     return $res;
 }
Esempio n. 5
0
 /**
  * Launch the need cron tasks
  *
  * @param $mode (internal/external, <0 to force)
  * @param $max number of task to launch ()
  * @param $name of task to run
  *
  * @return the name of last task launched
  **/
 public static function launch($mode, $max = 1, $name = '')
 {
     $taskname = '';
     if (self::get_lock()) {
         $crontask = new self();
         for ($i = 1; $i <= $max; $i++) {
             $prefix = ($mode == self::MODE_EXTERNAL ? 'External' : 'Internal') . " #{$i}: ";
             if ($crontask->getNeedToRun($mode, $name)) {
                 $_SESSION["glpicronuserrunning"] = "cron_" . $crontask->fields['name'];
                 if ($plug = isPluginItemType($crontask->fields['itemtype'])) {
                     Plugin::load($plug['plugin'], true);
                 }
                 $fonction = array($crontask->fields['itemtype'], 'cron' . $crontask->fields['name']);
                 if (is_callable($fonction)) {
                     if ($crontask->start()) {
                         // Lock in DB + log start
                         $taskname = $crontask->fields['name'];
                         logInFile('cron', $prefix . "Launch " . $crontask->fields['name'] . "\n");
                         $retcode = call_user_func($fonction, $crontask);
                         $crontask->end($retcode);
                         // Unlock in DB + log end
                     } else {
                         logInFile('cron', $prefix . "Can't start " . $crontask->fields['name'] . "\n");
                     }
                 } else {
                     if (is_array($fonction)) {
                         $fonction = implode('::', $fonction);
                     }
                     logInFile('php-errors', "Undefined function '{$fonction}' (for cron)\n");
                     logInFile('cron', $prefix . "Can't start " . $crontask->fields['name'] . "\nUndefined function '{$fonction}'\n");
                 }
             } else {
                 if ($i == 1) {
                     logInFile('cron', $prefix . "Nothing to launch\n");
                 }
             }
         }
         // end for
         $_SESSION["glpicronuserrunning"] = '';
         self::release_lock();
     } else {
         logInFile('cron', "Can't get DB lock'\n");
     }
     return $taskname;
 }
 /**
  * Function used to generate gif of rrdtool graph
  * 
  * @param type $itemtype
  * @param type $items_id
  * @param type $time 
  */
 function displayGLPIGraph($rrdtool_template, $itemtype, $items_id, $timezone, $time = '1d', $width = '470')
 {
     $filename = GLPI_PLUGIN_DOC_DIR . "/monitoring/templates/" . $rrdtool_template . "_graph.json";
     if (!file_exists($filename)) {
         return;
     }
     $a_json = json_decode(file_get_contents($filename));
     $timezonefile = str_replace("+", ".", $timezone);
     // Manage timezones
     $converttimezone = '0';
     if (strstr($timezone, '-')) {
         $timezone_temp = str_replace("-", "", $timezone);
         $converttimezone = $timezone_temp * 3600;
         $timezone = str_replace("-", "+", $timezone);
     } else {
         if (strstr($timezone, '+')) {
             $timezone_temp = str_replace("+", "", $timezone);
             $converttimezone = $timezone_temp * 3600;
             $timezone = str_replace("+", "-", $timezone);
         }
     }
     $opts = "";
     $opts .= ' --start -' . $time;
     $opts .= " --title '" . $a_json->data[0]->labels[0]->title . "'";
     //      $opts .= " --vertical-label '".$a_json->data->labels->vertical-label."'";
     $opts .= " --width " . $width;
     $opts .= " --height 200";
     foreach ($a_json->data[0]->miscellaneous[0]->color as $color) {
         $opts .= " --color " . $color;
     }
     if ($a_json->data[0]->limits[0]->{"upper-limit"} != "") {
         $opts .= " --upper-limit " . $a_json->data[0]->limits[0]->{"upper-limit"};
     }
     if ($a_json->data[0]->limits[0]->{"lower-limit"} != "") {
         $opts .= " --lower-limit " . $a_json->data[0]->limits[0]->{"lower-limit"};
     }
     if ($a_json->data[0]->{"y-axis"}[0]->{"units-exponent"} != "") {
         $opts .= " --units-exponent " . $a_json->data[0]->{"y-axis"}[0]->{"units-exponent"};
     }
     if ($a_json->data[0]->{"y-axis"}[0]->{"units"} != "") {
         $opts .= " --units " . $a_json->data[0]->{"y-axis"}[0]->{"units"};
     }
     foreach ($a_json->data[0]->data as $data) {
         $data = str_replace("[[RRDFILE]]", GLPI_PLUGIN_DOC_DIR . "/monitoring/" . $itemtype . "-" . $items_id . ".rrd", $data);
         if (strstr($time, "d") or strstr($time, "h")) {
             $data = str_replace("AVERAGE", "LAST", $data);
         }
         if (strstr($data, "DEF") and !strstr($data, "CDEF") and $converttimezone != '0') {
             $data = $data . ':start=-' . $time . $timezone . 'h:end=' . $timezone . 'h';
         }
         $opts .= " " . $data;
         if (strstr($data, "DEF") and !strstr($data, "CDEF") and $converttimezone != '0') {
             $a_explode = explode(":", $data);
             $a_name = explode("=", $a_explode[1]);
             $opts .= " SHIFT:" . $a_name[0] . ":" . $converttimezone;
         }
     }
     //$ret = rrd_graph(GLPI_PLUGIN_DOC_DIR."/monitoring/".$itemtype."-".$items_id."-".$time.".gif", $opts, count($opts));
     if (file_exists(GLPI_PLUGIN_DOC_DIR . "/monitoring/" . $itemtype . "-" . $items_id . ".rrd")) {
         $ret = '0';
         ob_start();
         $end = '';
         if (preg_match('/^windows/i', php_uname())) {
             session_write_close();
             $end = ' && exit';
         }
         system(PluginMonitoringConfig::getRRDPath() . "/rrdtool graph " . GLPI_PLUGIN_DOC_DIR . "/monitoring/" . $itemtype . "-" . $items_id . "-" . $time . $timezonefile . ".gif " . $opts . $end, $ret);
         ob_end_clean();
         if (isset($ret) and $ret != '0') {
             $displaytext = "Create error: {$ret} for " . PluginMonitoringConfig::getRRDPath() . "/rrdtool graph " . GLPI_PLUGIN_DOC_DIR . "/monitoring/" . $itemtype . "-" . $items_id . "-" . $time . $timezonefile . ".gif " . $opts . "\n";
             logInFile("plugin_monitoring_rrdtool", $displaytext);
             echo $displaytext;
         }
     }
     return true;
 }