static function afterAdd(Group_Ticket $item)
 {
     global $DB;
     //Toolbox::logDebug(__METHOD__, $item);
     $config = PluginBehaviorsConfig::getInstance();
     if ($config->getField('add_notif')) {
         if ($item->getField('type') == CommonITILActor::ASSIGN) {
             $ticket = new Ticket();
             if ($ticket->getFromDB($item->getField('tickets_id'))) {
                 NotificationEvent::raiseEvent('plugin_behaviors_ticketnewgrp', $ticket);
             }
         }
     }
     // Check is the connected user is a tech
     if (!is_numeric(Session::getLoginUserID(false)) || !Session::haveRight('own_ticket', 1)) {
         return false;
         // No check
     }
     $config = PluginBehaviorsConfig::getInstance();
     if ($config->getField('single_tech_mode') != 0 && $item->input['type'] == CommonITILActor::ASSIGN) {
         $crit = array('tickets_id' => $item->input['tickets_id'], 'type' => CommonITILActor::ASSIGN);
         foreach ($DB->request('glpi_groups_tickets', $crit) as $data) {
             if ($data['id'] != $item->getID()) {
                 $gu = new Group_Ticket();
                 $gu->delete($data);
             }
         }
         if ($config->getField('single_tech_mode') == 2) {
             foreach ($DB->request('glpi_tickets_users', $crit) as $data) {
                 $gu = new Ticket_User();
                 $gu->delete($data);
             }
         }
     }
 }
 static function afterUpdate(TicketSatisfaction $ticketsatisfaction)
 {
     $config = PluginBehaviorsConfig::getInstance();
     $ticket = new Ticket();
     if ($config->getField('add_notif') && $ticket->getFromDB($ticketsatisfaction->getField('tickets_id')) && $ticketsatisfaction->input["date_answered"]) {
         NotificationEvent::raiseEvent('plugin_behaviors_replysurvey', $ticket);
     }
 }
 static function afterPurge(Document_Item $document_item)
 {
     $config = PluginBehaviorsConfig::getInstance();
     if ($config->getField('add_notif') && $document_item->fields['itemtype'] == 'Ticket' && isset($_POST['item'])) {
         // prevent not use in case of purge ticket
         $ticket = new Ticket();
         $ticket->getFromDB($document_item->fields['items_id']);
         NotificationEvent::raiseEvent('plugin_behaviors_document_itemdel', $ticket);
     }
 }
 function post_deleteFromDB()
 {
     global $CFG_GLPI;
     $donotif = $CFG_GLPI["use_mailing"];
     if (isset($this->input["_no_notif"]) && $this->input["_no_notif"]) {
         $donotif = false;
     }
     $t = new Ticket();
     if ($t->getFromDB($this->fields['tickets_id'])) {
         if ($t->fields["suppliers_id_assign"] == 0 && $t->countUsers(Ticket::ASSIGN) == 0 && $t->countGroups(Ticket::ASSIGN) == 0) {
             $t->update(array('id' => $this->fields['tickets_id'], 'status' => 'new'));
         } else {
             $t->updateDateMod($this->fields['tickets_id']);
             if ($donotif) {
                 NotificationEvent::raiseEvent("update", $t);
             }
         }
     }
     parent::post_deleteFromDB();
 }
Exemple #5
0
 /**
  * @param $output
  * @param $params
  **/
 function executeActions($output, $params)
 {
     if (count($this->actions)) {
         foreach ($this->actions as $action) {
             switch ($action->fields["action_type"]) {
                 case "send":
                     $ticket = new Ticket();
                     if ($ticket->getFromDB($output['id'])) {
                         NotificationEvent::raiseEvent('recall', $ticket);
                     }
                     break;
                 case "add_validation":
                     if (isset($output['_add_validation']) && !is_array($output['_add_validation'])) {
                         $output['_add_validation'] = array($output['_add_validation']);
                     }
                     switch ($action->fields['field']) {
                         case 'users_id_validate_requester_supervisor':
                             $output['_add_validation'][] = 'requester_supervisor';
                             break;
                         case 'users_id_validate_assign_supervisor':
                             $output['_add_validation'][] = 'assign_supervisor';
                             break;
                         case 'groups_id_validate':
                             $output['_add_validation']['group'][] = $action->fields["value"];
                             break;
                         case 'users_id_validate':
                             $output['_add_validation'][] = $action->fields["value"];
                             break;
                         case 'validation_percent':
                             $output[$action->fields["field"]] = $action->fields["value"];
                             break;
                         default:
                             $output['_add_validation'][] = $action->fields["value"];
                             break;
                     }
                     break;
                 case "assign":
                     $output[$action->fields["field"]] = $action->fields["value"];
                     // Special case of users_id_requester
                     if ($action->fields["field"] === '_users_id_requester') {
                         // Add groups of requester
                         if (!isset($output['_groups_id_of_requester'])) {
                             $output['_groups_id_of_requester'] = array();
                         }
                         foreach (Group_User::getUserGroups($action->fields["value"]) as $g) {
                             $output['_groups_id_of_requester'][$g['id']] = $g['id'];
                         }
                     }
                     break;
                 case "append":
                     $actions = $this->getActions();
                     $value = $action->fields["value"];
                     if (isset($actions[$action->fields["field"]]["appendtoarray"]) && isset($actions[$action->fields["field"]]["appendtoarrayfield"])) {
                         $value = $actions[$action->fields["field"]]["appendtoarray"];
                         $value[$actions[$action->fields["field"]]["appendtoarrayfield"]] = $action->fields["value"];
                     }
                     $output[$actions[$action->fields["field"]]["appendto"]][] = $value;
                     // Special case of users_id_requester
                     if ($action->fields["field"] === '_users_id_requester') {
                         // Add groups of requester
                         if (!isset($output['_groups_id_of_requester'])) {
                             $output['_groups_id_of_requester'] = array();
                         }
                         foreach (Group_User::getUserGroups($action->fields["value"]) as $g) {
                             $output['_groups_id_of_requester'][$g['id']] = $g['id'];
                         }
                     }
                     break;
                 case 'fromuser':
                     if ($action->fields['field'] == 'locations_id' && isset($output['users_locations'])) {
                         $output['locations_id'] = $output['users_locations'];
                     }
                     break;
                 case 'fromitem':
                     if ($action->fields['field'] == 'locations_id' && isset($output['items_locations'])) {
                         $output['locations_id'] = $output['items_locations'];
                     }
                     if ($action->fields['field'] == 'groups_id' && isset($output['items_groups'])) {
                         $output['groups_id'] = $output['items_groups'];
                     }
                     break;
                 case 'compute':
                     // Value could be not set (from test)
                     $urgency = isset($output['urgency']) ? $output['urgency'] : 3;
                     $impact = isset($output['impact']) ? $output['impact'] : 3;
                     // Apply priority_matrix from config
                     $output['priority'] = Ticket::computePriority($urgency, $impact);
                     break;
                 case "affectbyip":
                 case "affectbyfqdn":
                 case "affectbymac":
                     if (!isset($output["entities_id"])) {
                         $output["entities_id"] = $params["entities_id"];
                     }
                     if (isset($this->regex_results[0])) {
                         $regexvalue = RuleAction::getRegexResultById($action->fields["value"], $this->regex_results[0]);
                     } else {
                         $regexvalue = $action->fields["value"];
                     }
                     switch ($action->fields["action_type"]) {
                         case "affectbyip":
                             $result = IPAddress::getUniqueItemByIPAddress($regexvalue, $output["entities_id"]);
                             break;
                         case "affectbyfqdn":
                             $result = FQDNLabel::getUniqueItemByFQDN($regexvalue, $output["entities_id"]);
                             break;
                         case "affectbymac":
                             $result = NetworkPortInstantiation::getUniqueItemByMac($regexvalue, $output["entities_id"]);
                             break;
                         default:
                             $result = array();
                     }
                     if (!empty($result)) {
                         $output["items_id"][$result["itemtype"]][] = $result["id"];
                     }
                     break;
             }
         }
     }
     return $output;
 }
Exemple #6
0
 function post_addItem()
 {
     global $CFG_GLPI;
     parent::post_addItem();
     if (isset($this->input['_tickets_id'])) {
         $ticket = new Ticket();
         if ($ticket->getFromDB($this->input['_tickets_id'])) {
             $pt = new Change_Ticket();
             $pt->add(array('tickets_id' => $this->input['_tickets_id'], 'changes_id' => $this->fields['id']));
             if (!empty($ticket->fields['itemtype']) && $ticket->fields['items_id'] > 0) {
                 $it = new Change_Item();
                 $it->add(array('changes_id' => $this->fields['id'], 'itemtype' => $ticket->fields['itemtype'], 'items_id' => $ticket->fields['items_id']));
             }
         }
     }
     if (isset($this->input['_problems_id'])) {
         $problem = new Problem();
         if ($problem->getFromDB($this->input['_problems_id'])) {
             $cp = new Change_Problem();
             $cp->add(array('problems_id' => $this->input['_problems_id'], 'changes_id' => $this->fields['id']));
         }
     }
     // Processing Email
     if ($CFG_GLPI["use_mailing"]) {
         // Clean reload of the change
         $this->getFromDB($this->fields['id']);
         $type = "new";
         if (isset($this->fields["status"]) && in_array($this->input["status"], $this->getSolvedStatusArray())) {
             $type = "solved";
         }
         NotificationEvent::raiseEvent($type, $this);
     }
 }
 /**
  * Cron action on softwares : alert on expired licences
  *
  * @param $task to log, if NULL display (default NULL)
  *
  * @return 0 : nothing to do 1 : done with success
  **/
 static function cronSoftware($task = NULL)
 {
     global $DB, $CFG_GLPI;
     $cron_status = 1;
     if (!$CFG_GLPI['use_mailing']) {
         return 0;
     }
     $message = array();
     $items_notice = array();
     $items_end = array();
     foreach (Entity::getEntitiesToNotify('use_licenses_alert') as $entity => $value) {
         $before = Entity::getUsedConfig('send_licenses_alert_before_delay', $entity);
         // Check licenses
         $query = "SELECT `glpi_softwarelicenses`.*,\n                          `glpi_softwares`.`name` AS softname\n                   FROM `glpi_softwarelicenses`\n                   INNER JOIN `glpi_softwares`\n                        ON (`glpi_softwarelicenses`.`softwares_id` = `glpi_softwares`.`id`)\n                   LEFT JOIN `glpi_alerts`\n                        ON (`glpi_softwarelicenses`.`id` = `glpi_alerts`.`items_id`\n                            AND `glpi_alerts`.`itemtype` = 'SoftwareLicense'\n                            AND `glpi_alerts`.`type` = '" . Alert::END . "')\n                   WHERE `glpi_alerts`.`date` IS NULL\n                         AND `glpi_softwarelicenses`.`expire` IS NOT NULL\n                         AND DATEDIFF(`glpi_softwarelicenses`.`expire`,\n                                      CURDATE()) < '{$before}'\n                         AND `glpi_softwares`.`is_template` = '0'\n                         AND `glpi_softwares`.`is_deleted` = '0'\n                         AND `glpi_softwares`.`entities_id` = '" . $entity . "'";
         $message = "";
         $items = array();
         foreach ($DB->request($query) as $license) {
             $name = $license['softname'] . ' - ' . $license['name'] . ' - ' . $license['serial'];
             //TRANS: %1$s the license name, %2$s is the expiration date
             $message .= sprintf(__('License %1$s expired on %2$s'), Html::convDate($license["expire"]), $name) . "<br>\n";
             $items[$license['id']] = $license;
         }
         if (!empty($items)) {
             $alert = new Alert();
             $options['entities_id'] = $entity;
             $options['licenses'] = $items;
             if (NotificationEvent::raiseEvent('alert', new self(), $options)) {
                 $entityname = Dropdown::getDropdownName("glpi_entities", $entity);
                 if ($task) {
                     //TRANS: %1$s is the entity, %2$s is the message
                     $task->log(sprintf(__('%1$s: %2$s') . "\n", $entityname, $message));
                     $task->addVolume(1);
                 } else {
                     Session::addMessageAfterRedirect(sprintf(__('%1$s: %2$s'), $entityname, $message));
                 }
                 $input["type"] = Alert::END;
                 $input["itemtype"] = 'SoftwareLicense';
                 // add alerts
                 foreach ($items as $ID => $consumable) {
                     $input["items_id"] = $ID;
                     $alert->add($input);
                     unset($alert->fields['id']);
                 }
             } else {
                 $entityname = Dropdown::getDropdownName('glpi_entities', $entity);
                 //TRANS: %s is entity name
                 $msg = sprintf(__('%1$s: %2$s'), $entityname, __('Send licenses alert failed'));
                 if ($task) {
                     $task->log($msg);
                 } else {
                     Session::addMessageAfterRedirect($msg, false, ERROR);
                 }
             }
         }
     }
     return $cron_status;
 }
 function post_updateItem($history = 1)
 {
     global $CFG_GLPI;
     $job = new Ticket();
     $donotif = $CFG_GLPI["use_mailing"];
     if (isset($this->input['_disablenotif'])) {
         $donotif = false;
     }
     if ($job->getFromDB($this->fields["tickets_id"])) {
         if (count($this->updates) && $donotif) {
             $options = array('validation_id' => $this->fields["id"], 'validation_status' => $this->fields["status"]);
             NotificationEvent::raiseEvent('validation_answer', $job, $options);
         }
         // Set global validation to accepted to define one
         if ($job->fields['global_validation'] == 'waiting' || self::getNumberValidationForTicket($this->fields["tickets_id"]) == 1 || self::isAllValidationsHaveSameStatusForTicket($this->fields["tickets_id"])) {
             $input['id'] = $this->fields["tickets_id"];
             $input['global_validation'] = $this->fields["status"];
             $job->update($input);
         }
     }
     parent::post_updateItem($history);
 }
Exemple #9
0
 /**
  *  Cron process to check DB replicate state
  *
  * @param $task to log and get param
  **/
 static function cronCheckDBreplicate($task)
 {
     global $DB;
     //Lauch cron only is :
     // 1 the master database is avalaible
     // 2 the slave database is configurated
     if (!$DB->isSlave() && self::isDBSlaveActive()) {
         $DBslave = self::getDBSlaveConf();
         if (is_array($DBslave->dbhost)) {
             $hosts = $DBslave->dbhost;
         } else {
             $hosts = array($DBslave->dbhost);
         }
         foreach ($hosts as $num => $name) {
             $diff = self::getReplicateDelay($num);
             // Quite strange, but allow simple stat
             $task->addVolume($diff);
             if ($diff > 1000000000) {
                 // very large means slave is disconnect
                 $task->log(sprintf(__s("Mysql server: %s can't connect to the database"), $name));
             } else {
                 //TRANS: %1$s is the server name, %2$s is the time
                 $task->log(sprintf(__('Mysql server: %1$s, difference between master and slave: %2$s'), $name, Html::timestampToString($diff, true)));
             }
             if ($diff > $task->fields['param'] * 60) {
                 //Raise event if replicate is not synchronized
                 $options = array('diff' => $diff, 'name' => $name, 'entities_id' => 0);
                 // entity to avoid warning in getReplyTo
                 NotificationEvent::raiseEvent('desynchronization', new self(), $options);
             }
         }
         return 1;
     }
     return 0;
 }
Exemple #10
0
 static function cronAdditionalalertsNewOcs($task = NULL)
 {
     global $DB, $CFG_GLPI;
     if (!$CFG_GLPI["use_mailing"]) {
         return 0;
     }
     $CronTask = new CronTask();
     if ($CronTask->getFromDBbyName("PluginAdditionalalertsOcsAlert", "AdditionalalertsNewOcs")) {
         if ($CronTask->fields["state"] == CronTask::STATE_DISABLE) {
             return 0;
         }
     } else {
         return 0;
     }
     $message = array();
     $cron_status = 0;
     foreach (self::getEntitiesToNotify('use_newocs_alert') as $entity => $repeat) {
         foreach ($DB->request("glpi_plugin_ocsinventoryng_ocsservers", "`is_active` = 1") as $config) {
             $query_newocsmachine = self::queryNew($config, $entity);
             $newocsmachine_infos = array();
             $newocsmachine_messages = array();
             $type = Alert::END;
             $newocsmachine_infos[$type] = array();
             foreach ($DB->request($query_newocsmachine) as $data) {
                 $entity = $data['entities_id'];
                 $message = $data["name"];
                 $newocsmachine_infos[$type][$entity][] = $data;
                 if (!isset($newocsmachines_infos[$type][$entity])) {
                     $newocsmachine_messages[$type][$entity] = __('New imported computers from OCS-NG', 'additionalalerts') . "<br />";
                 }
                 $newocsmachine_messages[$type][$entity] .= $message;
             }
             $delay_ocs = 0;
             foreach ($newocsmachine_infos[$type] as $entity => $newocsmachines) {
                 Plugin::loadLang('additionalalerts');
                 if (NotificationEvent::raiseEvent("newocs", new PluginAdditionalalertsOcsAlert(), array('entities_id' => $entity, 'ocsmachines' => $newocsmachines, 'delay_ocs' => $delay_ocs))) {
                     $message = $newocsmachine_messages[$type][$entity];
                     $cron_status = 1;
                     if ($task) {
                         $task->log(Dropdown::getDropdownName("glpi_entities", $entity) . ":  {$message}\n");
                         $task->addVolume(1);
                     } else {
                         Session::addMessageAfterRedirect(Dropdown::getDropdownName("glpi_entities", $entity) . ":  {$message}");
                     }
                 } else {
                     if ($task) {
                         $task->log(Dropdown::getDropdownName("glpi_entities", $entity) . ":  Send newocsmachines alert failed\n");
                     } else {
                         Session::addMessageAfterRedirect(Dropdown::getDropdownName("glpi_entities", $entity) . ":  Send newocsmachines alert failed", false, ERROR);
                     }
                 }
             }
         }
     }
     return $cron_status;
 }
Exemple #11
0
 function post_addItem()
 {
     global $CFG_GLPI;
     parent::post_addItem();
     if (isset($this->input['_tickets_id'])) {
         $ticket = new Ticket();
         if ($ticket->getFromDB($this->input['_tickets_id'])) {
             $pt = new Problem_Ticket();
             $pt->add(array('tickets_id' => $this->input['_tickets_id'], 'problems_id' => $this->fields['id'], '_no_notif' => true));
             if (!empty($ticket->fields['itemtype']) && $ticket->fields['items_id'] > 0) {
                 $it = new Item_Problem();
                 $it->add(array('problems_id' => $this->fields['id'], 'itemtype' => $ticket->fields['itemtype'], 'items_id' => $ticket->fields['items_id'], '_no_notif' => true));
             }
         }
     }
     // Processing Email
     if ($CFG_GLPI["use_mailing"]) {
         // Clean reload of the problem
         $this->getFromDB($this->fields['id']);
         $type = "new";
         if (isset($this->fields["status"]) && $this->fields["status"] == self::SOLVED) {
             $type = "solved";
         }
         NotificationEvent::raiseEvent($type, $this);
     }
 }
Exemple #12
0
 function post_addItem()
 {
     global $CFG_GLPI;
     if ($CFG_GLPI["use_mailing"]) {
         NotificationEvent::raiseEvent("new", $this);
     }
     parent::post_addItem();
 }
 function post_addItem()
 {
     global $CFG_GLPI;
     if (isset($this->input['_planningrecall'])) {
         $this->input['_planningrecall']['items_id'] = $this->fields['id'];
         PlanningRecall::manageDatas($this->input['_planningrecall']);
     }
     $donotif = $CFG_GLPI["use_mailing"];
     if (isset($this->fields["begin"]) && !empty($this->fields["begin"])) {
         Planning::checkAlreadyPlanned($this->fields["users_id_tech"], $this->fields["begin"], $this->fields["end"], array($this->getType() => array($this->fields["id"])));
         $calendars_id = Entity::getUsedConfig('calendars_id', $this->input["_job"]->fields['entities_id']);
         $calendar = new Calendar();
         // Using calendar
         if ($calendars_id > 0 && $calendar->getFromDB($calendars_id)) {
             if (!$calendar->isAWorkingHour(strtotime($this->fields["begin"]))) {
                 Session::addMessageAfterRedirect(__('Start of the selected timeframe is not a working hour.'), false, ERROR);
             }
             if (!$calendar->isAWorkingHour(strtotime($this->fields["end"]))) {
                 Session::addMessageAfterRedirect(__('End of the selected timeframe is not a working hour.'), false, ERROR);
             }
         }
     }
     $this->input["_job"]->updateDateMod($this->input[$this->input["_job"]->getForeignKeyField()]);
     if (isset($this->input["actiontime"]) && $this->input["actiontime"] > 0) {
         $this->input["_job"]->updateActionTime($this->input[$this->input["_job"]->getForeignKeyField()]);
     }
     //change status only if input change
     if (isset($this->input['_status']) && $this->input['_status'] != $this->input['_job']->fields['status']) {
         $update['status'] = $this->input['_status'];
         $update['id'] = $this->input['_job']->fields['id'];
         $update['_disablenotif'] = true;
         $this->input['_job']->update($update);
     }
     if (!empty($this->fields['begin']) && $this->input["_job"]->isStatusExists(CommonITILObject::PLANNED) && ($this->input["_job"]->fields["status"] == CommonITILObject::INCOMING || $this->input["_job"]->fields["status"] == CommonITILObject::ASSIGNED)) {
         $input2['id'] = $this->input["_job"]->getID();
         $input2['status'] = CommonITILObject::PLANNED;
         $input2['_disablenotif'] = true;
         $this->input["_job"]->update($input2);
     }
     if ($donotif) {
         $options = array('task_id' => $this->fields["id"], 'is_private' => $this->isPrivate());
         NotificationEvent::raiseEvent('add_task', $this->input["_job"], $options);
     }
     // Add log entry in the ITIL object
     $changes[0] = 0;
     $changes[1] = '';
     $changes[2] = $this->fields['id'];
     Log::history($this->getField($this->input["_job"]->getForeignKeyField()), $this->input["_job"]->getTYpe(), $changes, $this->getType(), Log::HISTORY_ADD_SUBITEM);
 }
Exemple #14
0
 function post_addItem()
 {
     global $CFG_GLPI;
     parent::post_addItem();
     if (isset($this->input['_tickets_id'])) {
         $ticket = new Ticket();
         if ($ticket->getFromDB($this->input['_tickets_id'])) {
             $pt = new Change_Ticket();
             $pt->add(array('tickets_id' => $this->input['_tickets_id'], 'changes_id' => $this->fields['id']));
             if (!empty($ticket->fields['itemtype']) && $ticket->fields['items_id'] > 0) {
                 $it = new Change_Item();
                 $it->add(array('changes_id' => $this->fields['id'], 'itemtype' => $ticket->fields['itemtype'], 'items_id' => $ticket->fields['items_id']));
             }
         }
     }
     if (isset($this->input['_problems_id'])) {
         $problem = new Problem();
         if ($problem->getFromDB($this->input['_problems_id'])) {
             $cp = new Change_Problem();
             $cp->add(array('problems_id' => $this->input['_problems_id'], 'changes_id' => $this->fields['id']));
             /// TODO add linked tickets and linked hardware (to problem and tickets)
             /// create standard function
         }
     }
     // Processing Email
     if ($CFG_GLPI["use_mailing"]) {
         // Clean reload of the change
         $this->getFromDB($this->fields['id']);
         $type = "new";
         if (isset($this->fields["status"]) && $this->fields["status"] == self::SOLVED) {
             $type = "solved";
         }
         NotificationEvent::raiseEvent($type, $this);
     }
 }
 /**
  * Cron action on consumables : alert if a stock is behind the threshold
  *
  * @param $task   to log, if NULL display (default NULL)
  *
  * @return 0 : nothing to do 1 : done with success
  **/
 static function cronConsumable($task = NULL)
 {
     global $DB, $CFG_GLPI;
     $cron_status = 1;
     if ($CFG_GLPI["use_mailing"]) {
         $message = array();
         $items = array();
         $alert = new Alert();
         foreach (Entity::getEntitiesToNotify('consumables_alert_repeat') as $entity => $repeat) {
             $query_alert = "SELECT `glpi_consumableitems`.`id` AS consID,\n                                   `glpi_consumableitems`.`entities_id` AS entity,\n                                   `glpi_consumableitems`.`ref` AS ref,\n                                   `glpi_consumableitems`.`name` AS name,\n                                   `glpi_consumableitems`.`alarm_threshold` AS threshold,\n                                   `glpi_alerts`.`id` AS alertID,\n                                   `glpi_alerts`.`date`\n                            FROM `glpi_consumableitems`\n                            LEFT JOIN `glpi_alerts`\n                                 ON (`glpi_consumableitems`.`id` = `glpi_alerts`.`items_id`\n                                     AND `glpi_alerts`.`itemtype`='ConsumableItem')\n                            WHERE `glpi_consumableitems`.`is_deleted` = '0'\n                                  AND `glpi_consumableitems`.`alarm_threshold` >= '0'\n                                  AND `glpi_consumableitems`.`entities_id` = '" . $entity . "'\n                                  AND (`glpi_alerts`.`date` IS NULL\n                                       OR (`glpi_alerts`.date+{$repeat}) < CURRENT_TIMESTAMP());";
             $message = "";
             $items = array();
             foreach ($DB->request($query_alert) as $consumable) {
                 if (($unused = Consumable::getUnusedNumber($consumable["consID"])) <= $consumable["threshold"]) {
                     // define message alert
                     //TRANS: %1$s is the consumable name, %2$s its reference, %3$d the remaining number
                     $message .= sprintf(__('Threshold of alarm reached for the type of consumable: %1$s - Reference %2$s - Remaining %3$d'), $consumable['name'], $consumable['ref'], $unused);
                     $message .= '<br>';
                     $items[$consumable["consID"]] = $consumable;
                     // if alert exists -> delete
                     if (!empty($consumable["alertID"])) {
                         $alert->delete(array("id" => $consumable["alertID"]));
                     }
                 }
             }
             if (!empty($items)) {
                 $options['entities_id'] = $entity;
                 $options['items'] = $items;
                 if (NotificationEvent::raiseEvent('alert', new ConsumableItem(), $options)) {
                     if ($task) {
                         $task->log(Dropdown::getDropdownName("glpi_entities", $entity) . " :  {$message}\n");
                         $task->addVolume(1);
                     } else {
                         Session::addMessageAfterRedirect(Dropdown::getDropdownName("glpi_entities", $entity) . " :  {$message}");
                     }
                     $input["type"] = Alert::THRESHOLD;
                     $input["itemtype"] = 'ConsumableItem';
                     // add alerts
                     foreach ($items as $ID => $consumable) {
                         $input["items_id"] = $ID;
                         $alert->add($input);
                         unset($alert->fields['id']);
                     }
                 } else {
                     $entityname = Dropdown::getDropdownName('glpi_entities', $entity);
                     //TRANS: %s is entity name
                     $msg = sprintf(__('%s: send consumable alert failed'), $entityname);
                     if ($task) {
                         $task->log($msg);
                     } else {
                         Session::addMessageAfterRedirect($msg, false, ERROR);
                     }
                 }
             }
         }
     }
     return $cron_status;
 }
Exemple #16
0
 /**
  * Check zombie crontask
  *
  * @param $task for log
  **/
 static function cronWatcher($task)
 {
     global $CFG_GLPI, $DB;
     $cron_status = 0;
     // Crontasks running for more than 1 hour or 2 frequency
     $query = "SELECT *\n                FROM `glpi_crontasks`\n                WHERE `state` = '" . self::STATE_RUNNING . "'\n                      AND ((unix_timestamp(`lastrun`) + 2 * `frequency` < unix_timestamp(now()))\n                           OR (unix_timestamp(`lastrun`) + 2*" . HOUR_TIMESTAMP . " < unix_timestamp(now())))";
     $crontasks = array();
     foreach ($DB->request($query) as $data) {
         $crontasks[$data['id']] = $data;
     }
     if (count($crontasks)) {
         $task = new self();
         $task->getFromDBByQuery("WHERE `itemtype` = 'Crontask' AND `name` = 'watcher'");
         if (NotificationEvent::raiseEvent("alert", $task, array('items' => $crontasks))) {
             $cron_status = 1;
             $task->addVolume(1);
         }
         QueuedMail::forceSendFor($task->getType(), $task->fields['id']);
     }
     return 1;
 }
Exemple #17
0
 /**
  * Cron for alert old tickets which are not solved
  *
  * @param $task : crontask object
  *
  * @return integer (0 : nothing done - 1 : done)
  **/
 static function cronAlertNotClosed($task)
 {
     global $DB, $CFG_GLPI;
     if (!$CFG_GLPI["use_mailing"]) {
         return 0;
     }
     // Recherche des entités
     $tot = 0;
     foreach (Entity::getEntitiesToNotify('notclosed_delay') as $entity => $value) {
         $query = "SELECT `glpi_tickets`.*\n                   FROM `glpi_tickets`\n                   WHERE `glpi_tickets`.`entities_id` = '" . $entity . "'\n                         AND `glpi_tickets`.`is_deleted` = 0\n                         AND `glpi_tickets`.`status` IN ('" . self::INCOMING . "',\n                                                         '" . self::ASSIGNED . "',\n                                                         '" . self::PLANNED . "',\n                                                         '" . self::WAITING . "')\n                         AND `glpi_tickets`.`closedate` IS NULL\n                         AND ADDDATE(`glpi_tickets`.`date`, INTERVAL " . $value . " DAY) < NOW()";
         $tickets = array();
         foreach ($DB->request($query) as $tick) {
             $tickets[] = $tick;
         }
         if (!empty($tickets)) {
             if (NotificationEvent::raiseEvent('alertnotclosed', new self(), array('items' => $tickets, 'entities_id' => $entity))) {
                 $tot += count($tickets);
                 $task->addVolume(count($tickets));
                 $task->log(sprintf(__('%1$s: %2$s'), Dropdown::getDropdownName('glpi_entities', $entity), count($tickets)));
             }
         }
     }
     return $tot > 0;
 }
Exemple #18
0
 /**
  * Cron action on contracts : alert depending of the config : on notice and expire
  *
  * @param $task for log, if NULL display (default NULL)
  **/
 static function cronContract($task = NULL)
 {
     global $DB, $CFG_GLPI;
     if (!$CFG_GLPI["use_mailing"]) {
         return 0;
     }
     $message = array();
     $items_notice = array();
     $items_end = array();
     $cron_status = 0;
     $contract_infos[Alert::END] = array();
     $contract_infos[Alert::NOTICE] = array();
     $contract_messages = array();
     foreach (Entity::getEntitiesToNotify('use_contracts_alert') as $entity => $value) {
         $before = Entity::getUsedConfig('send_contracts_alert_before_delay', $entity);
         $query_notice = "SELECT `glpi_contracts`.*\n                          FROM `glpi_contracts`\n                          LEFT JOIN `glpi_alerts`\n                              ON (`glpi_contracts`.`id` = `glpi_alerts`.`items_id`\n                                  AND `glpi_alerts`.`itemtype` = 'Contract'\n                                  AND `glpi_alerts`.`type`='" . Alert::NOTICE . "')\n                          WHERE (`glpi_contracts`.`alert` & " . pow(2, Alert::NOTICE) . ") >'0'\n                                AND `glpi_contracts`.`is_deleted` = '0'\n                                AND `glpi_contracts`.`begin_date` IS NOT NULL\n                                AND `glpi_contracts`.`duration` <> '0'\n                                AND `glpi_contracts`.`notice` <> '0'\n                                AND DATEDIFF(ADDDATE(`glpi_contracts`.`begin_date`,\n                                                     INTERVAL `glpi_contracts`.`duration` MONTH),\n                                             CURDATE()) > '0'\n                                AND DATEDIFF(ADDDATE(`glpi_contracts`.`begin_date`,\n                                                     INTERVAL (`glpi_contracts`.`duration`\n                                                                -`glpi_contracts`.`notice`) MONTH),\n                                             CURDATE()) < '{$before}'\n                                AND `glpi_alerts`.`date` IS NULL\n                                AND `glpi_contracts`.`entities_id` = '" . $entity . "'";
         $query_end = "SELECT `glpi_contracts`.*\n                       FROM `glpi_contracts`\n                       LEFT JOIN `glpi_alerts`\n                           ON (`glpi_contracts`.`id` = `glpi_alerts`.`items_id`\n                               AND `glpi_alerts`.`itemtype` = 'Contract'\n                               AND `glpi_alerts`.`type`='" . Alert::END . "')\n                       WHERE (`glpi_contracts`.`alert` & " . pow(2, Alert::END) . ") > '0'\n                             AND `glpi_contracts`.`is_deleted` = '0'\n                             AND `glpi_contracts`.`begin_date` IS NOT NULL\n                             AND `glpi_contracts`.`duration` <> '0'\n                             AND DATEDIFF(ADDDATE(`glpi_contracts`.`begin_date`,\n                                                  INTERVAL (`glpi_contracts`.`duration`) MONTH),\n                                          CURDATE()) < '{$before}'\n                             AND `glpi_alerts`.`date` IS NULL\n                             AND `glpi_contracts`.`entities_id` = '" . $entity . "'";
         $querys = array('notice' => $query_notice, 'end' => $query_end);
         foreach ($querys as $type => $query) {
             foreach ($DB->request($query) as $data) {
                 $entity = $data['entities_id'];
                 $message = sprintf(__('%1$s: %2$s') . "<br>\n", $data["name"], Infocom::getWarrantyExpir($data["begin_date"], $data["duration"], $data["notice"]));
                 $contract_infos[$type][$entity][$data['id']] = $data;
                 if (!isset($contract_messages[$type][$entity])) {
                     switch ($type) {
                         case 'notice':
                             $contract_messages[$type][$entity] = __('Contract entered in notice time') . "<br>";
                             break;
                         case 'end':
                             $contract_messages[$type][$entity] = __('Contract ended') . "<br>";
                             break;
                     }
                 }
                 $contract_messages[$type][$entity] .= $message;
             }
         }
         // Get contrats with periodicity alerts
         $query_periodicity = "SELECT `glpi_contracts`.*\n                               FROM `glpi_contracts`\n                               WHERE `glpi_contracts`.`alert` & " . pow(2, Alert::PERIODICITY) . " > '0'\n                                     AND `glpi_contracts`.`entities_id` = '" . $entity . "' ";
         // Foreach ones :
         foreach ($DB->request($query_periodicity) as $data) {
             $entity = $data['entities_id'];
             // Compute end date + 12 month : do not send alerts after
             $end_alert = date('Y-m-d', strtotime($data['begin_date'] . " +" . ($data['duration'] + 12) . " month"));
             if (!empty($data['begin_date']) && $data['periodicity'] && $end_alert > date('Y-m-d')) {
                 $todo = array('periodicity' => Alert::PERIODICITY);
                 if ($data['alert'] & pow(2, Alert::NOTICE)) {
                     $todo['periodicitynotice'] = Alert::NOTICE;
                 }
                 // Get previous alerts
                 foreach ($todo as $type => $event) {
                     $previous_alerts[$type] = Alert::getAlertDate(__CLASS__, $data['id'], $event);
                 }
                 // compute next alert date based on already send alerts (or not)
                 foreach ($todo as $type => $event) {
                     $next_alerts[$type] = date('Y-m-d', strtotime($data['begin_date'] . " -" . $before . " day"));
                     if ($type == Alert::NOTICE) {
                         $next_alerts[$type] = date('Y-m-d', strtotime($next_alerts[$type] . " -" . $data['notice'] . " month"));
                     }
                     $today_limit = date('Y-m-d', strtotime(date('Y-m-d') . " -" . $data['periodicity'] . " month"));
                     // Init previous by begin date if not set
                     if (empty($previous_alerts[$type])) {
                         $previous_alerts[$type] = $today_limit;
                     }
                     while ($next_alerts[$type] < $previous_alerts[$type] && $next_alerts[$type] < $end_alert) {
                         $next_alerts[$type] = date('Y-m-d', strtotime($next_alerts[$type] . " +" . $data['periodicity'] . " month"));
                     }
                     // If this date is passed : clean alerts and send again
                     if ($next_alerts[$type] <= date('Y-m-d')) {
                         $alert = new Alert();
                         $alert->clear(__CLASS__, $data['id'], $event);
                         $real_alert_date = date('Y-m-d', strtotime($next_alerts[$type] . " +" . $before . " day"));
                         $message = sprintf(__('%1$s: %2$s') . "<br>\n", $data["name"], Html::convDate($real_alert_date));
                         $data['alert_date'] = $real_alert_date;
                         $data['items'] = Contract_Item::getItemsForContract($data['id'], $entity);
                         $contract_infos[$type][$entity][$data['id']] = $data;
                         switch ($type) {
                             case 'periodicitynotice':
                                 $contract_messages[$type][$entity] = __('Contract entered in notice time for period') . "<br>";
                                 break;
                             case 'periodicity':
                                 $contract_messages[$type][$entity] = __('Contract period ended') . "<br>";
                                 break;
                         }
                         $contract_messages[$type][$entity] .= $message;
                     }
                 }
             }
         }
     }
     foreach (array('notice' => Alert::NOTICE, 'end' => Alert::END, 'periodicity' => Alert::PERIODICITY, 'periodicitynotice' => Alert::NOTICE) as $event => $type) {
         if (isset($contract_infos[$event]) && count($contract_infos[$event])) {
             foreach ($contract_infos[$event] as $entity => $contracts) {
                 if (NotificationEvent::raiseEvent($event, new self(), array('entities_id' => $entity, 'items' => $contracts))) {
                     $message = $contract_messages[$event][$entity];
                     $cron_status = 1;
                     $entityname = Dropdown::getDropdownName("glpi_entities", $entity);
                     if ($task) {
                         $task->log(sprintf(__('%1$s: %2$s') . "\n", $entityname, $message));
                         $task->addVolume(1);
                     } else {
                         Session::addMessageAfterRedirect(sprintf(__('%1$s: %2$s'), $entityname, $message));
                     }
                     $alert = new Alert();
                     $input["itemtype"] = __CLASS__;
                     $input["type"] = $type;
                     foreach ($contracts as $id => $contract) {
                         $input["items_id"] = $id;
                         $alert->add($input);
                         unset($alert->fields['id']);
                     }
                 } else {
                     $entityname = Dropdown::getDropdownName('glpi_entities', $entity);
                     //TRANS: %1$s is entity name, %2$s is the message
                     $msg = sprintf(__('%1$s: %2$s'), $entityname, __('send contract alert failed'));
                     if ($task) {
                         $task->log($msg);
                     } else {
                         Session::addMessageAfterRedirect($msg, false, ERROR);
                     }
                 }
             }
         }
     }
     return $cron_status;
 }
 /**
  * Send Alarms on mailgate errors
  *
  * @since version 0.85
  *
  * @param $task for log
  **/
 static function cronMailgateError($task)
 {
     global $DB, $CFG_GLPI;
     if (!$CFG_GLPI["use_mailing"]) {
         return 0;
     }
     $cron_status = 0;
     $query = "SELECT `glpi_mailcollectors`.*\n                FROM `glpi_mailcollectors`\n                WHERE `glpi_mailcollectors`.`errors`  > 0\n                      AND `glpi_mailcollectors`.`is_active`";
     $items = array();
     foreach ($DB->request($query) as $data) {
         $items[$data['id']] = $data;
     }
     if (count($items)) {
         if (NotificationEvent::raiseEvent('error', new self(), array('items' => $items))) {
             $cron_status = 1;
             if ($task) {
                 $task->setVolume(count($items));
             }
         }
     }
     return $cron_status;
 }
 /**
  * @return int
  */
 static function sendAlert()
 {
     global $DB, $CFG_GLPI;
     if (!$CFG_GLPI["use_mailing"]) {
         return 0;
     }
     $items_infos = array();
     $query = "SELECT `glpi_plugin_ocsinventoryng_notimportedcomputers`.*\n               FROM `glpi_plugin_ocsinventoryng_notimportedcomputers`\n               LEFT JOIN `glpi_alerts`\n                  ON (`glpi_plugin_ocsinventoryng_notimportedcomputers`.`id` = `glpi_alerts`.`items_id`\n                      AND `glpi_alerts`.`itemtype` = 'PluginOcsinventoryngNotimportedcomputer'\n                      AND `glpi_alerts`.`type` = '" . Alert::END . "')\n               WHERE `glpi_alerts`.`date` IS NULL";
     foreach ($DB->request($query) as $notimported) {
         $items_infos[$notimported['entities_id']][$notimported['id']] = $notimported;
     }
     foreach ($items_infos as $entity => $items) {
         if (NotificationEvent::raiseEvent('not_imported', new PluginOcsinventoryngNotimportedcomputer(), array('entities_id' => $entity, 'notimported' => $items))) {
             $alert = new Alert();
             $input["itemtype"] = 'PluginOcsinventoryngNotimportedcomputer';
             $input["type"] = Alert::END;
             foreach ($items as $id => $item) {
                 $input["items_id"] = $id;
                 $alert->add($input);
                 unset($alert->fields['id']);
             }
         } else {
             Toolbox::logDebug(__('%1$s: %2$s') . "\n", Dropdown::getDropdownName("glpi_entities", $entity), __('Send OCSNG not imported computers alert failed', 'ocsinventoryng'));
         }
     }
 }
Exemple #21
0
 /**
  * Cron action on tasks : ExpiredTasks
  *
  * @param $task for log, if NULL display
  *
  **/
 static function cronResourcesTask($task = NULL)
 {
     global $DB, $CFG_GLPI;
     if (!$CFG_GLPI["use_mailing"]) {
         return 0;
     }
     $message = array();
     $cron_status = 0;
     $resourcetask = new self();
     $query_expired = $resourcetask->queryAlert();
     $querys = array(Alert::END => $query_expired);
     $task_infos = array();
     $task_messages = array();
     foreach ($querys as $type => $query) {
         $task_infos[$type] = array();
         foreach ($DB->request($query) as $data) {
             $entity = $data['entities_id'];
             $message = $data["name"] . ": " . Html::convDate($data["date_end"]) . "<br>\n";
             $task_infos[$type][$entity][] = $data;
             if (!isset($tasks_infos[$type][$entity])) {
                 $task_messages[$type][$entity] = __('Not finished tasks', 'resources') . "<br />";
             }
             $task_messages[$type][$entity] .= $message;
         }
     }
     foreach ($querys as $type => $query) {
         foreach ($task_infos[$type] as $entity => $tasks) {
             Plugin::loadLang('resources');
             if (NotificationEvent::raiseEvent("AlertExpiredTasks", new PluginResourcesResource(), array('entities_id' => $entity, 'tasks' => $tasks))) {
                 $message = $task_messages[$type][$entity];
                 $cron_status = 1;
                 if ($task) {
                     $task->log(Dropdown::getDropdownName("glpi_entities", $entity) . ":  {$message}\n");
                     $task->addVolume(1);
                 } else {
                     Session::addMessageAfterRedirect(Dropdown::getDropdownName("glpi_entities", $entity) . ":  {$message}");
                 }
             } else {
                 if ($task) {
                     $task->log(Dropdown::getDropdownName("glpi_entities", $entity) . ":  Send tasks alert failed\n");
                 } else {
                     Session::addMessageAfterRedirect(Dropdown::getDropdownName("glpi_entities", $entity) . ":  Send tasks alert failed", false, ERROR);
                 }
             }
         }
     }
     return $cron_status;
 }
Exemple #22
0
 public static function cronComputeLateOrders($task)
 {
     global $CFG_GLPI, $DB;
     $nblate = 0;
     $table = getTableForItemType(__CLASS__);
     foreach (getAllDatasFromTable($table, "`is_template`='0'") as $values) {
         $order = new self();
         $order->fields = $values;
         if (!$order->fields['is_late'] && $order->shouldBeAlreadyDelivered(true)) {
             $order->setIsLate();
             $nblate++;
         }
     }
     $task->addVolume($nblate);
     $cron_status = 1;
     if ($CFG_GLPI["use_mailing"]) {
         $message = __("Order is late", "order");
         $alert = new Alert();
         $config = PluginOrderConfig::getConfig();
         $entities[] = 0;
         foreach ($DB->request("SELECT `id` FROM `glpi_entities` ORDER BY `id` ASC") as $entity) {
             $entities[] = $entity['id'];
         }
         foreach ($entities as $entity) {
             $query_alert = "SELECT `{$table}`.`id` AS id,\n                                   `{$table}`.`name` AS name,\n                                   `{$table}`.`num_order` AS num_order,\n                                   `{$table}`.`order_date` AS order_date,\n                                   `{$table}`.`duedate` AS duedate,\n                                   `{$table}`.`deliverydate` AS deliverydate,\n                                   `{$table}`.`comment` AS comment,\n                                   `{$table}`.`plugin_order_orderstates_id` AS plugin_order_orderstates_id,\n                                   `glpi_alerts`.`id` AS alertID,\n                                   `glpi_alerts`.`date`\n                            FROM `{$table}`\n                            LEFT JOIN `glpi_alerts`\n                                  ON (`{$table}`.`id` = `glpi_alerts`.`items_id`\n                                      AND `glpi_alerts`.`itemtype` = '" . __CLASS__ . "')\n                            WHERE `{$table}`.`entities_id` = '" . $entity . "'\n                                   AND (`glpi_alerts`.`date` IS NULL) AND `{$table}`.`is_late`='1'\n                                      AND `plugin_order_orderstates_id`!='" . $config->getDeliveredState() . "';";
             $orders = array();
             foreach ($DB->request($query_alert) as $order) {
                 $orders[$order['id']] = $order;
             }
             if (!empty($orders)) {
                 $options['entities_id'] = $entity;
                 $options['orders'] = $orders;
                 if (NotificationEvent::raiseEvent('duedate', new PluginOrderOrder(), $options)) {
                     if ($task) {
                         $task->log(Dropdown::getDropdownName("glpi_entities", $entity) . "&nbsp;:  {$message}\n");
                         $task->addVolume(1);
                     } else {
                         Session::addMessageAfterRedirect(Dropdown::getDropdownName("glpi_entities", $entity) . "&nbsp;:  {$message}");
                     }
                     $input["type"] = Alert::THRESHOLD;
                     $input["itemtype"] = 'PluginOrderOrder';
                     // add alerts
                     foreach ($orders as $ID => $tmp) {
                         $input["items_id"] = $ID;
                         $alert->add($input);
                         unset($alert->fields['id']);
                     }
                 } else {
                     if ($task) {
                         $task->log(Dropdown::getDropdownName("glpi_entities", $entity) . "&nbsp;: Send order alert failed\n");
                     } else {
                         Session::addMessageAfterRedirect(Dropdown::getDropdownName("glpi_entities", $entity) . "&nbsp;: Send order alert failed", false, ERROR);
                     }
                 }
             }
         }
     }
     return true;
 }
 function post_addItem()
 {
     global $CFG_GLPI;
     $donotif = $CFG_GLPI["use_mailing"];
     //       if (isset($this->input["_no_notif"]) && $this->input["_no_notif"]) {
     //          $donotif = false;
     //       }
     $this->input["_job"]->updateDateMod($this->input["tickets_id"], false, $this->input["users_id"]);
     if (isset($this->input["_close"]) && $this->input["_close"] && $this->input["_job"]->fields["status"] == CommonITILObject::SOLVED) {
         $update['id'] = $this->input["_job"]->fields['id'];
         $update['status'] = CommonITILObject::CLOSED;
         $update['closedate'] = $_SESSION["glpi_currenttime"];
         // Use update method for history
         $this->input["_job"]->update($update);
         $donotif = false;
         // Done for ticket update (new status)
     }
     if (isset($this->input["_reopen"]) && $this->input["_reopen"] && in_array($this->input["_job"]->fields["status"], array(CommonITILObject::CLOSED, CommonITILObject::SOLVED, CommonITILObject::WAITING))) {
         if ($this->input["_job"]->countUsers(CommonITILActor::ASSIGN) > 0 || $this->input["_job"]->countGroups(CommonITILActor::ASSIGN) > 0 || $this->input["_job"]->countSuppliers(CommonITILActor::ASSIGN) > 0) {
             $update['status'] = CommonITILObject::ASSIGNED;
         } else {
             $update['status'] = CommonITILObject::INCOMING;
         }
         $update['id'] = $this->input["_job"]->fields['id'];
         // Use update method for history
         $this->input["_job"]->update($update);
         $donotif = false;
         // Done for ticket update (new status)
     }
     if ($donotif) {
         $options = array('followup_id' => $this->fields["id"], 'is_private' => $this->fields['is_private']);
         NotificationEvent::raiseEvent("add_followup", $this->input["_job"], $options);
     }
     // Add log entry in the ticket
     $changes[0] = 0;
     $changes[1] = '';
     $changes[2] = $this->fields['id'];
     Log::history($this->getField('tickets_id'), 'Ticket', $changes, $this->getType(), Log::HISTORY_ADD_SUBITEM);
 }
Exemple #24
0
 function pre_deleteItem()
 {
     global $CFG_GLPI;
     if ($CFG_GLPI["use_mailing"]) {
         NotificationEvent::raiseEvent("delete", $this);
     }
     return true;
 }
 /**
  * Actions done after the PURGE of the item in the database
  * Delete answers
  *
  * @return nothing
  **/
 public function post_purgeItem()
 {
     $table = getTableForItemType('PluginFormcreatorAnswer');
     $query = "DELETE FROM `{$table}` WHERE `plugin_formcreator_formanwers_id` = {$this->getID()};";
     $GLOBALS['DB']->query($query);
     // If the form was waiting for validation
     if ($this->fields['status'] == 'waiting') {
         // Notify the requester
         NotificationEvent::raiseEvent('plugin_formcreator_deleted', $this);
     }
 }
 /**
  * Cron for alert old tickets which are not solved
  *
  * @param $task : crontask object
  *
  * @return integer (0 : nothing done - 1 : done)
  **/
 static function cronAlertNotClosed($task)
 {
     global $DB, $CFG_GLPI;
     if (!$CFG_GLPI["use_mailing"]) {
         return 0;
     }
     // Recherche des entités
     $tot = 0;
     foreach (Entity::getEntitiesToNotify('notclosed_delay') as $entity => $value) {
         /*         $query = "SELECT `glpi_tickets`.*
                    FROM `glpi_tickets`
                    LEFT JOIN `glpi_alerts` ON (`glpi_tickets`.`id` = `glpi_alerts`.`items_id`
                                                AND `glpi_alerts`.`itemtype` = 'Ticket'
                                                AND `glpi_alerts`.`type`='".Alert::NOTCLOSED."')
                    WHERE `glpi_tickets`.`entities_id` = '".$entity."'
                          AND `glpi_tickets`.`status` IN ('new','assign','plan','waiting')
                          AND `glpi_tickets`.`closedate` IS NULL
                          AND ADDDATE(`glpi_tickets`.`date`, INTERVAL ".$value." DAY) < CURDATE()
                          AND `glpi_alerts`.`date` IS NULL";*/
         $query = "SELECT `glpi_tickets`.*\n                   FROM `glpi_tickets`\n                   WHERE `glpi_tickets`.`entities_id` = '" . $entity . "'\n                         AND `glpi_tickets`.`status` IN ('new','assign','plan','waiting')\n                         AND `glpi_tickets`.`closedate` IS NULL\n                         AND ADDDATE(`glpi_tickets`.`date`, INTERVAL " . $value . " DAY) < CURDATE()";
         $tickets = array();
         foreach ($DB->request($query) as $tick) {
             $tickets[] = $tick;
         }
         if (!empty($tickets)) {
             if (NotificationEvent::raiseEvent('alertnotclosed', new self(), array('tickets' => $tickets, 'entities_id' => $entity))) {
                 // To be clean : do not mark ticket as already send : always send all
                 //                $alert = new Alert();
                 //                $input["itemtype"] = 'Ticket';
                 //                $input["type"] = Alert::NOTCLOSED;
                 //                foreach ($tickets as $ticket) {
                 //                   $input["items_id"] = $ticket['id'];
                 //                   $alert->add($input);
                 //                   unset($alert->fields['id']);
                 //                }
                 // To be clean : do not mark ticket as already send : always send all
                 //                $alert = new Alert();
                 //                $input["itemtype"] = 'Ticket';
                 //                $input["type"] = Alert::NOTCLOSED;
                 //                foreach ($tickets as $ticket) {
                 //                   $input["items_id"] = $ticket['id'];
                 //                   $alert->add($input);
                 //                   unset($alert->fields['id']);
                 //                }
                 $tot += count($tickets);
                 $task->addVolume(count($tickets));
                 $task->log(Dropdown::getDropdownName('glpi_entities', $entity) . " : " . count($tickets));
             }
         }
     }
     return $tot > 0;
 }
Exemple #27
0
 /**
  * Send password recovery for a user.
  *
  * @param $email email of the user
  *
  * @return nothing : send email or display error message
  **/
 function forgetPassword($email)
 {
     global $CFG_GLPI;
     echo "<div class='center'>";
     if ($this->getFromDBbyEmail($email, "`glpi_users`.`is_active` AND NOT `glpi_users`.`is_deleted`")) {
         // Send token if auth DB or not external auth defined
         if ($this->fields["authtype"] == Auth::DB_GLPI || !Auth::useAuthExt()) {
             if (NotificationMail::isUserAddressValid($email)) {
                 $input['password_forget_token'] = sha1(Toolbox::getRandomString(30));
                 $input['password_forget_token_date'] = $_SESSION["glpi_currenttime"];
                 $input['id'] = $this->fields['id'];
                 $this->update($input);
                 // Notication on root entity (glpi_users.entities_id is only a pref)
                 NotificationEvent::raiseEvent('passwordforget', $this, array('entities_id' => 0));
                 _e('An email has been sent to your email address. The email contains information for reset your password.');
             } else {
                 _e('Invalid email address');
             }
         } else {
             _e("The authentication method configuration doesn't allow you to change your password.");
         }
     } else {
         _e('Email address not found.');
     }
     echo "<br>";
     echo "<a href=\"" . $CFG_GLPI['root_doc'] . "/index.php\">" . __s('Back') . "</a>";
     echo "</div>";
 }
Exemple #28
0
 /**
  * Cron action on infocom : alert on expired warranty
  *
  * @param $task to log, if NULL use display (default NULL)
  *
  * @return 0 : nothing to do 1 : done with success
  **/
 static function cronInfocom($task = NULL)
 {
     global $DB, $CFG_GLPI;
     if (!$CFG_GLPI["use_mailing"]) {
         return 0;
     }
     $message = array();
     $cron_status = 0;
     $items_infos = array();
     $items_messages = array();
     foreach (Entity::getEntitiesToNotify('use_infocoms_alert') as $entity => $value) {
         $before = Entity::getUsedConfig('send_infocoms_alert_before_delay', $entity);
         $query_end = "SELECT `glpi_infocoms`.*\n                       FROM `glpi_infocoms`\n                       LEFT JOIN `glpi_alerts` ON (`glpi_infocoms`.`id` = `glpi_alerts`.`items_id`\n                                                   AND `glpi_alerts`.`itemtype` = 'Infocom'\n                                                   AND `glpi_alerts`.`type`='" . Alert::END . "')\n                       WHERE (`glpi_infocoms`.`alert` & " . pow(2, Alert::END) . ") >'0'\n                             AND `glpi_infocoms`.`entities_id`='" . $entity . "'\n                             AND `glpi_infocoms`.`warranty_duration`>'0'\n                             AND `glpi_infocoms`.`warranty_date` IS NOT NULL\n                             AND DATEDIFF(ADDDATE(`glpi_infocoms`.`warranty_date`,\n                                                  INTERVAL (`glpi_infocoms`.`warranty_duration`)\n                                                           MONTH),\n                                          CURDATE() ) < '{$before}'\n                             AND `glpi_alerts`.`date` IS NULL";
         foreach ($DB->request($query_end) as $data) {
             if ($item_infocom = getItemForItemtype($data["itemtype"])) {
                 if ($item_infocom->getFromDB($data["items_id"])) {
                     $entity = $data['entities_id'];
                     $warranty = self::getWarrantyExpir($data["warranty_date"], $data["warranty_duration"]);
                     //TRANS: %1$s is a type, %2$s is a name (used in croninfocom)
                     $name = sprintf(__('%1$s - %2$s'), $item_infocom->getTypeName(1), $item_infocom->getName());
                     //TRANS: %1$s is the warranty end date and %2$s the name of the item
                     $message = sprintf(__('Item reaching the end of warranty on %1$s: %2$s'), $warranty, $name) . "<br>";
                     $data['warrantyexpiration'] = $warranty;
                     $data['item_name'] = $item_infocom->getName();
                     $items_infos[$entity][$data['id']] = $data;
                     if (!isset($items_messages[$entity])) {
                         $items_messages[$entity] = __('No item reaching the end of warranty.') . "<br>";
                     }
                     $items_messages[$entity] .= $message;
                 }
             }
         }
     }
     foreach ($items_infos as $entity => $items) {
         if (NotificationEvent::raiseEvent("alert", new self(), array('entities_id' => $entity, 'items' => $items))) {
             $message = $items_messages[$entity];
             $cron_status = 1;
             if ($task) {
                 $task->log(sprintf(__('%1$s: %2$s') . "\n", Dropdown::getDropdownName("glpi_entities", $entity), $message));
                 $task->addVolume(1);
             } else {
                 Session::addMessageAfterRedirect(sprintf(__('%1$s: %2$s'), Dropdown::getDropdownName("glpi_entities", $entity), $message));
             }
             $alert = new Alert();
             $input["itemtype"] = 'Infocom';
             $input["type"] = Alert::END;
             foreach ($items as $id => $item) {
                 $input["items_id"] = $id;
                 $alert->add($input);
                 unset($alert->fields['id']);
             }
         } else {
             $entityname = Dropdown::getDropdownName('glpi_entities', $entity);
             //TRANS: %s is entity name
             $msg = sprintf(__('%1$s: %2$s'), $entityname, __('send infocom alert failed'));
             if ($task) {
                 $task->log($msg);
             } else {
                 Session::addMessageAfterRedirect($msg, false, ERROR);
             }
         }
     }
     return $cron_status;
 }
Exemple #29
0
 /**
  * Cron action on reservation : alert on end of reservations
  *
  * @param $task to log, if NULL use display (default NULL)
  *
  * @return 0 : nothing to do 1 : done with success
  **/
 static function cronReservation($task = NULL)
 {
     global $DB, $CFG_GLPI;
     if (!$CFG_GLPI["use_mailing"]) {
         return 0;
     }
     $message = array();
     $cron_status = 0;
     $items_infos = array();
     $items_messages = array();
     foreach (Entity::getEntitiesToNotify('use_reservations_alert') as $entity => $value) {
         $secs = $value * HOUR_TIMESTAMP;
         // Reservation already begin and reservation ended in $value hours
         $query_end = "SELECT `glpi_reservationitems`.*,\n                              `glpi_reservations`.`end` AS `end`,\n                              `glpi_reservations`.`id` AS `resaid`\n                       FROM `glpi_reservations`\n                       LEFT JOIN `glpi_alerts`\n                           ON (`glpi_reservations`.`id` = `glpi_alerts`.`items_id`\n                               AND `glpi_alerts`.`itemtype` = 'Reservation'\n                               AND `glpi_alerts`.`type` = '" . Alert::END . "')\n                       LEFT JOIN `glpi_reservationitems`\n                           ON (`glpi_reservations`.`reservationitems_id`\n                                 = `glpi_reservationitems`.`id`)\n                       WHERE `glpi_reservationitems`.`entities_id` = '{$entity}'\n                             AND (UNIX_TIMESTAMP(`glpi_reservations`.`end`) - {$secs}) < UNIX_TIMESTAMP()\n                             AND `glpi_reservations`.`begin` < NOW()\n                             AND `glpi_alerts`.`date` IS NULL";
         foreach ($DB->request($query_end) as $data) {
             if ($item_resa = getItemForItemtype($data['itemtype'])) {
                 if ($item_resa->getFromDB($data["items_id"])) {
                     $data['item_name'] = $item_resa->getName();
                     $data['entity'] = $entity;
                     $items_infos[$entity][$data['resaid']] = $data;
                     if (!isset($items_messages[$entity])) {
                         $items_messages[$entity] = __('Device reservations expiring today') . "<br>";
                     }
                     $items_messages[$entity] .= sprintf(__('%1$s - %2$s'), $item_resa->getTypeName(), $item_resa->getName()) . "<br>";
                 }
             }
         }
     }
     foreach ($items_infos as $entity => $items) {
         $resitem = new self();
         if (NotificationEvent::raiseEvent("alert", new Reservation(), array('entities_id' => $entity, 'items' => $items))) {
             $message = $items_messages[$entity];
             $cron_status = 1;
             if ($task) {
                 $task->addVolume(1);
                 $task->log(sprintf(__('%1$s: %2$s') . "\n", Dropdown::getDropdownName("glpi_entities", $entity), $message));
             } else {
                 //TRANS: %1$s is a name, %2$s is text of message
                 Session::addMessageAfterRedirect(sprintf(__('%1$s: %2$s'), Dropdown::getDropdownName("glpi_entities", $entity), $message));
             }
             $alert = new Alert();
             $input["itemtype"] = 'Reservation';
             $input["type"] = Alert::END;
             foreach ($items as $resaid => $item) {
                 $input["items_id"] = $resaid;
                 $alert->add($input);
                 unset($alert->fields['id']);
             }
         } else {
             $entityname = Dropdown::getDropdownName('glpi_entities', $entity);
             //TRANS: %s is entity name
             $msg = sprintf(__('%1$s: %2$s'), $entityname, __('Send reservation alert failed'));
             if ($task) {
                 $task->log($msg);
             } else {
                 Session::addMessageAfterRedirect($msg, false, ERROR);
             }
         }
     }
     return $cron_status;
 }
 function post_deleteFromDB()
 {
     global $CFG_GLPI;
     $donotif = $CFG_GLPI["use_mailing"];
     //       if (isset($this->input["_no_notif"]) && $this->input["_no_notif"]) {
     //          $donotif = false;
     //       }
     $item = $this->getConnexityItem(static::$itemtype_1, static::getItilObjectForeignKey());
     if ($item instanceof CommonDBTM) {
         if ($item->countSuppliers(CommonITILActor::ASSIGN) == 0 && $item->countUsers(CommonITILActor::ASSIGN) == 0 && $item->countGroups(CommonITILActor::ASSIGN) == 0 && $item->fields['status'] != CommonITILObject::CLOSED && $item->fields['status'] != CommonITILObject::SOLVED) {
             $status = CommonITILObject::INCOMING;
             if (in_array($item->fields['status'], Change::getNewStatusArray())) {
                 $status = $item->fields['status'];
             }
             $item->update(array('id' => $this->fields[static::getItilObjectForeignKey()], 'status' => $status));
         } else {
             $item->updateDateMod($this->fields[static::getItilObjectForeignKey()]);
             if ($donotif) {
                 $options = array();
                 if (isset($this->fields['users_id'])) {
                     $options = array('_old_user' => $this->fields);
                 }
                 NotificationEvent::raiseEvent("update", $item, $options);
             }
         }
     }
     parent::post_deleteFromDB();
 }