logInFile() static public method

Log a message in log file
static public logInFile ( $name, $text, $force = false )
$name string name of the log file
$text string text to log
$force boolean force log in file not seeing use_log_in_files config (false by default)
 /**
  * Log when extra-debug is activated
  */
 static function logIfExtradebug($file, $message)
 {
     if (!PluginFusioninventoryConfig::isExtradebugActive()) {
         return;
     }
     Toolbox::logInFile($file, $message);
 }
 function sendProlog($input)
 {
     $input = gzcompress($input);
     $fp = fsockopen($this->server_ip, 80, $errno, $errstr, 30);
     if (!$fp) {
         echo "{$errstr} ({$errno})\n";
     } else {
         $out = "POST " . $this->server_urlpath . " HTTP/1.1\r\n";
         $out .= "Host: " . $this->server_ip . " \r\n";
         $out .= "Content-Length: " . strlen($input) . "\r\n";
         $out .= "Connection: close\r\n\r\n";
         fputs($fp, $out . $input);
         $zipped = "";
         while (!feof($fp)) {
             $line = fgets($fp, 4096);
             $zipped .= $line;
             if ($line == "\r\n") {
                 $zipped = "";
             }
         }
         fclose($fp);
         Toolbox::logInFile("RETSERV", $zipped . "\n");
         if (!gzuncompress($zipped)) {
             echo $zipped;
         }
         return gzuncompress($zipped);
     }
 }
 /**
  * Log when extra-debug is activated
  */
 static function logIfExtradebug($file, $message)
 {
     $config = new PluginFusioninventoryConfig();
     if ($config->getValue('extradebug')) {
         if (is_array($message)) {
             $message = print_r($message, TRUE);
         }
         Toolbox::logInFile($file, $message);
     }
 }
Example #4
0
 function post_addItem()
 {
     //only log in file, important events (connections and critical events; TODO : we need to add a general option to filter this in 9.1)
     if (isset($this->fields['level']) && $this->fields['level'] <= 3) {
         $message_type = "";
         if (isset($this->fields['type']) && $this->fields['type'] != 'system') {
             $message_type = "[" . $this->fields['type'] . " " . $this->fields['id'] . "] ";
         }
         $full_message = "[" . $this->fields['service'] . "] " . $message_type . $this->fields['level'] . ": " . Toolbox::stripslashes_deep($this->fields['message']) . "\n";
         Toolbox::logInFile("event", $full_message);
     }
 }
/**
 * Include locales for a specific report
 *
 * @param $report_name  the name of the report to use
 * @param $plugin       plugins name (default 'reports')
 *
 * @return boolean, true if locale found
**/
function includeLocales($report_name, $plugin = 'reports')
{
    global $CFG_GLPI, $LANG;
    $prefix = GLPI_ROOT . "/plugins/{$plugin}/report/" . $report_name . "/" . $report_name;
    if (isset($_SESSION["glpilanguage"]) && file_exists($prefix . "." . $_SESSION["glpilanguage"] . ".php")) {
        include_once $prefix . "." . $_SESSION["glpilanguage"] . ".php";
    } else {
        if (file_exists($prefix . ".en_GB.php")) {
            include_once $prefix . ".en_GB.php";
        } else {
            // At least defined report name
            $name = $report_name . '_report_title';
            $LANG['plugin_' . $plugin][$report_name] = __($report_name . '_report_title', $plugin);
            // For dev
            if ($LANG['plugin_' . $plugin][$report_name] == $report_name . '_report_title') {
                Toolbox::logInFile('php-errors', "includeLocales({$name}, {$plugin}) => not found\n");
            }
            //    return false;
        }
    }
    return true;
}
Example #6
0
            $mmail->FromName = $row['email'];
        }
    }
    $body = str_replace("\\r", "", str_replace("\\n", "\n", $_POST['body']));
    if ($_POST['users_id_ticketmail']) {
        $address = PluginTicketmailProfile::getEmail($_POST['users_id_ticketmail']);
    } else {
        $address = $_POST["address"];
    }
    if (!NotificationMail::isUserAddressValid($address)) {
        Session::addMessageAfterRedirect(__("Invalid email address"), false, ERROR);
    }
    $mmail->AddAddress($address, $address);
    $mmail->Subject = $_POST["subject"];
    $mmail->Body = $body;
    $mmail->MessageID = "GLPI-ticketmail" . time() . "." . rand() . "@" . php_uname('n');
    if (!$mmail->Send()) {
        Session::addMessageAfterRedirect(__("Your email could not be processed.\nIf the problem persists, contact the administrator"), false, ERROR);
    } else {
        Toolbox::logInFile("mail", sprintf(__('%1$s: %2$s'), sprintf(__('An email was sent to %s'), $address), $_POST["subject"] . "\n"));
        $changes[0] = 0;
        $changes[1] = $address;
        $changes[2] = $_POST['subject'];
        Log::history($_POST['id'], 'Ticket', $changes, 'PluginTicketmailProfile', Log::HISTORY_PLUGIN + 1024);
        Session::addMessageAfterRedirect(sprintf(__('An email was sent to %s'), $address));
    }
    $mmail->ClearAddresses();
    Html::redirect($_SERVER['HTTP_REFERER']);
} else {
    Html::redirect("../index.php");
}
 /**
  * Standard method execution : checks if client can execute method + manage session
  *
  * @param $method string method name
  * @param $params array the method parameters
  * @param $protocol the communication protocol used
  *
  * @return array the method response
  **/
 function execute($method, $params, $protocol)
 {
     global $DB, $WEBSERVICES_METHOD, $TIMER_DEBUG;
     // Don't display error in result
     set_error_handler(array('Toolbox', 'userErrorHandlerNormal'));
     ini_set('display_errors', 'Off');
     $iptxt = isset($_SERVER["HTTP_X_FORWARDED_FOR"]) ? $_SERVER["HTTP_X_FORWARDED_FOR"] : $_SERVER["REMOTE_ADDR"];
     $ipnum = strstr($iptxt, ':') === false ? ip2long($iptxt) : '';
     if (isset($_SESSION["MESSAGE_AFTER_REDIRECT"])) {
         // Avoid to keep "info" message between call
         $_SESSION["MESSAGE_AFTER_REDIRECT"] = '';
     }
     $plug = new Plugin();
     if ($plug->isActivated('webservices')) {
         if (isset($params['session'])) {
             self::setSession($params['session']);
         }
         // Build query for security check
         $sql = "SELECT *\n                 FROM `glpi_plugin_webservices_clients`\n                 WHERE '" . addslashes($method) . "' REGEXP pattern\n                       AND `is_active` = '1' ";
         if ($ipnum) {
             $sql .= " AND (`ip_start` IS NULL\n                            OR (`ip_start` <= '{$ipnum}' AND `ip_end` >= '{$ipnum}'))";
         } else {
             $sql .= " AND `ipv6` = '" . addslashes($iptxt) . "'";
         }
         if (isset($params["username"])) {
             $username = addslashes($params["username"]);
             $password = md5(isset($params["password"]) ? $params["password"] : '');
             $sql .= " AND (`username` IS NULL\n                               OR (`username` = '{$username}' AND `password` = '{$password}'))";
             unset($params["username"]);
             unset($params["password"]);
         } else {
             $username = '******';
             $sql .= " AND `username` IS NULL ";
         }
         $deflate = $debug = $log = false;
         $entities = array();
         if (Session::getLoginUserID() && isset($_SESSION['glpiactiveentities'])) {
             $username = $_SESSION['glpiname'];
             // for log (no t for SQL request)
         }
         foreach ($DB->request($sql) as $data) {
             // Check matching rules
             // Store entities for not authenticated user
             if (!Session::getLoginUserID()) {
                 if ($data['is_recursive']) {
                     foreach (getSonsOf("glpi_entities", $data['entities_id']) as $entity) {
                         $entities[$entity] = $entity;
                     }
                 } else {
                     $entities[$data['entities_id']] = $data['entities_id'];
                 }
             }
             // Where to log
             if ($data["do_log"] == 2) {
                 // Log to file
                 $log = LOGFILENAME;
             } else {
                 if ($data["do_log"] == 1) {
                     // Log to History
                     $log = $data["id"];
                 }
             }
             $debug = $data['debug'];
             $deflate = $data['deflate'];
         }
         $callname = '';
         // Always log when connection denied
         if (!Session::getLoginUserID() && !count($entities)) {
             $resp = self::Error($protocol, 1, __('Access denied'));
             // log to file (not macthing config to use history)
             Toolbox::logInFile(LOGFILENAME, __('Access denied') . " ({$username}, {$iptxt}, {$method}, {$protocol})\n");
         } else {
             // Allowed
             if (!Session::getLoginUserID()) {
                 // TODO : probably more data should be initialized here
                 $_SESSION['glpiactiveentities'] = $entities;
             }
             // Log if configured
             if (is_numeric($log)) {
                 $changes[0] = 0;
                 $changes[1] = "";
                 $changes[2] = __('Connection') . " ({$username}, {$iptxt}, {$method}, {$protocol})";
                 Log::history($log, 'PluginWebservicesClient', $changes, 0, Log::HISTORY_LOG_SIMPLE_MESSAGE);
             } else {
                 if ($log && !$debug) {
                     Toolbox::logInFile($log, __('Connection') . " ({$username}, {$iptxt}, {$method})\n");
                 }
             }
             $defserver = ini_get('zlib.output_compression');
             if ($deflate && !$defserver) {
                 // Globally off, try to enable for this client
                 // This only work on PHP > 5.3.0
                 ini_set('zlib.output_compression', 'On');
             }
             if (!$deflate && $defserver) {
                 // Globally on, disable for this client
                 ini_set('zlib.output_compression', 'Off');
             }
             if (!isset($WEBSERVICES_METHOD[$method])) {
                 $resp = self::Error($protocol, 2, "Unknown method ({$method})");
                 Toolbox::logInFile(LOGFILENAME, "Unknown method ({$method})\n");
             } else {
                 if (is_callable($call = $WEBSERVICES_METHOD[$method], false, $callname)) {
                     $resp = call_user_func($WEBSERVICES_METHOD[$method], $params, $protocol);
                     Toolbox::logInFile(LOGFILENAME, "Execute method:{$method} ({$protocol}), function:{$callname}, " . "duration:" . $TIMER_DEBUG->getTime() . ", size:" . strlen(serialize($resp)) . "\n");
                 } else {
                     $resp = self::Error($protocol, 3, "Unknown internal function for {$method}", $protocol);
                     Toolbox::logInFile(LOGFILENAME, "Unknown internal function for {$method}\n");
                 }
             }
         }
         // Allowed
         if ($debug) {
             Toolbox::logInFile(LOGFILENAME, __('Connection') . ": {$username}, {$iptxt}\n" . "Protocol: {$protocol}, Method: {$method}, Function: {$callname}\n" . "Params: " . (count($params) ? print_r($params, true) : "none\n") . "Compression: Server:{$defserver}/" . ini_get('zlib.output_compression') . ", Config:{$deflate}, Agent:" . (isset($_SERVER['HTTP_ACCEPT_ENCODING']) ? $_SERVER['HTTP_ACCEPT_ENCODING'] : '?') . "\nDuration: " . $TIMER_DEBUG->getTime() . "\nResponse size: " . strlen(serialize($resp)) . "\nResponse content: " . print_r($resp, true));
         }
     } else {
         $resp = self::Error($protocol, 4, "Server not ready", $protocol);
     }
     // Activated
     return $resp;
 }
Example #8
0
 /**
  * Add a message to be displayed after redirect
  *
  * @param $msg             Message to add
  * @param $check_once      Check if the message is not already added (false by default)
  * @param $message_type    Message type (INFO, ERROR) (default INFO)
  * @param $reset           Clear previous added message (false by default)
  **/
 static function addMessageAfterRedirect($msg, $check_once = false, $message_type = INFO, $reset = false)
 {
     if (!empty($msg)) {
         if (self::isCron()) {
             // We are in cron mode
             // Do not display message in user interface, but record error
             if ($message_type == ERROR) {
                 Toolbox::logInFile('cron', $msg . "\n");
             }
         } else {
             if ($reset) {
                 $_SESSION["MESSAGE_AFTER_REDIRECT"] = '';
             }
             $toadd = "";
             if ($check_once) {
                 if (strstr($_SESSION["MESSAGE_AFTER_REDIRECT"], $msg) === false) {
                     $toadd = $msg . '<br>';
                 }
             } else {
                 $toadd = $msg . '<br>';
             }
             if (!empty($toadd)) {
                 switch ($message_type) {
                     case ERROR:
                     case WARNING:
                         $_SESSION["MESSAGE_AFTER_REDIRECT"] .= "<h3><span class='red'>{$toadd}</span></h3>";
                         break;
                     default:
                         // INFO
                         $_SESSION["MESSAGE_AFTER_REDIRECT"] .= "<h3>{$toadd}</h3>";
                 }
             }
         }
     }
 }
Example #9
0
 /** function buildTicket - Builds,and returns, the major structure of the ticket to be entered.
  *
  * @param $i                  mail ID
  * @param $options   array    of possible options
  *
  * @return ticket fields array
  */
 function buildTicket($i, $options = array())
 {
     global $CFG_GLPI;
     $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;
     // For RuleTickets
     $tkt['_mailgate'] = $options['mailgates_id'];
     // Use mail date if it's defined
     if ($this->fields['use_mail_date']) {
         $tkt['date'] = $head['date'];
     }
     // 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 (!isset($head['message_id']) || preg_match($glpi_message_match, $head['message_id'], $match)) {
         $tkt['_blacklisted'] = true;
         return $tkt;
     }
     // manage blacklist
     $blacklisted_emails = Blacklist::getEmails();
     // Add name of the mailcollector as blacklisted
     $blacklisted_emails[] = $this->fields['name'];
     if (Toolbox::inArrayCaseCompare($head['from'], $blacklisted_emails)) {
         $tkt['_blacklisted'] = true;
         return $tkt;
     }
     // max size = 0 : no import attachments
     if ($this->fields['filesize_max'] > 0) {
         if (is_writable(GLPI_TMP_DIR)) {
             $tkt['_filename'] = $this->getAttached($i, GLPI_TMP_DIR . "/", $this->fields['filesize_max']);
             $tkt['_tag'] = $this->tags;
         } else {
             //TRANS: %s is a directory
             Toolbox::logInFile('mailgate', sprintf(__('%s is not writable'), GLPI_TMP_DIR . "/"));
         }
     }
     //  Who is the user ?
     $tkt['_users_id_requester'] = User::getOrImportByEmail($head['from']);
     $tkt["_users_id_requester_notif"]['use_notification'] = 1;
     // Set alternative email if user not found / used if anonymous mail creation is enable
     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'] && !Toolbox::inArrayCaseCompare($cc, $blacklisted_emails) && ($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'] && !Toolbox::inArrayCaseCompare($to, $blacklisted_emails) && ($tmp = User::getOrImportByEmail($to)) > 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 = Toolbox::encodeInUtf8($body, $this->charset);
         $this->body_converted = true;
     }
     if (!Toolbox::seems_utf8($body)) {
         $tkt['content'] = Toolbox::encodeInUtf8($body);
     } else {
         $tkt['content'] = $body;
     }
     // 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('/\\[.+#(\\d+)\\]/', $head['subject'], $match)) {
         $tkt['tickets_id'] = intval($match[1]);
     }
     $is_html = false;
     //If files are present and content is html
     if (isset($this->files) && count($this->files) && $tkt['content'] != strip_tags($tkt['content']) && !isset($tkt['tickets_id'])) {
         $is_html = true;
         $tkt['content'] = Ticket::convertContentForTicket($tkt['content'], array_merge($this->files, $this->altfiles), $this->tags);
     }
     $tkt['content'] = $this->cleanMailContent($tkt['content']);
     if ($is_html && !isset($tkt['tickets_id'])) {
         $tkt['content'] = nl2br($tkt['content']);
     }
     $tkt['_supplier_email'] = false;
     // Found ticket link
     if (isset($tkt['tickets_id'])) {
         // it's a reply to a previous ticket
         $job = new Ticket();
         $tu = new Ticket_User();
         $st = new Supplier_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'] != CommonITILObject::CLOSED && ($CFG_GLPI['use_anonymous_followups'] || $tkt['_users_id_requester'] > 0 || $tu->isAlternateEmailForITILObject($tkt['tickets_id'], $head['from']) || ($tkt['_supplier_email'] = $st->isSupplierEmail($tkt['tickets_id'], $head['from'])))) {
             if ($tkt['_supplier_email']) {
                 $tkt['content'] = sprintf(__('From %s'), $head['from']) . "\n\n" . $tkt['content'];
             }
             $content = explode("\n", $tkt['content']);
             $tkt['content'] = "";
             $to_keep = array();
             // Move requester to author of followup :
             $tkt['users_id'] = $tkt['_users_id_requester'];
             $begin_strip = -1;
             $end_strip = -1;
             $begin_match = "/" . NotificationTargetTicket::HEADERTAG . ".*" . NotificationTargetTicket::HEADERTAG . "/";
             $end_match = "/" . NotificationTargetTicket::FOOTERTAG . ".*" . NotificationTargetTicket::FOOTERTAG . "/";
             foreach ($content as $ID => $val) {
                 // Get first tag for begin
                 if ($begin_strip < 0) {
                     if (preg_match($begin_match, $val)) {
                         $begin_strip = $ID;
                     }
                 }
                 // Get last tag for end
                 if ($begin_strip >= 0) {
                     if (preg_match($end_match, $val)) {
                         $end_strip = $ID;
                         continue;
                     }
                 }
             }
             if ($begin_strip >= 0) {
                 // Clean first and last lines
                 $content[$begin_strip] = preg_replace($begin_match, '', $content[$begin_strip]);
             }
             if ($end_strip >= 0) {
                 // Clean first and last lines
                 $content[$end_strip] = preg_replace($end_match, '', $content[$end_strip]);
             }
             if ($begin_strip >= 0) {
                 $length = count($content);
                 // Use end strip if set
                 if ($end_strip >= 0 && $end_strip < $length) {
                     $length = $end_strip;
                 }
                 for ($i = $begin_strip + 1; $i < $length; $i++) {
                     unset($content[$i]);
                 }
             }
             $to_keep = array();
             // Aditional clean for thunderbird
             foreach ($content as $ID => $val) {
                 if (!isset($val[0]) || $val[0] != '>') {
                     $to_keep[$ID] = $ID;
                 }
             }
             $tkt['content'] = "";
             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']);
         }
     }
     // Add message from getAttached
     if ($this->addtobody) {
         $tkt['content'] .= $this->addtobody;
     }
     $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');
     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 = Toolbox::addslashes_deep($tkt);
     return $tkt;
 }
Example #10
0
 /**
  * @param $options   array
  **/
 function sendNotification($options = array())
 {
     $mmail = new self();
     $mmail->AddCustomHeader("Auto-Submitted: auto-generated");
     // For exchange
     $mmail->AddCustomHeader("X-Auto-Response-Suppress: OOF, DR, NDR, RN, NRN");
     $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']);
     if (!empty($options['messageid'])) {
         $mmail->MessageID = "<" . $options['messageid'] . ">";
     }
     $messageerror = __('Error in sending the email');
     if (!$mmail->Send()) {
         $senderror = true;
         Session::addMessageAfterRedirect($messageerror . "<br>" . $mmail->ErrorInfo, true);
     } else {
         //TRANS to be written in logs %1$s is the to email / %2$s is the subject of the mail
         Toolbox::logInFile("mail", sprintf(__('%1$s: %2$s'), sprintf(__('An email was sent to %s'), $options['to']), $options['subject'] . "\n"));
     }
     $mmail->ClearAddresses();
     return true;
 }
Example #11
0
 /**
  * Generate the PDF for some object
  *
  * @param $tab_id  Array   of ID of object to print
  * @param $tabs    Array   of name of tab to print
  * @param $page    Integer 1 for landscape, 0 for portrait
  * @param $render  Boolean send result if true,  return result if false
  *
  * @return pdf output if $render is false
  **/
 final function generatePDF($tab_id, $tabs, $page = 0, $render = true)
 {
     $this->pdf = new PluginPdfSimplePDF('a4', $page ? 'landscape' : 'portrait');
     foreach ($tab_id as $key => $id) {
         if ($this->addHeader($id)) {
             $this->pdf->newPage();
         } else {
             // Object not found or no right to read
             continue;
         }
         foreach ($tabs as $tab) {
             if (!$this->displayTabContentForPDF($this->pdf, $this->obj, $tab) && !$this->displayCommonTabForPDF($this->pdf, $this->obj, $tab)) {
                 $data = explode('$', $tab);
                 $itemtype = $data[0];
                 // Default set
                 $tabnum = isset($data[1]) ? $data[1] : 1;
                 if (!is_integer($itemtype) && $itemtype != 'empty') {
                     if ($itemtype == "Item_Devices") {
                         $PluginPdfComputer = new PluginPdfComputer();
                         if ($PluginPdfComputer->displayTabContentForPdf($this->pdf, $this->obj, $tabnum)) {
                             continue;
                         }
                     } else {
                         if (method_exists($itemtype, "displayTabContentForPdf") && ($obj = getItemForItemtype($itemtype))) {
                             if ($obj->displayTabContentForPdf($this->pdf, $this->obj, $tabnum)) {
                                 continue;
                             }
                         }
                     }
                 }
                 Toolbox::logInFile('php-errors', sprintf(__("PDF: don't know how to display %s tab") . '\\n', $tab));
             }
         }
     }
     if ($render) {
         $this->pdf->render();
     } else {
         return $this->pdf->output();
     }
 }
 function getAgentsSubnet($nb_computers, $communication, $subnet = '', $ipstart = '', $ipend = '')
 {
     global $DB;
     $pfTaskjob = new PluginFusioninventoryTaskjob();
     $pfAgentmodule = new PluginFusioninventoryAgentmodule();
     // Number of computers min by agent
     $nb_computerByAgentMin = 20;
     $nb_agentsMax = ceil($nb_computers / $nb_computerByAgentMin);
     $a_agentList = array();
     if ($subnet != '') {
         $subnet = " AND `glpi_ipaddresses`.`name` LIKE '" . $subnet . "%' ";
     } else {
         if ($ipstart != '' and $ipend != '') {
             $subnet = " AND ( INET_ATON(`glpi_ipaddresses`.`name`) > INET_ATON('" . $ipstart . "')\n            AND  INET_ATON(`glpi_ipaddresses`.`name`) < INET_ATON('" . $ipend . "') ) ";
         }
     }
     $a_agents = $pfAgentmodule->getAgentsCanDo('NETWORKINVENTORY');
     $a_agentsid = array();
     foreach ($a_agents as $a_agent) {
         $a_agentsid[] = $a_agent['id'];
     }
     if (count($a_agentsid) == '0') {
         return $a_agentList;
     }
     $where = " AND `glpi_plugin_fusioninventory_agents`.`ID` IN (";
     $where .= implode(', ', $a_agentsid);
     $where .= ")\n         AND `glpi_ipaddresses`.`name` != '127.0.0.1' ";
     $query = "SELECT `glpi_plugin_fusioninventory_agents`.`id` as `a_id`,\n         `glpi_ipaddresses`.`name` as ip, token\n         FROM `glpi_plugin_fusioninventory_agents`\n         LEFT JOIN `glpi_networkports`\n            ON `glpi_networkports`.`items_id` = `glpi_plugin_fusioninventory_agents`.`computers_id`\n         LEFT JOIN `glpi_networknames`\n              ON `glpi_networknames`.`items_id`=`glpi_networkports`.`id`\n                 AND `glpi_networknames`.`itemtype`='NetworkPort'\n         LEFT JOIN `glpi_ipaddresses`\n              ON `glpi_ipaddresses`.`items_id`=`glpi_networknames`.`id`\n                 AND `glpi_ipaddresses`.`itemtype`='NetworkName'\n         LEFT JOIN `glpi_computers`\n            ON `glpi_computers`.`id` = `glpi_plugin_fusioninventory_agents`.`computers_id`\n         WHERE `glpi_networkports`.`itemtype`='Computer'\n            " . $subnet . "\n            " . $where . " ";
     Toolbox::logInFile('NET', $query);
     $result = $DB->query($query);
     if ($result) {
         while ($data = $DB->fetch_array($result)) {
             if ($communication == 'push') {
                 if ($pfTaskjob->isAgentAlive("1", $data['a_id'])) {
                     if (!in_array($a_agentList, $data['a_id'])) {
                         $a_agentList[] = $data['a_id'];
                         if (count($a_agentList) >= $nb_agentsMax) {
                             return $a_agentList;
                         }
                     }
                 }
             } else {
                 if ($communication == 'pull') {
                     if (!in_array($data['a_id'], $a_agentList)) {
                         $a_agentList[] = $data['a_id'];
                         if (count($a_agentList) > $nb_agentsMax) {
                             return $a_agentList;
                         }
                     }
                 }
             }
         }
     }
     return $a_agentList;
 }
 /**
  * Log when extra-debug is activated
  */
 static function logIfExtradebug($file, $message)
 {
     if (self::isExtradebugActive()) {
         if (is_array($message)) {
             $message = print_r($message, TRUE);
         }
         Toolbox::logInFile($file, $message);
     }
 }
Example #14
0
 /**
  * Add a message to be displayed after redirect
  *
  * @param $msg             Message to add
  * @param $check_once      Check if the message is not already added (false by default)
  * @param $message_type    Message type (INFO, WARNING, ERROR) (default INFO)
  * @param $reset           Clear previous added message (false by default)
  **/
 static function addMessageAfterRedirect($msg, $check_once = false, $message_type = INFO, $reset = false)
 {
     if (!empty($msg)) {
         if (self::isCron()) {
             // We are in cron mode
             // Do not display message in user interface, but record error
             if ($message_type == ERROR) {
                 Toolbox::logInFile('cron', $msg . "\n");
             }
         } else {
             if ($reset) {
                 $_SESSION["MESSAGE_AFTER_REDIRECT"] = [];
             }
             if (!isset($_SESSION["MESSAGE_AFTER_REDIRECT"][$message_type])) {
                 $_SESSION["MESSAGE_AFTER_REDIRECT"][$message_type] = array();
             }
             if (!$check_once || !isset($_SESSION["MESSAGE_AFTER_REDIRECT"][$message_type]) || in_array($msg, $_SESSION["MESSAGE_AFTER_REDIRECT"][$message_type]) === false) {
                 array_push($_SESSION["MESSAGE_AFTER_REDIRECT"][$message_type], $msg);
             }
         }
     }
 }
Example #15
0
 static function executeSync()
 {
     $REP_XML = GLPI_PLUGIN_DOC_DIR . '/sccm/xml/';
     $PluginSccmConfig = new PluginSccmConfig();
     $PluginSccmConfig->getFromDB(1);
     $PluginSccmSccm = new PluginSccmSccm();
     if ($PluginSccmConfig->getField('active_sync') == 1) {
         Toolbox::logInFile('sccm', "Inject start \n", true);
         $PluginSccmSccm->getDevices();
         Toolbox::logInFile('sccm', "getDevices OK \n", true);
         Toolbox::logInFile('sccm', "Generate XML start : " . count($PluginSccmSccm->devices) . " files\n", true);
         foreach ($PluginSccmSccm->devices as $device_values) {
             $PluginSccmSccmxml = new PluginSccmSccmxml($device_values);
             $PluginSccmSccmxml->setAccessLog();
             $PluginSccmSccmxml->setAccountInfos();
             $PluginSccmSccmxml->setHardware();
             $PluginSccmSccmxml->setOS();
             $PluginSccmSccmxml->setBios();
             $PluginSccmSccmxml->setProcessors();
             $PluginSccmSccmxml->setSoftwares();
             $PluginSccmSccmxml->setUsers();
             $PluginSccmSccmxml->setNetworks();
             $PluginSccmSccmxml->setDrives();
             $SXML = $PluginSccmSccmxml->sxml;
             $SXML->asXML($REP_XML . $PluginSccmSccmxml->device_id . ".ocs");
             $ch = curl_init();
             curl_setopt($ch, CURLOPT_URL, $PluginSccmConfig->getField('fusioninventory_url'));
             curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml'));
             curl_setopt($ch, CURLOPT_HEADER, 0);
             curl_setopt($ch, CURLOPT_POST, 1);
             curl_setopt($ch, CURLOPT_POSTFIELDS, $SXML->asXML());
             curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
             curl_setopt($ch, CURLOPT_REFERER, $PluginSccmConfig->getField('fusioninventory_url'));
             curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
             $ch_result = curl_exec($ch);
             curl_close($ch);
             Toolbox::logInFile('sccm', "Ajout OK - " . $PluginSccmSccmxml->device_id . " \n", true);
         }
     } else {
         echo __("Synchronization is disabled by configuration.", "sccm");
     }
 }
 function linkComponentsToItem($componentscatalogs_id, $componentscatalogs_hosts_id, $networkports_id = 0)
 {
     global $DB;
     Toolbox::logInFile("NET", $networkports_id . "\n");
     $pmService = new PluginMonitoringService();
     $pmComponentscatalog_Host = new PluginMonitoringComponentscatalog_Host();
     $pmComponentscatalog_Host->getFromDB($componentscatalogs_hosts_id);
     $query = "SELECT * FROM `glpi_plugin_monitoring_componentscatalogs_components`\n         WHERE `plugin_monitoring_componentscalalog_id`='" . $componentscatalogs_id . "'";
     $result = $DB->query($query);
     while ($data = $DB->fetch_array($result)) {
         $input = array();
         $itemtype = $pmComponentscatalog_Host->fields['itemtype'];
         $item = new $itemtype();
         $item->getFromDB($pmComponentscatalog_Host->fields['items_id']);
         if ($networkports_id == '0') {
             $input['entities_id'] = $item->fields['entities_id'];
             $input['plugin_monitoring_componentscatalogs_hosts_id'] = $componentscatalogs_hosts_id;
             $input['plugin_monitoring_components_id'] = $data['plugin_monitoring_components_id'];
             $input['name'] = Dropdown::getDropdownName("glpi_plugin_monitoring_components", $data['plugin_monitoring_components_id']);
             $input['state'] = 'WARNING';
             $input['state_type'] = 'HARD';
             $pmService->add($input);
         } else {
             if ($networkports_id > 0) {
                 $a_services = $pmService->find("`plugin_monitoring_components_id`='" . $data['plugin_monitoring_components_id'] . "'\n               AND `plugin_monitoring_componentscatalogs_hosts_id`='" . $componentscatalogs_hosts_id . "'\n               AND `networkports_id`='" . $networkports_id . "'", "", 1);
                 $item = new NetworkPort();
                 $item->getFromDB($networkports_id);
                 if (count($a_services) == '0') {
                     $input = array();
                     $input['networkports_id'] = $networkports_id;
                     $input['entities_id'] = $item->fields['entities_id'];
                     $input['plugin_monitoring_componentscatalogs_hosts_id'] = $componentscatalogs_hosts_id;
                     $input['plugin_monitoring_components_id'] = $data['plugin_monitoring_components_id'];
                     $input['name'] = Dropdown::getDropdownName("glpi_plugin_monitoring_components", $data['plugin_monitoring_components_id']);
                     $input['state'] = 'WARNING';
                     $input['state_type'] = 'HARD';
                     $pmService->add($input);
                 } else {
                     $a_service = current($a_services);
                     $queryu = "UPDATE `glpi_plugin_monitoring_services`\n                  SET `entities_id`='" . $item->fields['entities_id'] . "'\n                     WHERE `id`='" . $a_service['id'] . "'";
                     $DB->query($queryu);
                 }
             }
         }
     }
 }
 /**
  * Log when extra-debug is activated
  */
 static function logIfExtradebug($file, $message)
 {
     $config = new PluginMonitoringConfig();
     $config->getFromDB(1);
     if ($config->fields['extradebug']) {
         if (is_array($message)) {
             $message = print_r($message, TRUE);
         }
         Toolbox::logInFile($file, $message);
     }
 }
 /**
  * @param $options   array
  **/
 function sendNotification($options = array())
 {
     $data = array();
     $data['itemtype'] = $options['_itemtype'];
     $data['items_id'] = $options['_items_id'];
     $data['notificationtemplates_id'] = $options['_notificationtemplates_id'];
     $data['entities_id'] = $options['_entities_id'];
     $data["headers"]['Auto-Submitted'] = "auto-generated";
     $data["headers"]['X-Auto-Response-Suppress'] = "OOF, DR, NDR, RN, NRN";
     $data['sender'] = $options['from'];
     $data['sendername'] = $options['fromname'];
     if ($options['replyto']) {
         $data['replyto'] = $options['replyto'];
         $data['replytoname'] = $options['replytoname'];
     }
     $data['name'] = $options['subject'];
     $data['body_text'] = $options['content_text'];
     if (!empty($options['content_html'])) {
         $data['body_html'] = $options['content_html'];
     }
     $data['recipient'] = $options['to'];
     $data['recipientname'] = $options['toname'];
     if (!empty($options['messageid'])) {
         $data['messageid'] = $options['messageid'];
     }
     if (isset($options['documents'])) {
         $data['documents'] = $options['documents'];
     }
     $mailqueue = new QueuedMail();
     if (!$mailqueue->add(Toolbox::addslashes_deep($data))) {
         $senderror = true;
         Session::addMessageAfterRedirect(__('Error inserting email to queue'), true);
     } else {
         //TRANS to be written in logs %1$s is the to email / %2$s is the subject of the mail
         Toolbox::logInFile("mail", sprintf(__('%1$s: %2$s'), sprintf(__('An email to %s was added to queue'), $options['to']), $options['subject'] . "\n"));
     }
     return true;
 }
Example #19
0
 /**
  * Send mai lin queue
  *
  * @param $ID        integer ID of the item
  *
  * @return true if send false if not
  **/
 function sendMailById($ID)
 {
     global $CFG_GLPI;
     if ($this->getFromDB($ID)) {
         $mmail = new GLPIMailer();
         $headers = importArrayFromDB($this->fields['headers']);
         if (is_array($headers) && count($headers)) {
             foreach ($headers as $key => $val) {
                 $mmail->AddCustomHeader("{$key}: {$val}");
             }
         }
         // Add custom header for mail grouping in reader
         $mmail->AddCustomHeader("In-Reply-To: GLPI-" . $this->fields["itemtype"] . "-" . $this->fields["items_id"]);
         $mmail->SetFrom($this->fields['sender'], $this->fields['sendername']);
         if ($this->fields['replyto']) {
             $mmail->AddReplyTo($this->fields['replyto'], $this->fields['replytoname']);
         }
         $mmail->Subject = $this->fields['name'];
         if (empty($this->fields['body_html'])) {
             $mmail->isHTML(false);
             $mmail->Body = $this->fields['body_text'];
         } else {
             $mmail->isHTML(true);
             $mmail->Body = '';
             $this->fields['body_html'] = Html::entity_decode_deep($this->fields['body_html']);
             $documents = importArrayFromDB($this->fields['documents']);
             $link_doc = array();
             if (is_array($documents) && count($documents)) {
                 $doc = new Document();
                 foreach ($documents as $docID) {
                     $doc->getFromDB($docID);
                     // Add embeded image if tag present in ticket content
                     if (preg_match_all('/' . Document::getImageTag($doc->fields['tag']) . '/', $this->fields['body_html'], $matches, PREG_PATTERN_ORDER)) {
                         $mmail->AddEmbeddedImage(GLPI_DOC_DIR . "/" . $doc->fields['filepath'], Document::getImageTag($doc->fields['tag']), $doc->fields['filename'], 'base64', $doc->fields['mime']);
                         // Else Add link to the document
                     } else {
                         $link_doc[] = "<a href='" . rtrim($CFG_GLPI["url_base"], '/') . "/front/document.send.php?docid=" . $doc->fields['id'] . "' >" . $doc->fields['name'] . "</a>";
                     }
                 }
             }
             $mmail->Body .= $this->fields['body_html'];
             if (count($link_doc)) {
                 $mmail->Body .= '<p style="border:1px solid #cccccc;padding:5px">' . '<b>' . _n('Associated item', 'Associated items', Session::getPluralNumber()) . ' : </b>' . implode(', ', $link_doc) . '</p>';
             }
             $mmail->AltBody = $this->fields['body_text'];
         }
         $mmail->AddAddress($this->fields['recipient'], $this->fields['recipientname']);
         if (!empty($this->fields['messageid'])) {
             $mmail->MessageID = "<" . $this->fields['messageid'] . ">";
         }
         $messageerror = __('Error in sending the email');
         if (!$mmail->Send()) {
             Session::addMessageAfterRedirect($messageerror . "<br>" . $mmail->ErrorInfo, true);
             $mmail->ClearAddresses();
             $this->update(array('id' => $this->fields['id'], 'sent_try' => $this->fields['sent_try'] + 1));
             return false;
         } else {
             //TRANS to be written in logs %1$s is the to email / %2$s is the subject of the mail
             Toolbox::logInFile("mail", sprintf(__('%1$s: %2$s'), sprintf(__('An email was sent to %s'), $this->fields['recipient']), $this->fields['name'] . "\n"));
             $mmail->ClearAddresses();
             $this->update(array('id' => $this->fields['id'], 'sent_time' => $_SESSION['glpi_currenttime']));
             $this->delete(array('id' => $this->fields['id']));
             return true;
         }
     } else {
         return false;
     }
 }
Example #20
0
 /**
  * Log usage of the api into glpi historical or log files (defined by api config)
  * It stores the ip and the username of the current session.
  *
  * @param $endpoint   string  function called by api to log (default '')
  */
 private function logEndpointUsage($endpoint = "")
 {
     $username = "";
     if (isset($_SESSION['glpiname'])) {
         $username = "******" . $_SESSION['glpiname'] . ")";
     }
     $apiclient = new APIClient();
     if ($apiclient->getFromDB($this->apiclients_id)) {
         $changes[0] = 0;
         $changes[1] = "";
         $changes[2] = "Enpoint '{$endpoint}' called by " . $this->iptxt . " {$username}";
         switch ($apiclient->fields['dolog_method']) {
             case APIClient::DOLOG_HISTORICAL:
                 Log::history($this->apiclients_id, 'APIClient', $changes, 0, Log::HISTORY_LOG_SIMPLE_MESSAGE);
                 break;
             case APIClient::DOLOG_LOGS:
                 Toolbox::logInFile("api", $changes[2] . "\n");
                 break;
         }
     }
 }
Example #21
0
 /**
  * Prepare a MySQL query
  *
  * @param $query Query to prepare
  *
  * @return a statement object or FALSE if an error occurred.
  **/
 function prepare($query)
 {
     $res = @$this->dbh->prepare($query);
     if (!$res) {
         // no translation for error logs
         $error = "  *** MySQL prepare error:\n  SQL: " . addslashes($query) . "\n  Error: " . $this->dbh->error . "\n";
         $error .= toolbox::backtrace(false, 'DBmysql->prepare()', array('Toolbox::backtrace()'));
         Toolbox::logInFile("sql-errors", $error);
         if (class_exists('GlpitestSQLError')) {
             // For unit test
             throw new GlpitestSQLError($error);
         }
         if ($_SESSION['glpi_use_mode'] == Session::DEBUG_MODE && $CFG_GLPI["debug_sql"]) {
             $DEBUG_SQL["errors"][$SQL_TOTAL_REQUEST] = $this->error();
         }
     }
     return $res;
 }
 /**
  * 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'] == Session::DEBUG_MODE && $CFG_GLPI["debug_sql"]) {
         $SQL_TOTAL_REQUEST++;
         $DEBUG_SQL["queries"][$SQL_TOTAL_REQUEST] = $query;
         $TIMER = new Timer();
         $TIMER->start();
     }
     $res = @$this->dbh->query($query);
     if (!$res) {
         // no translation for error logs
         $error = "  *** MySQL query error:\n  SQL: " . addslashes($query) . "\n  Error: " . $this->dbh->error . "\n";
         $error .= toolbox::backtrace(false, 'DBmysql->query()', array('Toolbox::backtrace()'));
         Toolbox::logInFile("sql-errors", $error);
         if ($_SESSION['glpi_use_mode'] == Session::DEBUG_MODE && $CFG_GLPI["debug_sql"]) {
             $DEBUG_SQL["errors"][$SQL_TOTAL_REQUEST] = $this->error();
         }
     }
     if ($_SESSION['glpi_use_mode'] == Session::DEBUG_MODE && $CFG_GLPI["debug_sql"]) {
         $TIME = $TIMER->getTime();
         $DEBUG_SQL["times"][$SQL_TOTAL_REQUEST] = $TIME;
     }
     return $res;
 }
Example #23
0
function cron_plugin_webservices()
{
    Toolbox::logInFile('webservices', "cron called\n");
    plugin_webservices_soap_create_wdsl();
    return 1;
}
Example #24
0
 /**
  * Launch the need cron tasks
  *
  * @param $mode   (internal/external, <0 to force)
  * @param $max    number of task to launch (default 1)
  * @param $name   of task to run (default '')
  *
  * @return the name of last task launched
  **/
 public static function launch($mode, $max = 1, $name = '')
 {
     global $CFG_GLPI;
     // No cron in maintenance mode
     if (isset($CFG_GLPI['maintenance_mode']) && $CFG_GLPI['maintenance_mode']) {
         return false;
     }
     $crontask = new self();
     $taskname = '';
     if (abs($mode) == self::MODE_EXTERNAL) {
         // If cron is launched in command line, and if memory is insufficient,
         // display a warning in the logs
         if (Toolbox::checkMemoryLimit() == 2) {
             Toolbox::logInFile('cron', __('A minimum of 64 Mio is commonly required for GLPI.') . "\n");
         }
         // If no task in CLI mode, call cron.php from command line is not really usefull ;)
         if (!countElementsInTable($crontask->getTable(), ['mode' => abs($mode)])) {
             Toolbox::logInFile('cron', __('No task with Run mode = CLI, fix your tasks configuration') . "\n");
         }
     }
     if (self::get_lock()) {
         for ($i = 1; $i <= $max; $i++) {
             $prefix = abs($mode) == self::MODE_EXTERNAL ? __('External') : __('Internal');
             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'];
                         //TRANS: %1$s is mode (external or internal), %2$s is an order number,
                         $msgcron = sprintf(__('%1$s #%2$s'), $prefix, $i);
                         $msgcron = sprintf(__('%1$s: %2$s'), $msgcron, sprintf(__('%1$s %2$s') . "\n", __('Launch'), $crontask->fields['name']));
                         Toolbox::logInFile('cron', $msgcron);
                         $retcode = call_user_func($fonction, $crontask);
                         $crontask->end($retcode);
                         // Unlock in DB + log end
                     } else {
                         $msgcron = sprintf(__('%1$s #%2$s'), $prefix, $i);
                         $msgcron = sprintf(__('%1$s: %2$s'), $msgcron, sprintf(__('%1$s %2$s') . "\n", __("Can't start"), $crontask->fields['name']));
                         Toolbox::logInFile('cron', $msgcron);
                     }
                 } else {
                     if (is_array($fonction)) {
                         $fonction = implode('::', $fonction);
                     }
                     Toolbox::logInFile('php-errors', sprintf(__('Undefined function %s (for cron)') . "\n", $fonction));
                     $msgcron = sprintf(__('%1$s #%2$s'), $prefix, $i);
                     $msgcron = sprintf(__('%1$s: %2$s'), $msgcron, sprintf(__('%1$s %2$s') . "\n", __("Can't start"), $crontask->fields['name']));
                     Toolbox::logInFile('cron', $msgcron . "\n" . sprintf(__('Undefined function %s (for cron)') . "\n", $fonction));
                 }
             } else {
                 if ($i == 1) {
                     $msgcron = sprintf(__('%1$s #%2$s'), $prefix, $i);
                     $msgcron = sprintf(__('%1$s: %2$s'), $msgcron, __('Nothing to launch'));
                     Toolbox::logInFile('cron', $msgcron . "\n");
                 }
             }
         }
         // end for
         $_SESSION["glpicronuserrunning"] = '';
         self::release_lock();
     } else {
         Toolbox::logInFile('cron', __("Can't get DB lock") . "\n");
     }
     return $taskname;
 }
Example #25
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'] == Session::DEBUG_MODE && $CFG_GLPI["debug_sql"]) {
         $SQL_TOTAL_REQUEST++;
         $DEBUG_SQL["queries"][$SQL_TOTAL_REQUEST] = $query;
         $TIMER = new Timer();
         $TIMER->start();
     }
     $res = @$this->dbh->query($query);
     if (!$res) {
         // no translation for error logs
         $error = "*** MySQL query error: \n***\nSQL: " . addslashes($query) . "\nError: " . $this->dbh->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";
         Toolbox::logInFile("sql-errors", $error . "\n");
         if ($_SESSION['glpi_use_mode'] == Session::DEBUG_MODE && $CFG_GLPI["debug_sql"]) {
             $DEBUG_SQL["errors"][$SQL_TOTAL_REQUEST] = $this->error();
         }
     }
     if ($_SESSION['glpi_use_mode'] == Session::DEBUG_MODE && $CFG_GLPI["debug_sql"]) {
         $TIME = $TIMER->getTime();
         $DEBUG_SQL["times"][$SQL_TOTAL_REQUEST] = $TIME;
     }
     return $res;
 }
Example #26
0
 /**
  * log message for this migration
  *
  * @since version 0.84
  *
  * @param $message
  * @param $warning
  **/
 function log($message, $warning)
 {
     if ($warning) {
         $log_file_name = 'warning_during_migration_to_' . $this->version;
     } else {
         $log_file_name = 'migration_to_' . $this->version;
     }
     // Do not log if more than 3 log error
     if ($this->log_errors < 3 && !Toolbox::logInFile($log_file_name, $message . ' @ ', true)) {
         $this->log_errors++;
     }
 }
function plugin_item_add_update_timezones_dbconnection(Config $parm)
{
    $slaveDB = DBConnection::getDBSlaveConf();
    if ($slaveDB) {
        $host = $slaveDB->dbhost;
        $user = $slaveDB->dbuser;
        $password = $slaveDB->dbpassword;
        $DBname = $slaveDB->dbdefault;
        unset($slaveDB);
        timezones_createSlaveConnectionFile($host, $user, $password, $DBname) or Toolbox::logInFile('php-errors', "timezones: Can't create config_db_slave.php\n");
    }
}