PHP User::getFromDB Examples

PHP User::getFromDB - 30 examples found. These are the top rated real world PHP examples of User::getFromDB extracted from open source projects. You can rate examples to help us improve the quality of examples.
Example #1
0
 static function pdfForItem(PluginPdfSimplePDF $pdf, CommonDBTM $item)
 {
     global $DB, $CFG_GLPI;
     $ID = $item->getField('id');
     $type = get_class($item);
     if (!Session::haveRight("reservation_central", "r")) {
         return;
     }
     $user = new User();
     $ri = new ReservationItem();
     $pdf->setColumnsSize(100);
     if ($ri->getFromDBbyItem($type, $ID)) {
         $now = $_SESSION["glpi_currenttime"];
         $query = "SELECT *\n                   FROM `glpi_reservationitems`\n                   INNER JOIN `glpi_reservations`\n                        ON (`glpi_reservations`.`reservationitems_id` = `glpi_reservationitems`.`id`)\n                   WHERE `end` > '" . $now . "'\n                         AND `glpi_reservationitems`.`items_id` = '{$ID}'\n                   ORDER BY `begin`";
         $result = $DB->query($query);
         $pdf->setColumnsSize(100);
         $pdf->displayTitle("<b>" . __('Current and future reservations') . "</b>");
         if (!$DB->numrows($result)) {
             $pdf->displayLine("<b>" . __('No reservation') . "</b>");
         } else {
             $pdf->setColumnsSize(14, 14, 26, 46);
             $pdf->displayTitle('<i>' . __('Start date'), __('End date'), __('By'), __('Comments') . '</i>');
             while ($data = $DB->fetch_assoc($result)) {
                 if ($user->getFromDB($data["users_id"])) {
                     $name = formatUserName($user->fields["id"], $user->fields["name"], $user->fields["realname"], $user->fields["firstname"]);
                 } else {
                     $name = "(" . $data["users_id"] . ")";
                 }
                 $pdf->displayLine(Html::convDateTime($data["begin"]), Html::convDateTime($data["end"]), $name, str_replace(array("\r", "\n"), " ", $data["comment"]));
             }
         }
         $query = "SELECT *\n                   FROM `glpi_reservationitems`\n                   INNER JOIN `glpi_reservations`\n                        ON (`glpi_reservations`.`reservationitems_id` = `glpi_reservationitems`.`id`)\n                   WHERE `end` <= '" . $now . "'\n                         AND `glpi_reservationitems`.`items_id` = '{$ID}'\n                   ORDER BY `begin`\n                   DESC";
         $result = $DB->query($query);
         $pdf->setColumnsSize(100);
         $pdf->displayTitle("<b>" . __('Past reservations') . "</b>");
         if (!$DB->numrows($result)) {
             $pdf->displayLine("<b>" . __('No reservation') . "</b>");
         } else {
             $pdf->setColumnsSize(14, 14, 26, 46);
             $pdf->displayTitle('<i>' . __('Start date'), __('End date'), __('By'), __('Comments') . '</i>');
             while ($data = $DB->fetch_assoc($result)) {
                 if ($user->getFromDB($data["users_id"])) {
                     $name = formatUserName($user->fields["id"], $user->fields["name"], $user->fields["realname"], $user->fields["firstname"]);
                 } else {
                     $name = "(" . $data["users_id"] . ")";
                 }
                 $pdf->displayLine(Html::convDateTime($data["begin"]), Html::convDateTime($data["end"]), $name, str_replace(array("\r", "\n"), " ", $data["comment"]));
             }
         }
     }
     $pdf->displaySpace();
 }
Example #2
0
 /**
  * @since version 0.85
  *
  * @see CommonDBTM::processMassiveActionsForOneItemtype()
  **/
 static function processMassiveActionsForOneItemtype(MassiveAction $ma, CommonDBTM $item, array $ids)
 {
     switch ($ma->getAction()) {
         case 'delete_for_user':
             $input = $ma->getInput();
             if (isset($input['users_id'])) {
                 $user = new User();
                 $user->getFromDB($input['users_id']);
                 foreach ($ids as $id) {
                     if ($input['users_id'] == Session::getLoginUserID()) {
                         if ($item->deleteByCriteria(array('users_id' => $input['users_id'], 'itemtype' => $id))) {
                             $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_OK);
                         } else {
                             $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_KO);
                             $ma->addMessage($user->getErrorMessage(ERROR_ON_ACTION));
                         }
                     } else {
                         $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_NORIGHT);
                         $ma->addMessage($user->getErrorMessage(ERROR_RIGHT));
                     }
                 }
             } else {
                 $ma->itemDone($item->getType(), $ids, MassiveAction::ACTION_KO);
             }
             return;
     }
     parent::processMassiveActionsForOneItemtype($ma, $item, $ids);
 }
 /**
  * Override standard validation and sending notification to send the good PDF reports with 
  * appropriate rigths.
  * 
  * @see NotificationTarget::validateSendTo()
  * 
  * @param string $event notification event
  * @param Array $infos Current user informations
  * @param Boolean $notify_me Notify the current user of his own actions ?
  * 
  * @return boolean false to prevent standard mail sending
  */
 function validateSendTo($event, array $infos, $notify_me = false)
 {
     global $DB;
     if (isset($infos['users_id'])) {
         // save session variables
         $saved_session = $_SESSION;
         // Get current user full informations
         $user = new User();
         $user->getFromDB($infos['users_id']);
         // inialize session for user to build the proper PDF report
         unset($_SESSION['glpiprofiles'], $_SESSION['glpiactiveentities'], $_SESSION['glpiactiveprofile']);
         Session::initEntityProfiles($infos['users_id']);
         // Use default profile if exist
         if (isset($_SESSION['glpiprofiles'][$user->fields['profiles_id']])) {
             Session::changeProfile($user->fields['profiles_id']);
             // Else use first
         } else {
             Session::changeProfile(key($_SESSION['glpiprofiles']));
         }
         $user_name = $infos['username'] . '_';
         $file_name = $this->_buildPDF($user_name);
         $path = GLPI_PLUGIN_DOC_DIR . '/mreporting/notifications/' . $file_name;
         $mmail = new NotificationMail();
         $mmail->AddCustomHeader("Auto-Submitted: auto-generated");
         // For exchange
         $mmail->AddCustomHeader("X-Auto-Response-Suppress: OOF, DR, NDR, RN, NRN");
         // Get current entity administrator info to send the email from him
         $admin = $this->getSender();
         $mmail->From = $admin['email'];
         $mmail->FromName = $admin['name'];
         // Attach pdf to mail
         $mmail->AddAttachment($path, $file_name);
         // Get content infos
         $query = 'SELECT * 
               FROM glpi_notificationtemplatetranslations
               WHERE notificationtemplates_id = (
                  SELECT id 
                  FROM glpi_notificationtemplates 
                  WHERE itemtype = "PluginMreportingNotification"
               )
               AND (language LIKE "' . $_SESSION['glpilanguage'] . '" OR language LIKE "")
               ORDER BY language DESC
               LIMIT 0, 1';
         $result = $DB->query($query);
         $translation = $result->fetch_array();
         $mmail->isHTML(true);
         $mmail->Subject = $translation['subject'];
         $mmail->Body = $translation['content_html'];
         $mmail->AltBody = $translation['content_text'];
         $mmail->AddAddress($infos['email']);
         if ($mmail->Send()) {
         }
         //restore session
         unset($_SESSION);
         $_SESSION = $saved_session;
     }
     return false;
 }
 function manageContacts($items_id)
 {
     global $LANG;
     $pmContact = new PluginMonitoringContact();
     $user = new User();
     $a_list = $this->find("`plugin_monitoring_hosts_id`='" . $items_id . "'");
     echo "<form name='contacts_form' id='contacts_form'\n             method='post' action=' ";
     echo getItemTypeFormURL(__CLASS__) . "'>";
     echo "<table class='tab_cadre_fixe'>";
     echo "<tr class='tab_bg_1'>";
     echo "<th colspan='3'>";
     echo $LANG['plugin_monitoring']['contact'][20];
     echo "</th>";
     echo "</tr>";
     echo "<tr class='tab_bg_1'>";
     echo "<td class='right'>";
     $a_contacts = $pmContact->find();
     $a_elements = array();
     foreach ($a_contacts as $data) {
         $user->getFromDB($data['users_id']);
         $a_elements[$data['id']] = $user->getName();
     }
     asort($a_elements);
     Dropdown::showFromArray('plugin_monitoring_contacts_id', $a_elements);
     echo "</td>";
     echo "<td class='center'>";
     echo "<input type='submit' class='submit' name='parent_add' value='" . $LANG['buttons'][8] . " >>'>";
     echo "<br><br>";
     if ($a_list) {
         echo "<input type='submit' class='submit' name='parent_delete' value='<< " . $LANG['buttons'][6] . "'>";
     }
     echo "</td>";
     echo "<td>";
     if ($a_list) {
         echo "<select name='parent_to_delete[]' multiple size='5'>";
         foreach ($a_list as $data) {
             $pmContact->getFromDB($data['plugin_monitoring_contacts_id']);
             $user->getFromDB($pmContact->fields['users_id']);
             echo "<option value='" . $data['plugin_monitoring_contacts_id'] . "'>" . $user->getName() . "</option>";
         }
         echo "</select>";
     } else {
         echo "&nbsp;";
     }
     echo "</td>";
     echo "</tr>";
     echo "</table>";
     echo "<input type='hidden' name='id' value='" . $items_id . "' />";
     echo "</form>";
 }
Example #5
0
 public function testInitSessionUserToken()
 {
     // retrieve personnal token of 'glpi' user
     $user = new User();
     $user->getFromDB(2);
     $token = isset($user->fields['personnal_token']) ? $user->fields['personnal_token'] : "";
     if (empty($token)) {
         $token = User::getPersonalToken(2);
     }
     $res = $this->doHttpRequest('initSession', ['user_token' => $token]);
     $this->assertEquals(200, $res->getStatusCode());
     $data = xmlrpc_decode($res->getBody());
     $this->assertNotEquals(false, $data);
     $this->assertArrayHasKey('session_token', $data);
 }
 function getDatasForTemplate($event, $options = array())
 {
     global $LANG, $CFG_GLPI;
     //----------- Reservation infos -------------- //
     $events = $this->getAllEvents();
     $this->datas['##reservation.action##'] = $events[$event];
     if ($event != 'alert') {
         $this->datas['##reservation.user##'] = "";
         $user_tmp = new User();
         if ($user_tmp->getFromDB($this->obj->getField('users_id'))) {
             $this->datas['##reservation.user##'] = $user_tmp->getName();
         }
         $this->datas['##reservation.begin##'] = convDateTime($this->obj->getField('begin'));
         $this->datas['##reservation.end##'] = convDateTime($this->obj->getField('end'));
         $this->datas['##reservation.comment##'] = $this->obj->getField('comment');
         $reservationitem = new ReservationItem();
         $reservationitem->getFromDB($this->obj->getField('reservationitems_id'));
         $itemtype = $reservationitem->getField('itemtype');
         if (class_exists($itemtype)) {
             $item = new $itemtype();
             $item->getFromDB($reservationitem->getField('items_id'));
             $this->datas['##reservation.itemtype##'] = $item->getTypeName();
             $this->datas['##reservation.item.name##'] = $item->getField('name');
             $this->datas['##reservation.item.entity##'] = Dropdown::getDropdownName('glpi_entities', $item->getField('entities_id'));
             if ($item->isField('users_id_tech')) {
                 $this->datas['##reservation.item.tech##'] = Dropdown::getDropdownName('glpi_users', $item->getField('users_id_tech'));
             }
             $this->datas['##reservation.url##'] = urldecode($CFG_GLPI["url_base"] . "/index.php?redirect=" . strtolower($itemtype) . "_" . $reservationitem->getField('id'));
         }
     } else {
         $this->datas['##reservation.entity##'] = Dropdown::getDropdownName('glpi_entities', $options['entities_id']);
         foreach ($options['items'] as $id => $item) {
             $tmp = array();
             $obj = new $item['itemtype']();
             $tmp['##reservation.itemtype##'] = $obj->getTypeName();
             $tmp['##reservation.item##'] = $item['item_name'];
             $tmp['##reservation.expirationdate##'] = convDateTime($item['end']);
             $tmp['##reservation.url##'] = urldecode($CFG_GLPI["url_base"] . "/index.php?redirect=reservation_" . $id);
             $this->datas['reservations'][] = $tmp;
         }
     }
     $this->getTags();
     foreach ($this->tag_descriptions[NotificationTarget::TAG_LANGUAGE] as $tag => $values) {
         if (!isset($this->datas[$tag])) {
             $this->datas[$tag] = $values['label'];
         }
     }
 }
 /**
  * @see NotificationTarget::getDatasForTemplate()
  **/
 function getDatasForTemplate($event, $options = array())
 {
     //----------- Reservation infos -------------- //
     $events = $this->getAllEvents();
     $this->datas['##reservation.action##'] = $events[$event];
     if ($event != 'alert') {
         $this->datas['##reservation.user##'] = "";
         $user_tmp = new User();
         if ($user_tmp->getFromDB($this->obj->getField('users_id'))) {
             $this->datas['##reservation.user##'] = $user_tmp->getName();
         }
         $this->datas['##reservation.begin##'] = Html::convDateTime($this->obj->getField('begin'));
         $this->datas['##reservation.end##'] = Html::convDateTime($this->obj->getField('end'));
         $this->datas['##reservation.comment##'] = $this->obj->getField('comment');
         $reservationitem = new ReservationItem();
         $reservationitem->getFromDB($this->obj->getField('reservationitems_id'));
         $itemtype = $reservationitem->getField('itemtype');
         if ($item = getItemForItemtype($itemtype)) {
             $item->getFromDB($reservationitem->getField('items_id'));
             $this->datas['##reservation.itemtype##'] = $item->getTypeName(1);
             $this->datas['##reservation.item.name##'] = $item->getField('name');
             $this->datas['##reservation.item.entity##'] = Dropdown::getDropdownName('glpi_entities', $item->getField('entities_id'));
             if ($item->isField('users_id_tech')) {
                 $this->datas['##reservation.item.tech##'] = Dropdown::getDropdownName('glpi_users', $item->getField('users_id_tech'));
             }
             $this->datas['##reservation.itemurl##'] = $this->formatURL($options['additionnaloption']['usertype'], $itemtype . "_" . $item->getField('id'));
             $this->datas['##reservation.url##'] = $this->formatURL($options['additionnaloption']['usertype'], "ReservationItem_" . $reservationitem->getField('id'));
         }
     } else {
         $this->datas['##reservation.entity##'] = Dropdown::getDropdownName('glpi_entities', $options['entities_id']);
         foreach ($options['items'] as $id => $item) {
             $tmp = array();
             if ($obj = getItemForItemtype($item['itemtype'])) {
                 $tmp['##reservation.itemtype##'] = $obj->getTypeName(1);
                 $tmp['##reservation.item##'] = $item['item_name'];
                 $tmp['##reservation.expirationdate##'] = Html::convDateTime($item['end']);
                 $tmp['##reservation.url##'] = $this->formatURL($options['additionnaloption']['usertype'], "Reservation_" . $id);
             }
             $this->datas['reservations'][] = $tmp;
         }
     }
     $this->getTags();
     foreach ($this->tag_descriptions[NotificationTarget::TAG_LANGUAGE] as $tag => $values) {
         if (!isset($this->datas[$tag])) {
             $this->datas[$tag] = $values['label'];
         }
     }
 }
Example #8
0
 public function testInitSessionUserToken()
 {
     // retrieve personnal token of 'glpi' user
     $user = new User();
     $user->getFromDB(2);
     $token = isset($user->fields['personnal_token']) ? $user->fields['personnal_token'] : "";
     if (empty($token)) {
         $token = User::getPersonalToken(2);
     }
     $res = $this->doHttpRequest('GET', 'initSession/', ['headers' => ['Authorization' => "user_token {$token}"]]);
     $this->assertNotEquals(null, $res, $this->last_error);
     $this->assertEquals(200, $res->getStatusCode());
     $body = $res->getBody();
     $data = json_decode($body, true);
     $this->assertNotEquals(false, $data);
     $this->assertArrayHasKey('session_token', $data);
 }
Example #9
0
 protected function _testTicketUser(Ticket $ticket, $actor, $role, $notify, $alternateEmail)
 {
     if ($actor > 0) {
         $user = new User();
         $user->getFromDB($actor);
         $this->assertFalse($user->isNewItem());
         $ticketUser = new Ticket_User();
         $ticketUser->getFromDBForItems($ticket, $user);
         $this->assertFalse($ticketUser->isNewItem());
         $this->assertEquals($role, $ticketUser->getField('type'));
         $this->assertEquals($notify, $ticketUser->getField('use_notification'));
     } else {
         $ticketId = $ticket->getID();
         $ticketUser = new Ticket_User();
         $ticketUser->getFromDBByQuery("WHERE `tickets_id` = '{$ticketId}' AND `users_id` = '0' AND `alternative_email` = '{$alternateEmail}'");
         $this->assertFalse($ticketUser->isNewItem());
         $this->assertEquals($role, $ticketUser->getField('type'));
         $this->assertEquals($notify, $ticketUser->getField('use_notification'));
     }
 }
 public function getDatasForTemplate($event, $options = array())
 {
     $form = new PluginFormcreatorForm();
     $form->getFromDB($this->obj->fields['plugin_formcreator_forms_id']);
     $link = $GLOBALS['CFG_GLPI']['url_base'];
     $link .= '/plugins/formcreator/front/formanswer.form.php?id=' . $this->obj->getID();
     $requester = new User();
     $requester->getFromDB($this->obj->fields['requester_id']);
     $validator = new User();
     $validator->getFromDB($this->obj->fields['validator_id']);
     $this->datas['##formcreator.form_id##'] = $form->getID();
     $this->datas['##formcreator.form_name##'] = $form->fields['name'];
     $this->datas['##formcreator.form_requester##'] = $requester->getName();
     $this->datas['##formcreator.form_validator##'] = $validator->getName();
     $this->datas['##formcreator.form_creation_date##'] = Html::convDateTime($this->obj->fields['request_date']);
     $this->datas['##formcreator.form_full_answers##'] = $this->obj->getFullForm();
     $this->datas['##formcreator.validation_comment##'] = $this->obj->fields['comment'];
     $this->datas['##formcreator.validation_link##'] = $link;
     $this->datas['##formcreator.request_id##'] = $this->obj->fields['id'];
 }
 /**
  * Print the object user form for notification
  *
  * @param $ID              integer ID of the item
  * @param $options   array
  *
  * @return Nothing (display)
  **/
 function showUserNotificationForm($ID, $options = array())
 {
     global $CFG_GLPI;
     $this->check($ID, UPDATE);
     if (!isset($this->fields['users_id'])) {
         return false;
     }
     $item = new static::$itemtype_1();
     echo "<br><form method='post' action='" . $_SERVER['PHP_SELF'] . "'>";
     echo "<div class='center'>";
     echo "<table class='tab_cadre' width='80%'>";
     echo "<tr class='tab_bg_2'><td>" . $item->getTypeName(1) . "</td>";
     echo "<td>";
     if ($item->getFromDB($this->fields[static::getItilObjectForeignKey()])) {
         echo $item->getField('name');
     }
     echo "</td></tr>";
     $user = new User();
     $default_email = "";
     $emails = array();
     if ($user->getFromDB($this->fields["users_id"])) {
         $default_email = $user->getDefaultEmail();
         $emails = $user->getAllEmails();
     }
     echo "<tr class='tab_bg_2'><td>" . __('User') . "</td>";
     echo "<td>" . $user->getName() . "</td></tr>";
     echo "<tr class='tab_bg_1'><td>" . __('Email Followup') . "</td>";
     echo "<td>";
     Dropdown::showYesNo('use_notification', $this->fields['use_notification']);
     echo "</td></tr>";
     echo "<tr class='tab_bg_1'><td>" . __('Email') . "</td>";
     echo "<td>";
     if (count($emails) == 1 && !empty($default_email) && NotificationMail::isUserAddressValid($default_email)) {
         echo $default_email;
     } else {
         if (count($emails) > 1) {
             // Several emails : select in the list
             $emailtab = array();
             foreach ($emails as $new_email) {
                 if ($new_email != $default_email) {
                     $emailtab[$new_email] = $new_email;
                 } else {
                     $emailtab[''] = $new_email;
                 }
             }
             Dropdown::showFromArray("alternative_email", $emailtab, array('value' => $this->fields['alternative_email']));
         } else {
             echo "<input type='text' size='40' name='alternative_email' value='" . $this->fields['alternative_email'] . "'>";
         }
     }
     echo "</td></tr>";
     echo "<tr class='tab_bg_2'>";
     echo "<td class='center' colspan='2'>";
     echo "<input type='submit' name='update' value=\"" . _sx('button', 'Save') . "\" class='submit'>";
     echo "<input type='hidden' name='id' value='{$ID}'>";
     echo "</td></tr>";
     echo "</table></div>";
     Html::closeForm();
 }
Example #12
0
/**
 * @param $pid
 * @param $data
 * @param $server
 * @param $prof
 * @param $verb
 * @param $mail
**/
function syncEntity($pid, $data, $server, $prof, $verb, $mail)
{
    global $DB, $LANG, $CFG_GLPI;
    // Re-establish DB connexion - mandatory in each forked process
    if (!DBConnection::switchToMaster()) {
        echo " {$pid}: lost DB connection\n";
        return 0;
    }
    // Server from entity (if not given from option)
    if ($data['authldaps_id'] > 0) {
        $server = $data['authldaps_id'];
    }
    $entity = new Entity();
    if ($entity->getFromDB($id = $data['id'])) {
        $tps = microtime(true);
        if ($verb) {
            echo "  {$pid}: Synchonizing entity '" . $entity->getField('completename') . "' ({$id}, mail={$mail})\n";
        }
        $sql = "SELECT DISTINCT glpi_users.*\n              FROM glpi_users\n              INNER JOIN glpi_profiles_users\n                  ON (glpi_profiles_users.users_id = glpi_users.id\n                      AND glpi_profiles_users.entities_id = {$id}";
        if ($prof > 0) {
            $sql .= "    AND glpi_profiles_users.profiles_id = {$prof}";
        }
        $sql .= ")\n               WHERE glpi_users.authtype = " . Auth::LDAP;
        if ($server > 0) {
            $sql .= " AND glpi_users.auths_id = {$server}";
        }
        $users = array();
        $results = array(AuthLDAP::USER_IMPORTED => 0, AuthLDAP::USER_SYNCHRONIZED => 0, AuthLDAP::USER_DELETED_LDAP => 0);
        $req = $DB->request($sql);
        $i = 0;
        $nb = $req->numrows();
        foreach ($req as $row) {
            $i++;
            $result = AuthLdap::ldapImportUserByServerId(array('method' => AuthLDAP::IDENTIFIER_LOGIN, 'value' => $row['name']), AuthLDAP::ACTION_SYNCHRONIZE, $row['auths_id']);
            if ($result) {
                $results[$result['action']] += 1;
                $users[$row['id']] = $row['name'];
                if ($result['action'] == AuthLDAP::USER_SYNCHRONIZED) {
                    if ($verb) {
                        echo "  {$pid}: User '" . $row['name'] . "' synchronized ({$i}/{$nb})\n";
                    }
                } else {
                    if ($verb) {
                        echo "  {$pid}: User '" . $row['name'] . "' deleted\n";
                    }
                }
            } else {
                if ($verb) {
                    echo "  {$pid}: Problem with LDAP for user '" . $row['name'] . "'\n";
                }
            }
        }
        $tps = microtime(true) - $tps;
        printf("  %d: Entity '%s' - Synchronized: %d, Deleted from LDAP: %d, Time: %.2f\"\n", $pid, $entity->getField('completename'), $results[AuthLDAP::USER_SYNCHRONIZED], $results[AuthLDAP::USER_DELETED_LDAP], $tps);
        if ($mail) {
            $report = '';
            $user = new User();
            foreach ($users as $id => $name) {
                if ($user->getFromDB($id)) {
                    $logs = Log::getHistoryData($user, 0, $_SESSION['glpilist_limit'], "`date_mod`='" . $_SESSION['glpi_currenttime'] . "'");
                    if (count($logs)) {
                        $report .= "\n{$name} (" . $user->getName() . ")\n";
                        foreach ($logs as $log) {
                            $report .= "\t";
                            if ($log['field']) {
                                $report .= $log['field'] . ": ";
                            }
                            $report .= Html::clean($log['change']) . "\n";
                        }
                    }
                } else {
                    $report .= "\n" . $name . "\n\t deleted\n";
                }
            }
            if ($report) {
                $report = "Synchronization of already imported users\n " . "Entité: " . $entity->getField('completename') . "\n " . "Date: " . Html::convDateTime($_SESSION['glpi_currenttime']) . "\n " . $report;
                $entdata = new Entity();
                $mmail = new NotificationMail();
                $mmail->AddCustomHeader("Auto-Submitted: auto-generated");
                $mmail->From = $CFG_GLPI["admin_email"];
                $mmail->FromName = "GLPI";
                $mmail->Subject = "[GLPI] LDAP directory link";
                $mmail->Body = $report . "\n--\n" . $CFG_GLPI["mailing_signature"];
                if ($mail & 1 && $entdata->getFromDB($entity->getField('id')) && $entdata->fields['admin_email']) {
                    $mmail->AddAddress($entdata->fields['admin_email']);
                } else {
                    if ($mail & 1 && $verb) {
                        echo "  {$pid}: No address found for email entity\n";
                    }
                    $mail = $mail & 2;
                }
                if ($mail & 2 && $CFG_GLPI['admin_email']) {
                    $mmail->AddAddress($CFG_GLPI['admin_email']);
                } else {
                    if ($mail & 2 && $verb) {
                        echo "  {$pid}: No address found for email admin\n";
                    }
                    $mail = $mail & 1;
                }
                if ($mail) {
                    if ($mmail->Send() && $verb) {
                        echo "  {$pid}: Report sent by email\n";
                    }
                } else {
                    echo "  {$pid}: Cannot send report (" . $entity->getField('completename') . ") " . "invalid address\n";
                }
            }
        }
        return $results[AuthLDAP::USER_DELETED_LDAP] + $results[AuthLDAP::USER_SYNCHRONIZED];
    }
    return 0;
}
Example #13
0
 /**
  * Load display options to $_SESSION
  *
  * @since version 0.84
  *
  * @param $sub_itemtype  string   sub itemtype if needed (default '')
  *
  * @return nothing
  **/
 static function getDisplayOptions($sub_itemtype = '')
 {
     if (!isset($_SESSION['glpi_display_options'])) {
         // Load display_options from user table
         $_SESSION['glpi_display_options'] = array();
         if ($uid = Session::getLoginUserID()) {
             $user = new User();
             if ($user->getFromDB($uid)) {
                 $_SESSION['glpi_display_options'] = importArrayFromDB($user->fields['display_options']);
             }
         }
     }
     if (!isset($_SESSION['glpi_display_options'][self::getType()])) {
         $_SESSION['glpi_display_options'][self::getType()] = array();
     }
     if (!empty($sub_itemtype)) {
         if (!isset($_SESSION['glpi_display_options'][self::getType()][$sub_itemtype])) {
             $_SESSION['glpi_display_options'][self::getType()][$sub_itemtype] = array();
         }
         $display_options =& $_SESSION['glpi_display_options'][self::getType()][$sub_itemtype];
     } else {
         $display_options =& $_SESSION['glpi_display_options'][self::getType()];
     }
     // Load default values if not set
     $options = static::getAvailableDisplayOptions();
     if (count($options)) {
         foreach ($options as $option_group_name => $option_group) {
             foreach ($option_group as $option_name => $attributs) {
                 if (!isset($display_options[$option_name])) {
                     $display_options[$option_name] = $attributs['default'];
                 }
             }
         }
     }
     return $display_options;
 }
Example #14
0
 static function pdfMain(PluginPdfSimplePDF $pdf, Ticket $job)
 {
     global $CFG_GLPI, $DB;
     $ID = $job->getField('id');
     if (!$job->can($ID, 'r')) {
         return false;
     }
     $pdf->setColumnsSize(100);
     $pdf->displayTitle('<b>' . (empty($job->fields["name"]) ? __('Without title') : ($name = $job->fields["name"])) . '</b>');
     if (count($_SESSION['glpiactiveentities']) > 1) {
         $entity = " (" . Dropdown::getDropdownName("glpi_entities", $job->fields["entities_id"]) . ")";
     } else {
         $entity = '';
     }
     $pdf->setColumnsSize(50, 50);
     $recipient_name = '';
     if ($job->fields["users_id_recipient"]) {
         $recipient = new User();
         $recipient->getFromDB($job->fields["users_id_recipient"]);
         $recipient_name = $recipient->getName();
     }
     $sla = $due = $commentsla = '';
     if ($job->fields['due_date']) {
         $due = "<b><i>" . sprintf(__('%1$s: %2$s'), __('Due date') . "</b></i>", Html::convDateTime($job->fields['due_date']));
     }
     $pdf->displayLine("<b><i>" . sprintf(__('%1$s: %2$s'), __('Opening date') . "</i></b>", Html::convDateTime($job->fields["date"])), $due);
     $pdf->setColumnsSize(100);
     if ($job->fields["slas_id"] > 0) {
         $sla = "<b><i>" . sprintf(__('%1$s: %2$s'), __('SLA') . "</b></i>", Html::clean(Dropdown::getDropdownName("glpi_slas", $job->fields["slas_id"])));
         $slalevel = new SlaLevel();
         if ($slalevel->getFromDB($job->fields['slalevels_id'])) {
             $commentsla = "<b><i>" . sprintf(__('%1$s: %2$s'), __('Escalation level') . "</b></i>", $slalevel->getName());
         }
         $nextaction = new SlaLevel_Ticket();
         if ($nextaction->getFromDBForTicket($job->fields["id"])) {
             $commentsla .= " <b><i>" . sprintf(__('Next escalation: %s') . "</b></i>", Html::convDateTime($nextaction->fields['date']));
             if ($slalevel->getFromDB($nextaction->fields['slalevels_id'])) {
                 $commentsla .= " <b><i>" . sprintf(__('%1$s: %2$s'), __('Escalation level'), $slalevel->getName());
             }
         }
         $pdf->displayText($sla, $commentsla, 1);
     }
     $pdf->setColumnsSize(50, 50);
     $lastupdate = Html::convDateTime($job->fields["date_mod"]);
     if ($job->fields['users_id_lastupdater'] > 0) {
         $lastupdate = sprintf(__('%1$s by %2$s'), $lastupdate, getUserName($job->fields["users_id_lastupdater"]));
     }
     $pdf->displayLine('<b><i>' . sprintf(__('%1$s: %2$s'), __('By') . "</i></b>", $recipient_name), '<b><i>' . sprintf(__('%1$s: %2$s'), __('Last update') . '</i></b>', $lastupdate));
     $pdf->displayLine("<b><i>" . sprintf(__('%1$s: %2$s'), __('Type') . "</i></b>", Html::clean(Ticket::getTicketTypeName($job->fields["type"]))), "<b><i>" . sprintf(__('%1$s: %2$s'), __('Category') . "</i></b>", Html::clean(Dropdown::getDropdownName("glpi_itilcategories", $job->fields["itilcategories_id"]))));
     $status = '';
     if (in_array($job->fields["status"], $job->getSolvedStatusArray()) || in_array($job->fields["status"], $job->getClosedStatusArray())) {
         $status = sprintf(__('%1$s %2$s'), '-', Html::convDateTime($job->fields["solvedate"]));
     }
     if (in_array($job->fields["status"], $job->getClosedStatusArray())) {
         $status = sprintf(__('%1$s %2$s'), '-', Html::convDateTime($job->fields["closedate"]));
     }
     if ($job->fields["status"] == Ticket::WAITING) {
         $status = sprintf(__('%1$s %2$s'), '-', Html::convDateTime($job->fields['begin_waiting_date']));
     }
     $pdf->displayLine("<b><i>" . sprintf(__('%1$s: %2$s'), __('Status') . "</i></b>", Html::clean($job->getStatus($job->fields["status"])) . $status), "<b><i>" . sprintf(__('%1$s: %2$s'), __('Request source') . "</i></b>", Html::clean(Dropdown::getDropdownName('glpi_requesttypes', $job->fields['requesttypes_id']))));
     $pdf->displayLine("<b><i>" . sprintf(__('%1$s: %2$s'), __('Urgency') . "</i></b>", Html::clean($job->getUrgencyName($job->fields["urgency"]))), "<b><i>" . sprintf(__('%1$s: %2$s'), __('Approval') . "</i></b>", TicketValidation::getStatus($job->fields['global_validation'])));
     $pdf->displayLine("<b><i>" . sprintf(__('%1$s: %2$s'), __('Impact') . "</i></b>", Html::clean($job->getImpactName($job->fields["impact"]))));
     $pdf->displayLine("<b><i>" . sprintf(__('%1$s: %2$s'), __('Priority') . "</i></b>", Html::clean($job->getPriorityName($job->fields["priority"]))), "<b><i>" . sprintf(__('%1$s: %2$s'), __('Location') . "</i></b>", Html::clean(Dropdown::getDropdownName("glpi_locations", $job->fields["locations_id"]))));
     // Item
     $name = "<b><i>" . sprintf(__('%1$s: %2$s'), __('Associated element') . "</i></b>", '');
     $commentitem = '';
     $pdf->setColumnsSize(100);
     if ($job->fields['itemtype'] && ($item = getItemForItemtype($job->fields['itemtype']))) {
         if ($item->getFromDB($job->fields["items_id"])) {
             $name = "<b><i>" . sprintf(__('%1$s: %2$s'), __('Associated element') . "</i></b>", $item->getNameID());
             if (isset($item->fields["serial"])) {
                 $commentitem = ", <b><i>" . sprintf(__('%1$s: %2$s'), __('Serial number') . "</i></b>", Html::clean($item->fields["serial"]));
                 Html::clean($item->fields["serial"]);
             }
             if (isset($item->fields["otherserial"])) {
                 $commentitem .= ", <b><i>" . sprintf(__('%1$s: %2$s'), __('Inventory number') . "</i></b>", Html::clean($item->fields["otherserial"]));
             }
             if (isset($item->fields["locations_id"])) {
                 $commentitem .= ", <b><i>" . sprintf(__('%1$s: %2$s'), __('Location') . "</i></b>", Html::clean(Dropdown::getDropdownName("glpi_locations", $item->fields["locations_id"])));
             }
         }
     }
     $pdf->displayText($name, $commentitem, 1);
     $pdf->setColumnsSize(50, 50);
     // Requester
     $users = array();
     $listusers = '';
     $requester = '<b><i>' . sprintf(__('%1$s: %2$s') . "</i></b>", __('Requester'), $listusers);
     foreach ($job->getUsers(CommonITILActor::REQUESTER) as $d) {
         if ($d['users_id']) {
             $tmp = Html::clean(getUserName($d['users_id']));
             if ($d['alternative_email']) {
                 $tmp .= ' (' . $d['alternative_email'] . ')';
             }
         } else {
             $tmp = $d['alternative_email'];
         }
         $users[] = $tmp;
     }
     if (count($users)) {
         $listusers = implode(', ', $users);
     }
     $pdf->displayText($requester, $listusers, 1);
     $groups = array();
     $listgroups = '';
     $requestergroup = '<b><i>' . sprintf(__('%1$s: %2$s') . "</i></b>", __('Requester group'), $listgroups);
     foreach ($job->getGroups(CommonITILActor::REQUESTER) as $d) {
         $groups[] = Html::clean(Dropdown::getDropdownName("glpi_groups", $d['groups_id']));
     }
     if (count($groups)) {
         $listgroups = implode(', ', $groups);
     }
     $pdf->displayText($requestergroup, $listgroups, 1);
     // Observer
     $users = array();
     $listusers = '';
     $watcher = '<b><i>' . sprintf(__('%1$s: %2$s') . "</i></b>", __('Watcher'), $listusers);
     foreach ($job->getUsers(CommonITILActor::OBSERVER) as $d) {
         if ($d['users_id']) {
             $tmp = Html::clean(getUserName($d['users_id']));
             if ($d['alternative_email']) {
                 $tmp .= ' (' . $d['alternative_email'] . ')';
             }
         } else {
             $tmp = $d['alternative_email'];
         }
         $users[] = $tmp;
     }
     if (count($users)) {
         $listusers = implode(', ', $users);
     }
     $pdf->displayText($watcher, $listusers, 1);
     $groups = array();
     $listgroups = '';
     $watchergroup = '<b><i>' . sprintf(__('%1$s: %2$s') . "</i></b>", __('Watcher group'), $listgroups);
     foreach ($job->getGroups(CommonITILActor::OBSERVER) as $d) {
         $groups[] = Html::clean(Dropdown::getDropdownName("glpi_groups", $d['groups_id']));
     }
     if (count($groups)) {
         $listgroups = implode(', ', $groups);
     }
     $pdf->displayText($watchergroup, $listgroups, 1);
     // Assign to
     $users = array();
     $listusers = '';
     $assign = '<b><i>' . sprintf(__('%1$s: %2$s') . "</i></b>", __('User assigned'), $listusers);
     foreach ($job->getUsers(CommonITILActor::ASSIGN) as $d) {
         if ($d['users_id']) {
             $tmp = Html::clean(getUserName($d['users_id']));
             if ($d['alternative_email']) {
                 $tmp .= ' (' . $d['alternative_email'] . ')';
             }
         } else {
             $tmp = $d['alternative_email'];
         }
         $users[] = $tmp;
     }
     if (count($users)) {
         $listusers = implode(', ', $users);
     }
     $pdf->displayText($assign, $listusers, 1);
     $groups = array();
     $listgroups = '';
     $assigngroup = '<b><i>' . sprintf(__('%1$s: %2$s') . "</i></b>", __('Group assigned'), $listgroups);
     foreach ($job->getGroups(CommonITILActor::ASSIGN) as $d) {
         $groups[] = Html::clean(Dropdown::getDropdownName("glpi_groups", $d['groups_id']));
     }
     if (count($groups)) {
         $listgroups = implode(', ', $groups);
     }
     $pdf->displayText($assigngroup, $listgroups, 1);
     // Supplier
     $suppliers = array();
     $listsuppliers = '';
     $assignsupplier = '<b><i>' . sprintf(__('%1$s: %2$s') . "</i></b>", __('Supplier assigned'), $listsuppliers);
     foreach ($job->getSuppliers(CommonITILActor::ASSIGN) as $d) {
         $suppliers[] = Html::clean(Dropdown::getDropdownName("glpi_suppliers", $d['suppliers_id']));
     }
     if (count($suppliers)) {
         $listsuppliers = implode(', ', $suppliers);
     }
     $pdf->displayText($assignsupplier, $listsuppliers, 1);
     $pdf->setColumnsSize(100);
     $pdf->displayLine("<b><i>" . sprintf(__('%1$s: %2$s'), __('Title') . "</i></b>", $job->fields["name"]));
     $pdf->displayText("<b><i>" . sprintf(__('%1$s: %2$s'), __('Description') . "</i></b>", $job->fields['content']));
     // Linked tickets
     $tickets = Ticket_Ticket::getLinkedTicketsTo($ID);
     if (is_array($tickets) && count($tickets)) {
         $ticket = new Ticket();
         foreach ($tickets as $linkID => $data) {
             $tmp = sprintf(__('%1$s %2$s'), Ticket_Ticket::getLinkName($data['link']), sprintf(__('%1$s %2$s'), __('ID'), $data['tickets_id']));
             if ($ticket->getFromDB($data['tickets_id'])) {
                 $tmp = sprintf(__('%1$s: %2$s'), $tmp, $ticket->getName());
             }
             $jobs[] = $tmp;
             $jobs = implode("\n", $jobs);
         }
         $linked = "<b><i>" . sprintf(__('%1$s: %2$s') . "</i></b>", __('Linked tickets'), '');
         $pdf->displayText($linked, $jobs, 1);
     }
     $pdf->displaySpace();
 }
Example #15
0
 static function displayLine($data, $displayhost = 1)
 {
     global $DB, $CFG_GLPI;
     $pMonitoringService = new PluginMonitoringService();
     $networkPort = new NetworkPort();
     $pMonitoringComponent = new PluginMonitoringComponent();
     $pmComponentscatalog_Host = new PluginMonitoringComponentscatalog_Host();
     $entity = new Entity();
     $pMonitoringService->getFromDB($data['id']);
     echo "<td width='32' class='center'>";
     $shortstate = self::getState($data['state'], $data['state_type'], $data['event'], $data['is_acknowledged']);
     $alt = __('Ok', 'monitoring');
     if ($shortstate == 'orange') {
         $alt = __('Warning (data)', 'monitoring');
     } else {
         if ($shortstate == 'yellow') {
             $alt = __('Warning (connection)', 'monitoring');
         } else {
             if ($shortstate == 'red') {
                 $alt = __('Critical', 'monitoring');
             } else {
                 if ($shortstate == 'redblue') {
                     $alt = __('Critical / Acknowledge', 'monitoring');
                 }
             }
         }
     }
     echo "<img src='" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/pics/box_" . $shortstate . "_32.png'\n         title='" . $alt . "' alt='" . $alt . "' />";
     echo "</td>";
     echo "<td>";
     $entity->getFromDB($data['entities_id']);
     echo $entity->fields['completename'];
     echo "</td>";
     $pMonitoringComponent->getFromDB($data['plugin_monitoring_components_id']);
     echo "<td class='center'>";
     $timezone = '0';
     if (isset($_SESSION['plugin_monitoring_timezone'])) {
         $timezone = $_SESSION['plugin_monitoring_timezone'];
     }
     if ($pMonitoringComponent->fields['graph_template'] != '') {
         echo "<a href='" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/front/display.form.php?itemtype=PluginMonitoringService&items_id=" . $data['id'] . "'>";
         $pmServicegraph = new PluginMonitoringServicegraph();
         ob_start();
         $pmServicegraph->displayGraph($pMonitoringComponent->fields['graph_template'], "PluginMonitoringService", $data['id'], "0", '2h', "div", "600");
         $div = ob_get_contents();
         ob_end_clean();
         $chart = "<table width='600' class='tab_cadre'><tr><td>" . $div . "</td></tr></table>";
         Html::showToolTip($chart, array('img' => $CFG_GLPI['root_doc'] . "/plugins/monitoring/pics/stats_32.png"));
         $pmServicegraph->displayGraph($pMonitoringComponent->fields['graph_template'], "PluginMonitoringService", $data['id'], "0", '2h', "js");
     }
     echo "</a>";
     echo "</td>";
     if ($displayhost == '1') {
         $pmComponentscatalog_Host->getFromDB($data["plugin_monitoring_componentscatalogs_hosts_id"]);
         if (isset($pmComponentscatalog_Host->fields['itemtype']) and $pmComponentscatalog_Host->fields['itemtype'] != '') {
             $itemtype = $pmComponentscatalog_Host->fields['itemtype'];
             $item = new $itemtype();
             $item->getFromDB($pmComponentscatalog_Host->fields['items_id']);
             echo "<td>";
             echo $item->getTypeName() . " : " . $item->getLink();
             if (!is_null($pMonitoringService->fields['networkports_id']) and $pMonitoringService->fields['networkports_id'] > 0) {
                 $networkPort->getFromDB($pMonitoringService->fields['networkports_id']);
                 echo " [" . $networkPort->getLink() . "]";
             }
             echo "</td>";
         } else {
             echo "<td>" . __('Resources', 'monitoring') . "</td>";
         }
     }
     echo "<td>" . $pMonitoringComponent->getLink();
     if (!is_null($pMonitoringService->fields['networkports_id']) and $pMonitoringService->fields['networkports_id'] > 0) {
         $networkPort->getFromDB($pMonitoringService->fields['networkports_id']);
         echo " [" . $networkPort->getLink() . "]";
     }
     echo "</td>";
     //      $nameitem = '';
     //      if (isset($itemmat->fields['name'])) {
     //         $nameitem = "[".$itemmat->getLink(1)."]";
     //      }
     //if ($pMonitoringService->fields['plugin_monitoring_services_id'] == '0') {
     //echo "<td>".$itemmat->getLink(1)."</td>";
     //      } else {
     //         $pMonitoringServiceH->getFromDB($pMonitoringService->fields['plugin_monitoring_services_id']);
     //         $itemtypemat = $pMonitoringServiceH->fields['itemtype'];
     //         $itemmat = new $itemtypemat();
     //         $itemmat->getFromDB($pMonitoringServiceH->fields['items_id']);
     //         echo "<td>".$pMonitoringService->getLink(1).$nameitem." ".__('on', 'monitoring')." ".$itemmat->getLink(1)."</td>";
     //      }
     //      unset($itemmat);
     echo "<td class='center'>";
     if ($shortstate == 'red') {
         echo "<table>";
         echo "<tr>";
         echo "<td>";
         echo $data['state'];
         echo "</td>";
         echo "<td>";
         echo "<a href='" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/front/acknowledge.form.php?id=" . $data['id'] . "'>" . "<img src='" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/pics/acknowledge_checked.png'" . " alt='" . __('Define an acknowledge', 'monitoring') . "'" . " title='" . __('Define an acknowledge', 'monitoring') . "'/>" . "</a>";
         echo "</td>";
         echo "</tr>";
         echo "</table>";
     } else {
         echo $data['state'];
     }
     echo "</td>";
     echo "<td>";
     echo Html::convDate($data['last_check']) . ' ' . substr($data['last_check'], 11, 8);
     echo "</td>";
     echo "<td>";
     echo $data['event'];
     echo "</td>";
     echo "<td align='center'>";
     $segments = CalendarSegment::getSegmentsBetween($pMonitoringComponent->fields['calendars_id'], date('w', date('U')), date('H:i:s'), date('w', date('U')), date('H:i:s'));
     if (count($segments) == '0') {
         echo "<img src='" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/pics/service_pause.png' />";
     } else {
         echo "<img src='" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/pics/service_run.png' />";
     }
     echo "</td>";
     if ($displayhost == '0') {
         $pmUnavaibility = new PluginMonitoringUnavaibility();
         $pmUnavaibility->displayValues($pMonitoringService->fields['id'], 'currentmonth', 1);
         $pmUnavaibility->displayValues($pMonitoringService->fields['id'], 'lastmonth', 1);
         $pmUnavaibility->displayValues($pMonitoringService->fields['id'], 'currentyear', 1);
         echo "<td class='center'>";
         echo "<a href='" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/front/unavaibility.php?" . "field[0]=2&searchtype[0]=equals&contains[0]=" . $pMonitoringService->fields['id'] . "&sort=3&order=DESC&itemtype=PluginMonitoringUnavaibility'>\n            <img src='" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/pics/info.png'/></a>";
         echo "</td>";
     }
     echo "<td>";
     if ($shortstate == 'redblue') {
         echo "<i>" . _n('User', 'Users', 1) . " : </i>";
         $user = new User();
         $user->getFromDB($data['acknowledge_users_id']);
         echo $user->getName(1);
         echo "<br/>";
         echo "<i>" . __('Comments') . " : </i>" . $data['acknowledge_comment'];
     }
     echo "</td>";
     if ($displayhost == '0') {
         echo "<td>";
         if (PluginMonitoringProfile::haveRight("componentscatalog", 'w')) {
             $a_arg = importArrayFromDB($pMonitoringService->fields['arguments']);
             $cnt = '';
             if (count($a_arg) > 0) {
                 $cnt = " (" . count($a_arg) . ")";
             }
             echo "<a href='" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/front/servicearg.form.php?id=" . $data['id'] . "'>" . __('Configure', 'monitoring') . $cnt . "</a>";
         }
         echo "</td>";
     }
 }
 } else {
     if (isset($_POST["restore"])) {
         $user->check($_POST['id'], PURGE);
         $user->restore($_POST);
         Event::log($_POST["id"], "users", 4, "setup", sprintf(__('%s restores an item'), $_SESSION["glpiname"]));
         $user->redirectToList();
     } else {
         if (isset($_POST["purge"])) {
             $user->check($_POST['id'], PURGE);
             $user->delete($_POST, 1);
             Event::log($_POST["id"], "users", 4, "setup", sprintf(__('%s purges an item'), $_SESSION["glpiname"]));
             $user->redirectToList();
         } else {
             if (isset($_POST["force_ldap_resynch"])) {
                 Session::checkRight('user', User::UPDATEAUTHENT);
                 $user->getFromDB($_POST["id"]);
                 AuthLdap::ldapImportUserByServerId(array('method' => AuthLDAP::IDENTIFIER_LOGIN, 'value' => $user->fields["name"]), true, $user->fields["auths_id"], true);
                 Html::back();
             } else {
                 if (isset($_POST["update"])) {
                     $user->check($_POST['id'], UPDATE);
                     $user->update($_POST);
                     Event::log($_POST['id'], "users", 5, "setup", sprintf(__('%s updates an item'), $_SESSION["glpiname"]));
                     Html::back();
                 } else {
                     if (isset($_POST["addgroup"])) {
                         $groupuser->check(-1, CREATE, $_POST);
                         if ($groupuser->add($_POST)) {
                             Event::log($_POST["users_id"], "users", 4, "setup", sprintf(__('%s adds a user to a group'), $_SESSION["glpiname"]));
                         }
                         Html::back();
Example #17
0
   function _addContactUser($a_contacts, $users_id, $i) {

      $pmContact              = new PluginMonitoringContact();
      $pmNotificationcommand  = new PluginMonitoringNotificationcommand();
      $pmContacttemplate      = new PluginMonitoringContacttemplate();
      $user                   = new User();
      $calendar               = new Calendar();

      $user->getFromDB($users_id);

      // Get contact template
      $a_pmcontact = current($pmContact->find("`users_id`='".$users_id."'", "", 1));
      if (empty($a_pmcontact) OR
              (isset($a_pmcontact['plugin_monitoring_contacttemplates_id'])
              AND $a_pmcontact['plugin_monitoring_contacttemplates_id'] == '0')) {
         // Use default template
         $a_pmcontact = current($pmContacttemplate->find("`is_default`='1'", "", 1));
      } else {
         // Use contact defined template
         $a_pmcontact = current($pmContacttemplate->find("`id`='".$a_pmcontact['plugin_monitoring_contacttemplates_id']."'", "", 1));
      }
      $a_contacts[$i]['contact_name'] = $user->fields['name'];
      $a_contacts[$i]['alias'] = $user->getName();
      PluginMonitoringToolbox::logIfExtradebug(
         'pm-shinken',
         "- contact ".$user->fields['name']." - ".$user->getName()."\n"
      );
      // Toolbox::logInFile("pm-contacts", "- contact ".serialize($user->fields)."\n");

      if (!isset($a_pmcontact['host_notification_period'])) {
         $a_calendars = current($calendar->find("", "", 1));
         $cal = '24x7';
         if (isset($a_calendars['name'])) {
            $cal = $a_calendars['name'];
         }
         $a_pmcontact['host_notifications_enabled'] = '0';
         $a_pmcontact['service_notifications_enabled'] = '0';
         $a_pmcontact['service_notification_period'] = $cal;
         $a_pmcontact['host_notification_period'] = $cal;
         $a_pmcontact['service_notification_options_w'] = '0';
         $a_pmcontact['service_notification_options_u'] = '0';
         $a_pmcontact['service_notification_options_c'] = '0';
         $a_pmcontact['service_notification_options_r'] = '0';
         $a_pmcontact['service_notification_options_f'] = '0';
         $a_pmcontact['service_notification_options_n'] = '0';
         $a_pmcontact['host_notification_options_d'] = '0';
         $a_pmcontact['host_notification_options_u'] = '0';
         $a_pmcontact['host_notification_options_r'] = '0';
         $a_pmcontact['host_notification_options_f'] = '0';
         $a_pmcontact['host_notification_options_s'] = '0';
         $a_pmcontact['host_notification_options_n'] = '0';
         $a_pmcontact['service_notification_commands'] = '2';
         $a_pmcontact['host_notification_commands'] = '1';
      }
      $a_contacts[$i]['host_notifications_enabled'] = $a_pmcontact['host_notifications_enabled'];
      $a_contacts[$i]['service_notifications_enabled'] = $a_pmcontact['service_notifications_enabled'];

      $calendar->getFromDB($a_pmcontact['service_notification_period']);
      if (isset($calendar->fields['name'])) {
         $a_contacts[$i]['service_notification_period'] = $calendar->fields['name'];
      } else {
         $a_contacts[$i]['service_notification_period'] = '24x7';
      }

      $calendar->getFromDB($a_pmcontact['host_notification_period']);
      if (isset($calendar->fields['name'])) {
         $a_contacts[$i]['host_notification_period'] = $calendar->fields['name'];
      } else {
         $a_contacts[$i]['host_notification_period'] = '24x7';
      }

      $a_servicenotif = array();
      if ($a_pmcontact['service_notification_options_w'] == '1')
         $a_servicenotif[] = "w";
      if ($a_pmcontact['service_notification_options_u'] == '1')
         $a_servicenotif[] = "u";
      if ($a_pmcontact['service_notification_options_c'] == '1')
         $a_servicenotif[] = "c";
      if ($a_pmcontact['service_notification_options_r'] == '1')
         $a_servicenotif[] = "r";
      if ($a_pmcontact['service_notification_options_f'] == '1')
         $a_servicenotif[] = "f";
      if ($a_pmcontact['service_notification_options_n'] == '1')
         $a_servicenotif = array("n");
      if (count($a_servicenotif) == "0")
         $a_servicenotif = array("n");
      $a_contacts[$i]['service_notification_options'] = implode(",", $a_servicenotif);

      $a_hostnotif = array();
      if ($a_pmcontact['host_notification_options_d'] == '1')
         $a_hostnotif[] = "d";
      if ($a_pmcontact['host_notification_options_u'] == '1')
         $a_hostnotif[] = "u";
      if ($a_pmcontact['host_notification_options_r'] == '1')
         $a_hostnotif[] = "r";
      if ($a_pmcontact['host_notification_options_f'] == '1')
         $a_hostnotif[] = "f";
      if ($a_pmcontact['host_notification_options_s'] == '1')
         $a_hostnotif[] = "s";
      if ($a_pmcontact['host_notification_options_n'] == '1')
         $a_hostnotif = array("n");
      if (count($a_hostnotif) == "0")
         $a_hostnotif = array("n");
      $a_contacts[$i]['host_notification_options'] = implode(",", $a_hostnotif);

      $pmNotificationcommand->getFromDB($a_pmcontact['service_notification_commands']);
      if (isset($pmNotificationcommand->fields['command_name'])) {
         $a_contacts[$i]['service_notification_commands'] = PluginMonitoringCommand::$command_prefix . $pmNotificationcommand->fields['command_name'];
      } else {
         $a_contacts[$i]['service_notification_commands'] = '';
      }
      $pmNotificationcommand->getFromDB($a_pmcontact['host_notification_commands']);
      if (isset($pmNotificationcommand->fields['command_name'])) {
         $a_contacts[$i]['host_notification_commands'] = PluginMonitoringCommand::$command_prefix . $pmNotificationcommand->fields['command_name'];
      } else {
         $a_contacts[$i]['host_notification_commands'] = '';
      }

      // Get first email
      $a_emails = UserEmail::getAllForUser($users_id);
      $first = 0;
      foreach ($a_emails as $email) {
         if ($first == 0) {
            $a_contacts[$i]['email'] = $email;
         }
         $first++;
      }
      if (!isset($a_contacts[$i]['email'])) {
         $a_contacts[$i]['email'] = '';
      }
      $a_contacts[$i]['pager'] = $user->fields['phone'];

      if (isset($a_pmcontact['shinken_administrator'])) {
         $a_contacts[$i]['is_admin'] = $a_pmcontact['shinken_administrator'];
      } else {
         $a_contacts[$i]['is_admin'] = self::$shinkenParameters['webui']['contacts']['is_admin'];
      }
      if (isset($a_pmcontact['shinken_can_submit_commands'])) {
         $a_contacts[$i]['can_submit_commands'] = $a_pmcontact['shinken_can_submit_commands'];
      } else {
         $a_contacts[$i]['can_submit_commands'] = self::$shinkenParameters['webui']['contacts']['can_submit_commands'];
      }
      if (empty($user->fields['password'])) {
         $a_contacts[$i]['password'] = self::$shinkenParameters['webui']['contacts']['password'];
      } else {
         $a_contacts[$i]['password'] = $user->fields['password'];
      }

      /*
      TODO:
      address1, address2, ..., address6 are available in Shinken
      */

      return $a_contacts;
   }
 /**
  * @see NotificationTargetCommonITILObject::getDatasForObject()
  **/
 function getDatasForObject(CommonDBTM $item, array $options, $simple = false)
 {
     global $CFG_GLPI;
     // Common ITIL datas
     $datas = parent::getDatasForObject($item, $options, $simple);
     $datas['##ticket.description##'] = Html::clean($datas['##ticket.description##']);
     $datas['##ticket.description##'] = $item->convertContentForNotification($datas['##ticket.description##'], $item);
     $datas['##ticket.content##'] = $datas['##ticket.description##'];
     // Specific datas
     $datas['##ticket.urlvalidation##'] = $this->formatURL($options['additionnaloption']['usertype'], "ticket_" . $item->getField("id") . "_TicketValidation\$1");
     $datas['##ticket.globalvalidation##'] = TicketValidation::getStatus($item->getField('global_validation'));
     $datas['##ticket.type##'] = Ticket::getTicketTypeName($item->getField('type'));
     $datas['##ticket.requesttype##'] = Dropdown::getDropdownName('glpi_requesttypes', $item->getField('requesttypes_id'));
     $autoclose_value = Entity::getUsedConfig('autoclose_delay', $this->getEntity(), '', Entity::CONFIG_NEVER);
     $datas['##ticket.autoclose##'] = __('Never');
     $datas['##lang.ticket.autoclosewarning##'] = "";
     if ($autoclose_value > 0) {
         $datas['##ticket.autoclose##'] = $autoclose_value;
         $datas['##lang.ticket.autoclosewarning##'] = sprintf(_n('Without a reply, the ticket will be automatically closed after %s day', 'Without a reply, the ticket will be automatically closed after %s days', $autoclose_value), $autoclose_value);
     }
     $datas['##ticket.sla##'] = '';
     if ($item->getField('slas_id')) {
         $datas['##ticket.sla##'] = Dropdown::getDropdownName('glpi_slas', $item->getField('slas_id'));
     }
     $datas['##ticket.location##'] = '';
     if ($item->getField('locations_id')) {
         $datas['##ticket.location##'] = Dropdown::getDropdownName('glpi_locations', $item->getField('locations_id'));
     }
     // is ticket deleted
     $datas['##ticket.isdeleted##'] = Dropdown::getYesNo($item->getField('is_deleted'));
     //Tags associated with the object linked to the ticket
     $datas['##ticket.itemtype##'] = '';
     $datas['##ticket.item.name##'] = '';
     $datas['##ticket.item.serial##'] = '';
     $datas['##ticket.item.otherserial##'] = '';
     $datas['##ticket.item.location##'] = '';
     $datas['##ticket.item.contact##'] = '';
     $datas['##ticket.item.contactnumber##'] = '';
     $datas['##ticket.item.user##'] = '';
     $datas['##ticket.item.group##'] = '';
     $datas['##ticket.item.model##'] = '';
     $item_ticket = new Item_Ticket();
     $items = $item_ticket->find("`tickets_id` = '" . $item->getField('id') . "'");
     $datas['items'] = array();
     if (count($items)) {
         foreach ($items as $val) {
             if (isset($val['itemtype']) && ($hardware = getItemForItemtype($val['itemtype'])) && isset($val["items_id"]) && $hardware->getFromDB($val["items_id"])) {
                 $tmp = array();
                 //Object type
                 $tmp['##ticket.itemtype##'] = $hardware->getTypeName();
                 //Object name
                 $tmp['##ticket.item.name##'] = $hardware->getField('name');
                 //Object serial
                 if ($hardware->isField('serial')) {
                     $tmp['##ticket.item.serial##'] = $hardware->getField('serial');
                 }
                 //Object contact
                 if ($hardware->isField('contact')) {
                     $tmp['##ticket.item.contact##'] = $hardware->getField('contact');
                 }
                 //Object contact num
                 if ($hardware->isField('contact_num')) {
                     $tmp['##ticket.item.contactnumber##'] = $hardware->getField('contact_num');
                 }
                 //Object otherserial
                 if ($hardware->isField('otherserial')) {
                     $tmp['##ticket.item.otherserial##'] = $hardware->getField('otherserial');
                 }
                 //Object location
                 if ($hardware->isField('locations_id')) {
                     $tmp['##ticket.item.location##'] = Dropdown::getDropdownName('glpi_locations', $hardware->getField('locations_id'));
                 }
                 //Object user
                 if ($hardware->getField('users_id')) {
                     $user_tmp = new User();
                     if ($user_tmp->getFromDB($hardware->getField('users_id'))) {
                         $tmp['##ticket.item.user##'] = $user_tmp->getName();
                     }
                 }
                 //Object group
                 if ($hardware->getField('groups_id')) {
                     $tmp['##ticket.item.group##'] = Dropdown::getDropdownName('glpi_groups', $hardware->getField('groups_id'));
                 }
                 $modeltable = getSingular($hardware->getTable()) . "models";
                 $modelfield = getForeignKeyFieldForTable($modeltable);
                 if ($hardware->isField($modelfield)) {
                     $tmp['##ticket.item.model##'] = Dropdown::getDropdownName($modeltable, $hardware->getField($modelfield));
                 }
                 $datas['items'][] = $tmp;
             }
         }
     }
     $datas['##ticket.numberofitems##'] = count($datas['items']);
     // Get followups, log, validation, satisfaction, linked tickets
     if (!$simple) {
         // Linked tickets
         $linked_tickets = Ticket_Ticket::getLinkedTicketsTo($item->getField('id'));
         $datas['linkedtickets'] = array();
         if (count($linked_tickets)) {
             $linkedticket = new Ticket();
             foreach ($linked_tickets as $data) {
                 if ($linkedticket->getFromDB($data['tickets_id'])) {
                     $tmp = array();
                     $tmp['##linkedticket.id##'] = $data['tickets_id'];
                     $tmp['##linkedticket.link##'] = Ticket_Ticket::getLinkName($data['link']);
                     $tmp['##linkedticket.url##'] = $this->formatURL($options['additionnaloption']['usertype'], "ticket_" . $data['tickets_id']);
                     $tmp['##linkedticket.title##'] = $linkedticket->getField('name');
                     $tmp['##linkedticket.content##'] = $linkedticket->getField('content');
                     $datas['linkedtickets'][] = $tmp;
                 }
             }
         }
         $datas['##ticket.numberoflinkedtickets##'] = count($datas['linkedtickets']);
         $restrict = "`tickets_id`='" . $item->getField('id') . "'";
         $problems = getAllDatasFromTable('glpi_problems_tickets', $restrict);
         $datas['problems'] = array();
         if (count($problems)) {
             $problem = new Problem();
             foreach ($problems as $data) {
                 if ($problem->getFromDB($data['problems_id'])) {
                     $tmp = array();
                     $tmp['##problem.id##'] = $data['problems_id'];
                     $tmp['##problem.date##'] = $problem->getField('date');
                     $tmp['##problem.title##'] = $problem->getField('name');
                     $tmp['##problem.url##'] = $this->formatURL($options['additionnaloption']['usertype'], "problem_" . $data['problems_id']);
                     $tmp['##problem.content##'] = $problem->getField('content');
                     $datas['problems'][] = $tmp;
                 }
             }
         }
         $datas['##ticket.numberofproblems##'] = count($datas['problems']);
         $restrict = "`tickets_id`='" . $item->getField('id') . "'";
         $changes = getAllDatasFromTable('glpi_changes_tickets', $restrict);
         $datas['changes'] = array();
         if (count($changes)) {
             $change = new Change();
             foreach ($changes as $data) {
                 if ($change->getFromDB($data['changes_id'])) {
                     $tmp = array();
                     $tmp['##change.id##'] = $data['changes_id'];
                     $tmp['##change.date##'] = $change->getField('date');
                     $tmp['##change.title##'] = $change->getField('name');
                     $tmp['##change.url##'] = $this->formatURL($options['additionnaloption']['usertype'], "change_" . $data['changes_id']);
                     $tmp['##change.content##'] = $change->getField('content');
                     $datas['changes'][] = $tmp;
                 }
             }
         }
         $datas['##ticket.numberofchanges##'] = count($datas['changes']);
         if (!isset($options['additionnaloption']['show_private']) || !$options['additionnaloption']['show_private']) {
             $restrict .= " AND `is_private` = '0'";
         }
         $restrict .= " ORDER BY `date` DESC, `id` ASC";
         //Followup infos
         $followups = getAllDatasFromTable('glpi_ticketfollowups', $restrict);
         $datas['followups'] = array();
         foreach ($followups as $followup) {
             $tmp = array();
             $tmp['##followup.isprivate##'] = Dropdown::getYesNo($followup['is_private']);
             $tmp['##followup.author##'] = Html::clean(getUserName($followup['users_id']));
             $tmp['##followup.requesttype##'] = Dropdown::getDropdownName('glpi_requesttypes', $followup['requesttypes_id']);
             $tmp['##followup.date##'] = Html::convDateTime($followup['date']);
             $tmp['##followup.description##'] = $followup['content'];
             $datas['followups'][] = $tmp;
         }
         $datas['##ticket.numberoffollowups##'] = count($datas['followups']);
         // Approbation of solution
         $restrict .= " LIMIT 1";
         $replysolved = getAllDatasFromTable('glpi_ticketfollowups', $restrict);
         $data = current($replysolved);
         $datas['##ticket.solution.approval.description##'] = $data['content'];
         $datas['##ticket.solution.approval.date##'] = Html::convDateTime($data['date']);
         $datas['##ticket.solution.approval.author##'] = Html::clean(getUserName($data['users_id']));
         //Validation infos
         $restrict = "`tickets_id`='" . $item->getField('id') . "'";
         if (isset($options['validation_id']) && $options['validation_id']) {
             $restrict .= " AND `glpi_ticketvalidations`.`id` = '" . $options['validation_id'] . "'";
         }
         $restrict .= " ORDER BY `submission_date` DESC, `id` ASC";
         $validations = getAllDatasFromTable('glpi_ticketvalidations', $restrict);
         $datas['validations'] = array();
         foreach ($validations as $validation) {
             $tmp = array();
             $tmp['##validation.submission.title##'] = sprintf(__('An approval request has been submitted by %s'), Html::clean(getUserName($validation['users_id'])));
             $tmp['##validation.answer.title##'] = sprintf(__('An answer to an an approval request was produced by %s'), Html::clean(getUserName($validation['users_id_validate'])));
             $tmp['##validation.author##'] = Html::clean(getUserName($validation['users_id']));
             $tmp['##validation.status##'] = TicketValidation::getStatus($validation['status']);
             $tmp['##validation.storestatus##'] = $validation['status'];
             $tmp['##validation.submissiondate##'] = Html::convDateTime($validation['submission_date']);
             $tmp['##validation.commentsubmission##'] = $validation['comment_submission'];
             $tmp['##validation.validationdate##'] = Html::convDateTime($validation['validation_date']);
             $tmp['##validation.validator##'] = Html::clean(getUserName($validation['users_id_validate']));
             $tmp['##validation.commentvalidation##'] = $validation['comment_validation'];
             $datas['validations'][] = $tmp;
         }
         // Ticket Satisfaction
         $inquest = new TicketSatisfaction();
         $datas['##satisfaction.type##'] = '';
         $datas['##satisfaction.datebegin##'] = '';
         $datas['##satisfaction.dateanswered##'] = '';
         $datas['##satisfaction.satisfaction##'] = '';
         $datas['##satisfaction.description##'] = '';
         if ($inquest->getFromDB($item->getField('id'))) {
             // internal inquest
             if ($inquest->fields['type'] == 1) {
                 $datas['##ticket.urlsatisfaction##'] = $this->formatURL($options['additionnaloption']['usertype'], "ticket_" . $item->getField("id") . '_Ticket$3');
                 // external inquest
             } else {
                 if ($inquest->fields['type'] == 2) {
                     $datas['##ticket.urlsatisfaction##'] = Entity::generateLinkSatisfaction($item);
                 }
             }
             $datas['##satisfaction.type##'] = $inquest->getTypeInquestName($inquest->getfield('type'));
             $datas['##satisfaction.datebegin##'] = Html::convDateTime($inquest->fields['date_begin']);
             $datas['##satisfaction.dateanswered##'] = Html::convDateTime($inquest->fields['date_answered']);
             $datas['##satisfaction.satisfaction##'] = $inquest->fields['satisfaction'];
             $datas['##satisfaction.description##'] = $inquest->fields['comment'];
         }
     }
     return $datas;
 }
Example #19
0
 /**
  * @since version 0.90
  *
  * @param $rand
  **/
 function showTimeline($rand)
 {
     global $CFG_GLPI, $DB, $autolink_options;
     //get ticket actors
     $ticket_users_keys = $this->getTicketActors();
     $user = new User();
     $group = new Group();
     $followup_obj = new TicketFollowup();
     $pics_url = $CFG_GLPI['root_doc'] . "/pics/timeline";
     $timeline = $this->getTimelineItems();
     $autolink_options['strip_protocols'] = false;
     //display timeline
     echo "<div class='timeline_history'>";
     $tmp = array_values($timeline);
     $first_item = array_shift($tmp);
     // show approbation form on top when ticket is solved
     if ($this->fields["status"] == CommonITILObject::SOLVED) {
         echo "<div class='approbation_form' id='approbation_form{$rand}'>";
         $followup_obj->showApprobationForm($this);
         echo "</div>";
     }
     // show title for timeline
     self::showTimelineHeader();
     $timeline_index = 0;
     foreach ($timeline as $item) {
         $options = array('parent' => $this, 'rand' => $rand);
         if ($obj = getItemForItemtype($item['type'])) {
             $obj->fields = $item['item'];
         } else {
             $obj = $item;
         }
         Plugin::doHook('pre_show_item', array('item' => &$obj, 'options' => &$options));
         if (is_array($obj)) {
             $item_i = $obj['item'];
         } else {
             $item_i = $obj->fields;
         }
         $date = "";
         if (isset($item_i['date'])) {
             $date = $item_i['date'];
         }
         if (isset($item_i['date_mod'])) {
             $date = $item_i['date_mod'];
         }
         // check if curent item user is assignee or requester
         $user_position = 'left';
         if (isset($ticket_users_keys[$item_i['users_id']]) && $ticket_users_keys[$item_i['users_id']] == CommonItilActor::ASSIGN || $item['type'] == 'Assign') {
             $user_position = 'right';
         }
         //display solution in middle
         if ($timeline_index == 0 && $item['type'] == "Solution" && $this->fields["status"] == CommonITILObject::SOLVED) {
             $user_position .= ' middle';
         }
         echo "<div class='h_item {$user_position}'>";
         echo "<div class='h_info'>";
         echo "<div class='h_date'>" . Html::convDateTime($date) . "</div>";
         if ($item_i['users_id'] !== false) {
             echo "<div class='h_user'>";
             if (isset($item_i['users_id']) && $item_i['users_id'] != 0) {
                 $user->getFromDB($item_i['users_id']);
                 echo "<div class='tooltip_picture_border'>";
                 echo "<img class='user_picture' alt=\"" . __s('Picture') . "\" src='" . User::getThumbnailURLForPicture($user->fields['picture']) . "'>";
                 echo "</div>";
                 echo "<span class='h_user_name'>";
                 $userdata = getUserName($item_i['users_id'], 2);
                 echo $user->getLink() . "&nbsp;";
                 echo Html::showToolTip($userdata["comment"], array('link' => $userdata['link']));
                 echo "</span>";
             } else {
                 _e("Requester");
             }
             echo "</div>";
             // h_user
         }
         echo "</div>";
         //h_date
         echo "<div class='h_content " . $item['type'] . (isset($item_i['status']) ? " " . $item_i['status'] : "") . "'" . "id='viewitem" . $item['type'] . $item_i['id'] . $rand . "'>";
         if (isset($item_i['can_edit']) && $item_i['can_edit']) {
             echo "<div class='edit_item_content'></div>";
             echo "<span class='cancel_edit_item_content'></span>";
         }
         echo "<div class='displayed_content'>";
         if (!in_array($item['type'], array('Document_Item', 'Assign')) && $item_i['can_edit']) {
             echo "<span class='edit_item' ";
             echo "onclick='javascript:viewEditSubitem" . $this->fields['id'] . "{$rand}(event, \"" . $item['type'] . "\", " . $item_i['id'] . ", this, \"viewitem" . $item['type'] . $item_i['id'] . $rand . "\")'";
             echo "></span>";
         }
         if (isset($item_i['requesttypes_id']) && file_exists("{$pics_url}/" . $item_i['requesttypes_id'] . ".png")) {
             echo "<img src='{$pics_url}/" . $item_i['requesttypes_id'] . ".png' title='' class='h_requesttype' />";
         }
         if (isset($item_i['content'])) {
             $content = $item_i['content'];
             $content = autolink($content, 40);
             //$content = nl2br($content);
             $long_text = "";
             if (substr_count($content, "<br") > 30 || strlen($content) > 2000) {
                 $long_text = "long_text";
             }
             echo "<div class='item_content {$long_text}'>";
             echo "<p>";
             if (isset($item_i['state'])) {
                 $onClick = "onclick='change_task_state(" . $item_i['id'] . ", this)'";
                 if (!$item_i['can_edit']) {
                     $onClick = "style='cursor: not-allowed;'";
                 }
                 echo "<span class='state state_" . $item_i['state'] . "'\n                           {$onClick}\n                           title='" . Planning::getState($item_i['state']) . "'>";
                 echo "</span>";
             }
             echo $content;
             echo "</p>";
             if (!empty($long_text)) {
                 echo "<p class='read_more'>";
                 echo "<a class='read_more_button'>.....</a>";
                 echo "</p>";
             }
             echo "</div>";
         }
         echo "<div class='b_right'>";
         if (isset($item_i['solutiontypes_id']) && !empty($item_i['solutiontypes_id'])) {
             echo Dropdown::getDropdownName("glpi_solutiontypes", $item_i['solutiontypes_id']) . "<br>";
         }
         if (isset($item_i['taskcategories_id']) && !empty($item_i['taskcategories_id'])) {
             echo Dropdown::getDropdownName("glpi_taskcategories", $item_i['taskcategories_id']) . "<br>";
         }
         if (isset($item_i['requesttypes_id']) && !empty($item_i['requesttypes_id'])) {
             echo Dropdown::getDropdownName("glpi_requesttypes", $item_i['requesttypes_id']) . "<br>";
         }
         if (isset($item_i['actiontime']) && !empty($item_i['actiontime'])) {
             echo "<span class='actiontime'>";
             echo Html::timestampToString($item_i['actiontime'], false);
             echo "</span>";
         }
         if (isset($item_i['begin'])) {
             echo "<span class='planification'>";
             echo Html::convDateTime($item_i["begin"]);
             echo " &rArr; ";
             echo Html::convDateTime($item_i["end"]);
             echo "</span>";
         }
         if (isset($item_i['users_id_tech']) && $item_i['users_id_tech'] > 0) {
             echo "<div class='users_id_tech' id='users_id_tech_" . $item_i['users_id_tech'] . "'>";
             $user->getFromDB($item_i['users_id_tech']);
             echo Html::image($CFG_GLPI['root_doc'] . "/pics/user.png") . "&nbsp;";
             $userdata = getUserName($item_i['users_id_tech'], 2);
             echo $user->getLink() . "&nbsp;";
             echo Html::showToolTip($userdata["comment"], array('link' => $userdata['link']));
             echo "</div>";
         }
         if (isset($item_i['groups_id_tech']) && $item_i['groups_id_tech'] > 0) {
             echo "<div class='groups_id_tech'>";
             $group->getFromDB($item_i['groups_id_tech']);
             echo Html::image($CFG_GLPI['root_doc'] . "/pics/group.png") . "&nbsp;";
             echo $group->getLink() . "&nbsp;";
             echo Html::showToolTip($group->getComments(), array('link' => $group->getLinkURL()));
             echo "</div>";
         }
         // show "is_private" icon
         if (isset($item_i['is_private']) && $item_i['is_private']) {
             echo "<div class='private'>" . __('Private') . "</div>";
         }
         echo "</div>";
         // b_right
         if ($item['type'] == 'Document_Item') {
             $filename = $item_i['filename'];
             $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
             echo "<img src='";
             if (empty($filename)) {
                 $filename = $item_i['name'];
             }
             if (file_exists(GLPI_ROOT . "/pics/icones/{$ext}-dist.png")) {
                 echo $CFG_GLPI['root_doc'] . "/pics/icones/{$ext}-dist.png";
             } else {
                 echo "{$pics_url}/file.png";
             }
             echo "' title='file' />&nbsp;";
             echo "<a href='" . $CFG_GLPI['root_doc'] . "/front/document.send.php?docid=" . $item_i['id'] . "&tickets_id=" . $this->getID() . "' target='_blank'>{$filename}";
             if (in_array($ext, array('jpg', 'jpeg', 'png', 'bmp'))) {
                 echo "<div class='timeline_img_preview'>";
                 echo "<img src='" . $CFG_GLPI['root_doc'] . "/front/document.send.php?docid=" . $item_i['id'] . "&tickets_id=" . $this->getID() . "'/>";
                 echo "</div>";
             }
             echo "</a>";
             if (!empty($item_i['mime'])) {
                 echo "&nbsp;(" . $item_i['mime'] . ")";
             }
             echo "<a href='" . $CFG_GLPI['root_doc'] . "/front/document.form.php?id=" . $item_i['id'] . "' class='edit_document' title='" . _sx("button", "Update") . "'>";
             echo "<img src='{$pics_url}/edit.png' /></a>";
             echo "<a href='" . $CFG_GLPI['root_doc'] . "/front/ticket.form.php?delete_document&documents_id=" . $item_i['id'] . "&tickets_id=" . $this->getID() . "' class='delete_document' title='" . _sx("button", "Delete permanently") . "'>";
             echo "<img src='{$pics_url}/delete.png' /></a>";
         }
         echo "</div>";
         // displayed_content
         echo "</div>";
         //end h_content
         echo "</div>";
         //end  h_info
         $timeline_index++;
         Plugin::doHook('post_show_item', array('item' => $obj, 'options' => $options));
     }
     // end foreach timeline
     echo "<div class='break'></div>";
     // recall ticket content (not needed in classic and splitted layout)
     if (!CommonGLPI::isLayoutWithMain()) {
         echo "<div class='h_item middle'>";
         echo "<div class='h_info'>";
         echo "<div class='h_date'>" . Html::convDateTime($this->fields['date']) . "</div>";
         echo "<div class='h_user'>";
         $dem = '0';
         foreach ($DB->request("glpi_tickets_users", "`tickets_id` = " . $this->fields['id'] . " AND `type` = 1") as $req) {
             $dem = $req['users_id'];
         }
         if ((!isset($item_i['users_id_recipient']) || $item_i['users_id_recipient'] == 0) && $dem == 0) {
             _e("Requester");
         } else {
             if (isset($item_i['users_id_recipient']) && $item_i['users_id_recipient'] != 0) {
                 $user->getFromDB($this->fields['users_id_recipient']);
             } else {
                 if ($dem > 0) {
                     $requester = new User();
                     if ($requester->getFromDB($dem)) {
                         $user = $requester;
                     }
                 }
             }
             echo "<div class='tooltip_picture_border'>";
             $picture = "";
             if (isset($user->fields['picture'])) {
                 $picture = $user->fields['picture'];
             }
             echo "<img class='user_picture' alt=\"" . __s('Picture') . "\" src='" . User::getThumbnailURLForPicture($picture) . "'>";
             echo "</div>";
             echo $user->getLink();
         }
         echo "</div>";
         // h_user
         echo "</div>";
         //h_info
         echo "<div class='h_content TicketContent'>";
         echo "<div class='b_right'>" . __("Ticket recall") . "</div>";
         echo "<div class='ticket_title'>";
         echo html_entity_decode($this->fields['name']);
         echo "</div>";
         echo "<div class='ticket_description'>";
         echo $this->setSimpleTextContent($this->fields['content']);
         echo "</div>";
         echo "</div>";
         // h_content TicketContent
         echo "</div>";
         // h_item middle
         echo "<div class='break'></div>";
     }
     // end timeline
     echo "</div>";
     // h_item $user_position
     echo "<script type='text/javascript'>read_more();</script>";
 }
Example #20
0
 public function showForm($ID, $options = array())
 {
     global $CFG_GLPI, $DB;
     $this->initForm($ID, $options);
     $this->showFormHeader($options);
     $rand = mt_rand();
     $config = PluginOrderConfig::getConfig();
     $user = new User();
     if (isset($options['withtemplate']) && $options['withtemplate'] == 2) {
         $template = "newcomp";
         $datestring = sprintf(__('Created on %s'), Html::convDateTime($_SESSION["glpi_currenttime"]));
     } elseif (isset($options['withtemplate']) && $options['withtemplate'] == 1) {
         $template = "newtemplate";
         $datestring = sprintf(__('Created on %s'), Html::convDateTime($_SESSION["glpi_currenttime"]));
     } else {
         $template = false;
         $datestring = sprintf(__('Last update on %s'), Html::convDateTime($this->fields["date_mod"]));
     }
     $canedit = $this->canUpdateOrder() && $this->canUpdate() && !$this->isCanceled();
     $cancancel = self::canCancel() && $this->can($ID, UPDATE) && $this->isCanceled();
     $options['canedit'] = $canedit;
     $options['candel'] = $cancancel;
     if ($template) {
         $this->fields['order_date'] = NULL;
     }
     // Displaying OVER BUDGET ALERT
     if ($this->fields['budgets_id'] > 0) {
         self::displayAlertOverBudget(self::isOverBudget($ID));
     }
     //Display without inside table
     /* title */
     echo "<tr class='tab_bg_1'><td>" . __("Order name", "order") . "*: </td>";
     echo "<td>";
     if ($canedit) {
         $objectName = autoName($this->fields["name"], "name", $template === "newcomp", $this->getType(), $this->fields["entities_id"]);
         Html::autocompletionTextField($this, "name", array('value' => $objectName));
     } else {
         echo $this->fields["name"];
     }
     echo "</td>";
     /* date of order */
     echo "<td>" . __("Date of order", "order") . ":</td><td>";
     if ($canedit) {
         if ($this->fields["order_date"] == NULL) {
             Html::showDateFormItem("order_date", date("Y-m-d"), true, true);
         } else {
             Html::showDateFormItem("order_date", $this->fields["order_date"], true, true);
         }
     } else {
         echo Html::convDate($this->fields["order_date"]);
     }
     echo "</td></tr>";
     /* num order */
     echo "<tr class='tab_bg_1'><td>" . __("Order number", "order");
     if ($ID > 0) {
         echo "*";
     } else {
         echo " <span class='red'>*</span>";
     }
     echo ": </td>";
     echo "<td>";
     if ($canedit) {
         $objectOrder = autoName($this->fields["num_order"], "num_order", $template === "newcomp", $this->getType(), $this->fields["entities_id"]);
         Html::autocompletionTextField($this, "num_order", array('value' => $objectOrder));
     } else {
         echo $this->fields["num_order"];
     }
     echo "</td>";
     /* type order */
     echo "<td>" . __("Type") . ": </td><td>";
     if ($canedit) {
         PluginOrderOrderType::Dropdown(array('name' => "plugin_order_ordertypes_id", 'value' => $this->fields["plugin_order_ordertypes_id"]));
     } else {
         echo Dropdown::getDropdownName("glpi_plugin_order_ordertypes", $this->fields["plugin_order_ordertypes_id"]);
     }
     echo "</td></tr>";
     /* state */
     echo "<tr class='tab_bg_1'><td>" . __("Order status", "order") . ": </td>";
     echo "<td>";
     if (!$this->getID()) {
         $state = $config->getDraftState();
     } else {
         $state = $this->fields["plugin_order_orderstates_id"];
     }
     if ($canedit) {
         PluginOrderOrderState::Dropdown(array('name' => "plugin_order_orderstates_id", 'value' => $state));
     } else {
         echo Dropdown::getDropdownName("glpi_plugin_order_orderstates", $this->getState());
     }
     echo "</td>";
     /* budget */
     echo "<td>" . __("Budget") . ": </td>";
     echo "<td>";
     if ($canedit) {
         if ($config->canHideInactiveBudgets()) {
             $restrict = " (`end_date` IS NULL) OR (`end_date`> '" . date("Y-m-d") . "')";
         } else {
             $restrict = "";
         }
         Budget::Dropdown(array('name' => "budgets_id", 'value' => $this->fields["budgets_id"], 'entity' => $this->fields["entities_id"], 'comments' => true, 'condition' => $restrict, 'width' => '150px'));
     } else {
         $budget = new Budget();
         if ($this->fields["budgets_id"] > 0 && $budget->can($this->fields["budgets_id"], READ)) {
             echo $budget->getLink();
         } else {
             echo Dropdown::getDropdownName("glpi_budgets", $this->fields["budgets_id"]);
         }
     }
     echo "</td></tr>";
     /* location */
     echo "<tr class='tab_bg_1'><td>" . __("Delivery location", "order") . ": </td>";
     echo "<td>";
     if ($canedit) {
         Location::Dropdown(array('name' => "locations_id", 'value' => $this->fields["locations_id"], 'entity' => $this->fields["entities_id"]));
     } else {
         echo Dropdown::getDropdownName("glpi_locations", $this->fields["locations_id"]);
     }
     echo "</td>";
     /* payment */
     echo "<td>" . __("Payment conditions", "order") . ": </td><td>";
     if ($canedit) {
         PluginOrderOrderPayment::Dropdown(array('name' => "plugin_order_orderpayments_id", 'value' => $this->fields["plugin_order_orderpayments_id"]));
     } else {
         echo Dropdown::getDropdownName("glpi_plugin_order_orderpayments", $this->fields["plugin_order_orderpayments_id"]);
     }
     echo "</td>";
     echo "</tr>";
     /* supplier of order */
     echo "<tr class='tab_bg_1'><td>" . __("Supplier") . ": </td>";
     echo "<td>";
     if ($canedit && !$this->checkIfDetailExists($ID)) {
         $rand = mt_rand();
         Supplier::dropdown(array('name' => "suppliers_id", 'rand' => $rand, 'value' => $this->fields["suppliers_id"], 'entity' => $this->fields["entities_id"]));
         $params = array('suppliers_id' => '__VALUE__', 'fieldname' => 'contacts_id');
         Ajax::updateItemOnSelectEvent("dropdown_suppliers_id{$rand}", "show_contacts_id{$rand}", "../ajax/dropdownSupplier.php", $params);
     } else {
         $supplier = new Supplier();
         if ($supplier->can($this->fields['suppliers_id'], READ)) {
             echo $supplier->getLink();
         } else {
             echo Dropdown::getDropdownName("glpi_suppliers", $this->fields["suppliers_id"]);
         }
     }
     echo "</td>";
     /* port price */
     echo "<td>" . __("Postage", "order") . ": </td>";
     echo "<td>";
     if ($canedit) {
         echo "<input type='number' step='" . PLUGIN_ORDER_NUMBER_STEP . "' name='port_price' size='5'" . " value=\"" . Html::formatNumber($this->fields["port_price"], true) . "\">";
     } else {
         echo Html::formatNumber($this->fields["port_price"]);
     }
     echo "</td>";
     echo "</tr>";
     /* linked contact of the supplier of order */
     echo "<tr class='tab_bg_1'><td>" . __("Contact") . ": </td>";
     echo "<td><span id='show_contacts_id'>";
     if ($canedit) {
         echo "<span id='show_contacts_id{$rand}'>";
         // Make a select box
         $query = "SELECT c.`id`, c.`name`, c.`firstname`\n                   FROM `glpi_contacts` c\n                   LEFT JOIN `glpi_contacts_suppliers` s ON (s.`contacts_id` = c.`id`)\n                   WHERE s.`suppliers_id` = '{$this->fields['suppliers_id']}'\n                   ORDER BY c.`name`";
         $result = $DB->query($query);
         $number = $DB->numrows($result);
         $values = array(0 => Dropdown::EMPTY_VALUE);
         if ($number) {
             while ($data = $DB->fetch_assoc($result)) {
                 $values[$data['id']] = formatUserName('', '', $data['name'], $data['firstname']);
             }
         }
         Dropdown::showFromArray("contacts_id", $values, array('value' => $this->fields['contacts_id'], 'rand' => $rand));
         echo "</span>\n";
     } else {
         echo Dropdown::getDropdownName("glpi_contacts", $this->fields["contacts_id"]);
     }
     echo "</span></td>";
     /* tva port price */
     echo "<td>" . __("VAT", "order") . " " . __("Postage", "order") . ": </td><td>";
     $PluginOrderConfig = new PluginOrderConfig();
     $default_taxes = $PluginOrderConfig->getDefaultTaxes();
     $taxes = empty($ID) || $ID < 0 ? $default_taxes : $this->fields["plugin_order_ordertaxes_id"];
     if ($canedit) {
         PluginOrderOrderTax::Dropdown(array('name' => "plugin_order_ordertaxes_id", 'value' => $taxes, 'display_emptychoice' => true, 'emptylabel' => __("No VAT", "order")));
     } else {
         echo Dropdown::getDropdownName("glpi_plugin_order_ordertaxes", $taxes);
     }
     echo "</td>";
     echo "</tr>";
     echo "<tr class='tab_bg_1'>";
     echo "<td>" . __("Associable to a ticket") . "&nbsp;:</td><td>";
     if ($canedit) {
         Dropdown::showYesNo('is_helpdesk_visible', $this->fields['is_helpdesk_visible']);
     } else {
         echo Dropdown::getYesNo($this->fields['is_helpdesk_visible']);
     }
     echo "</td>";
     echo "<td>";
     echo __("Estimated due date", "order") . ":";
     if ($this->isDelivered() && $this->fields['deliverydate']) {
         echo "<br/>" . __("Delivery date") . ":";
     }
     echo " </td><td>";
     if ($canedit) {
         if ($this->fields["duedate"] == NULL) {
             Html::showDateFormItem("duedate", '', true, true);
         } else {
             Html::showDateFormItem("duedate", $this->fields["duedate"], true, true);
         }
     } else {
         echo Html::convDate($this->fields["duedate"]);
     }
     if ($this->shouldBeAlreadyDelivered()) {
         echo "<br/><span class='red'>" . __("Due date overtaken", "order") . "</span>";
     }
     if ($this->isDelivered() && $this->fields['deliverydate']) {
         echo "<br/>" . Html::convDate($this->fields['deliverydate']);
     }
     echo "</td>";
     echo "</tr>";
     echo "<tr class='tab_bg_1'>";
     echo "<td colspan='2' class='center'>" . $datestring;
     if (!$template && !empty($this->fields['template_name'])) {
         echo "<span class='small_space'>(" . __("Template name") . "&nbsp;: " . $this->fields['template_name'] . ")</span>";
     }
     echo "</td><td colspan='2'></td>";
     echo "</tr>";
     echo "<tr class='tab_bg_1'>";
     //comments of order
     echo "<td>" . __("Comments") . ":  </td>";
     echo "<td colspan='3' align='center'>";
     if ($canedit) {
         echo "<textarea cols='40' rows='3' name='comment'>" . $this->fields["comment"] . "</textarea>";
     } else {
         echo $this->fields["comment"];
     }
     echo "</td></tr>";
     echo "<tr class='tab_bg_1'>";
     echo "<th colspan='2'>" . __("Actor") . "</th>";
     if ($ID > 0 && !$template) {
         echo "<th colspan='2'>" . __("Cost") . "</th></tr>";
     } else {
         echo "<th colspan='2'></th>";
     }
     echo "</tr>";
     echo "<tr class='tab_bg_1'>";
     echo "<td colspan='2'>";
     echo "<table class='format'>";
     echo "<tr class='tab_bg_1'><td>" . __("Author") . ":</td><td style='width: 170px;'>";
     if ($canedit) {
         if ($template == 'newcomp') {
             $value = Session::getLoginUserID();
         } else {
             $value = $this->fields['users_id'];
         }
         User::Dropdown(array('name' => 'users_id', 'value' => $value, 'right' => 'interface', 'entity' => $this->fields["entities_id"], 'width' => '150px'));
     } else {
         if ($this->fields['users_id']) {
             $output = "";
             if ($user->getFromDB($this->fields['users_id'])) {
                 $output = formatUserName($this->fields['users_id'], $user->fields['name'], $user->fields['realname'], $user->fields['firstname']);
             }
             echo $output;
         }
     }
     echo "</td>";
     echo "<td>" . __("Author group", "order") . ":</td>";
     echo "<td style='width: 180px;'>";
     if ($canedit) {
         if (empty($ID) || $ID < 0) {
             if (!empty($this->fields['groups_id'])) {
                 $groups_id = $this->fields['groups_id'];
             } else {
                 $groups_id = $config->getDefaultAuthorGroup();
             }
         } else {
             $groups_id = $this->fields['groups_id'];
         }
         Group::Dropdown(array('value' => $groups_id, 'width' => '150px'));
     } else {
         echo Dropdown::getDropdownName('glpi_groups', $this->fields['groups_id']);
     }
     echo "</td></tr>";
     echo "<tr class='tab_bg_1'>";
     echo "<td>" . __("Recipient") . ":</td>";
     echo "<td style='width: 170px;'>";
     if ($canedit) {
         if (empty($ID) || $ID < 0) {
             if (!empty($this->fields['users_id_delivery'])) {
                 $users_id = $this->fields['users_id_delivery'];
             } else {
                 $users_id = $config->getDefaultRecipient();
             }
         } else {
             $users_id = $this->fields['users_id_delivery'];
         }
         User::Dropdown(array('name' => 'users_id_delivery', 'value' => $users_id, 'right' => 'all', 'entity' => $this->fields["entities_id"], 'width' => '150px'));
     } else {
         if ($this->fields['users_id_delivery']) {
             $user->getFromDB($this->fields['users_id_delivery']);
             $output = formatUserName($this->fields['users_id'], $user->fields['name'], $user->fields['realname'], $user->fields['firstname']);
             echo $output;
         }
     }
     echo "</td>";
     echo "<td>" . __("Recipient group", "order") . ":</td>";
     echo "<td style='width: 180px;'>";
     if ($canedit) {
         if (empty($ID) || $ID < 0) {
             if (!empty($this->fields['groups_id_delivery'])) {
                 $groups_id = $this->fields['groups_id_delivery'];
             } else {
                 $groups_id = $config->getDefaultRecipientGroup();
             }
         } else {
             $groups_id = $this->fields['groups_id_delivery'];
         }
         Group::Dropdown(array('name' => 'groups_id_delivery', 'value' => $groups_id, 'width' => '150px'));
     } else {
         echo Dropdown::getDropdownName('glpi_groups', $this->fields['groups_id_delivery']);
     }
     echo "</td>";
     echo "</tr></table></td>";
     echo "<td colspan='2'>";
     if ($ID > 0 && !$template) {
         $PluginOrderOrder_Item = new PluginOrderOrder_Item();
         $prices = $PluginOrderOrder_Item->getAllPrices($ID);
         echo "<table class='format'>";
         echo "<tr>";
         echo "<td>" . __("Price tax free", "order") . "</td>";
         echo "<td>" . Html::formatNumber($prices["priceHT"]) . "</td>";
         echo "</tr>";
         // total price (with postage)
         $postagewithTVA = $PluginOrderOrder_Item->getPricesATI($this->fields["port_price"], Dropdown::getDropdownName("glpi_plugin_order_ordertaxes", $this->fields["plugin_order_ordertaxes_id"]));
         $priceHTwithpostage = $prices["priceHT"] + $this->fields["port_price"];
         echo "<tr>";
         echo "<td>" . __("Price tax free with postage", "order") . "</td>";
         echo "<td>" . Html::formatNumber($priceHTwithpostage) . "</td>";
         echo "</tr>";
         // total price (with taxes)
         $total = $prices["priceTTC"] + $postagewithTVA;
         echo "<tr>";
         echo "<td>" . __("Price ATI", "order") . "</td>";
         echo "<td>" . Html::formatNumber($total) . "</td>";
         echo "</tr>";
         // total TVA
         $total_tva = $prices["priceTVA"] + ($postagewithTVA - $this->fields["port_price"]);
         echo "<tr>";
         echo "<td>" . __("VAT", "order") . "</td>";
         echo "<td>" . Html::formatNumber($total_tva) . "</td>";
         echo "</tr>";
         echo "</table>";
     }
     echo "</td>";
     echo "</tr>";
     if ($canedit || $cancancel) {
         $this->showFormButtons($options);
     } else {
         echo "</table></div>";
         Html::closeForm();
     }
     return true;
 }
Example #21
0
 /**
  * @see Rule::executeActions()
  **/
 function executeActions($output, $params)
 {
     if (count($this->actions)) {
         foreach ($this->actions as $action) {
             switch ($action->fields["action_type"]) {
                 case "assign":
                     switch ($action->fields["field"]) {
                         default:
                             $output[$action->fields["field"]] = $action->fields["value"];
                             break;
                         case "_affect_entity_by_user_entity":
                             //3 cases :
                             //1 - rule contains a criteria like : Profil is XXXX
                             //    -> in this case, profiles_id is stored in
                             //       $this->criterias_results['PROFILES'] (one value possible)
                             //2-   rule contains criteria "User has only one profile"
                             //    -> in this case, profiles_id is stored in
                             //       $this->criterias_results['PROFILES'] (one value possible) (same as 1)
                             //3   -> rule contains only one profile
                             $profile = 0;
                             //Case 2:
                             if (isset($this->criterias_results['ONE_PROFILE'])) {
                                 $profile = $this->criterias_results['ONE_PROFILE'];
                                 //Case 3
                             } else {
                                 if (isset($this->criterias_results['UNIQUE_PROFILE'])) {
                                     $profile = $this->criterias_results['UNIQUE_PROFILE'];
                                     //Case 1
                                 } else {
                                     if (isset($this->criterias_results['PROFILES'])) {
                                         $profile = $this->criterias_results['PROFILES'];
                                     }
                                 }
                             }
                             if ($profile) {
                                 $entities = array();
                                 if (isset($params['_users_id_requester'])) {
                                     // Not set when testing
                                     $entities = Profile_User::getEntitiesForProfileByUser($params['_users_id_requester'], $profile);
                                 }
                                 //Case 2 : check if there's only one profile for this user
                                 if (isset($this->criterias_results['ONE_PROFILE']) && count($entities) == 1 || !isset($this->criterias_results['ONE_PROFILE'])) {
                                     if (count($entities) == 1) {
                                         //User has right on only one entity
                                         $output['entities_id'] = array_pop($entities);
                                     } else {
                                         if (isset($this->criterias_results['UNIQUE_PROFILE'])) {
                                             $output['entities_id'] = array_pop($entities);
                                         } else {
                                             //Rights on more than one entity : get the user's prefered entity
                                             if (isset($params['_users_id_requester'])) {
                                                 // Not set when testing
                                                 $user = new User();
                                                 $user->getFromDB($params['_users_id_requester']);
                                                 $tmpid = $user->getField('entities_id');
                                                 // Retrieve all the entities (pref could be set on a child)
                                                 $entities = Profile_User::getEntitiesForProfileByUser($params['_users_id_requester'], $profile, true);
                                                 // If an entity is defined in user's preferences,
                                                 // and this entity allowed for this profile, use this one
                                                 // else do not set the rule as matched
                                                 if (in_array($tmpid, $entities)) {
                                                     $output['entities_id'] = $user->fields['entities_id'];
                                                 }
                                             }
                                         }
                                     }
                                 }
                             }
                     }
                     break;
                 case "regex_result":
                     foreach ($this->regex_results as $regex_result) {
                         $entity_found = -1;
                         $res = RuleAction::getRegexResultById($action->fields["value"], $regex_result);
                         if ($res != null) {
                             switch ($action->fields["field"]) {
                                 case "_affect_entity_by_domain":
                                     $entity_found = Entity::getEntityIDByDomain(addslashes($res));
                                     break;
                                 case "_affect_entity_by_tag":
                                     $entity_found = Entity::getEntityIDByTag(addslashes($res));
                                     break;
                             }
                             //If an entity was found
                             if ($entity_found > -1) {
                                 $output['entities_id'] = $entity_found;
                                 break;
                             }
                         }
                     }
                     // switch (field)
                     break;
             }
         }
     }
     return $output;
 }
 /**
  * @param $item         CommonGLPI object
  * @param $tabnum       (default 1)
  * @param $withtemplate (default 0)
  **/
 static function displayTabContentForItem(CommonGLPI $item, $tabnum = 1, $withtemplate = 0)
 {
     global $CFG_GLPI;
     if ($item->getType() == 'Preference') {
         $config = new self();
         $user = new User();
         if ($user->getFromDB(Session::getLoginUserID())) {
             $user->computePreferences();
             $config->showFormUserPrefs($user->fields);
         }
     } else {
         if ($item->getType() == 'User') {
             $config = new self();
             $item->computePreferences();
             $config->showFormUserPrefs($item->fields);
         } else {
             if ($item->getType() == __CLASS__) {
                 switch ($tabnum) {
                     case 1:
                         $item->showFormDisplay();
                         break;
                     case 2:
                         $item->showFormUserPrefs($CFG_GLPI);
                         break;
                     case 3:
                         $item->showFormInventory();
                         break;
                     case 4:
                         $item->showFormHelpdesk();
                         break;
                     case 5:
                         $item->showSystemInformations();
                         break;
                     case 6:
                         $item->showFormDBSlave();
                         break;
                 }
             }
         }
     }
     return true;
 }
 /**
  * Get all data needed for template processing
  *
  * @param $event
  * @param $options   array
  **/
 function getDatasForTemplate($event, $options = array())
 {
     global $CFG_GLPI;
     $events = $this->getEvents();
     $object = getItemForItemtype($options['item']->fields['itemtype']);
     $object->getFromDB($options['item']->fields['items_id']);
     $user = new User();
     $user->getFromDB($options['item']->fields['users_id']);
     $this->datas['##objectlock.action##'] = $events[$event];
     $this->datas['##objectlock.name##'] = $object->fields['name'];
     $this->datas['##objectlock.id##'] = $options['item']->fields['items_id'];
     $this->datas['##objectlock.type##'] = $options['item']->fields['itemtype'];
     $this->datas['##objectlock.date_mod##'] = Html::convDateTime($options['item']->fields['date_mod'], $user->fields['date_format']);
     $this->datas['##objectlock.lockedby.lastname##'] = $user->fields['realname'];
     $this->datas['##objectlock.lockedby.firstname##'] = $user->fields['firstname'];
     $this->datas['##objectlock.requester.lastname##'] = $_SESSION['glpirealname'];
     $this->datas['##objectlock.requester.firstname##'] = $_SESSION['glpifirstname'];
     $this->datas['##objectlock.url##'] = $CFG_GLPI['url_base'] . "/?redirect=" . $options['item']->fields['itemtype'] . "_" . $options['item']->fields['items_id'];
     $this->getTags();
     foreach ($this->tag_descriptions[NotificationTarget::TAG_LANGUAGE] as $tag => $values) {
         if (!isset($this->datas[$tag])) {
             $this->datas[$tag] = $values['label'];
         }
     }
 }
Example #24
0
 /**
  * Display a reservation
  *
  * @param $ID     ID a the reservation item
  * @param $date   date to display
  **/
 static function displayReservationsForAnItem($ID, $date)
 {
     global $DB;
     $users_id = Session::getLoginUserID();
     $resa = new self();
     $user = new User();
     list($year, $month, $day) = explode("-", $date);
     $debut = $date . " 00:00:00";
     $fin = $date . " 23:59:59";
     $query = "SELECT *\n                FROM `glpi_reservations`\n                WHERE '" . $debut . "' < `end`\n                      AND '" . $fin . "' > `begin`\n                      AND `reservationitems_id` = '{$ID}'\n                ORDER BY `begin`";
     if ($result = $DB->query($query)) {
         if ($DB->numrows($result) > 0) {
             echo "<table width='100%'>";
             while ($row = $DB->fetch_assoc($result)) {
                 echo "<tr>";
                 $user->getFromDB($row["users_id"]);
                 $display = "";
                 if ($debut > $row['begin']) {
                     $heure_debut = "00:00";
                 } else {
                     $heure_debut = get_hour_from_sql($row['begin']);
                 }
                 if ($fin < $row['end']) {
                     $heure_fin = "24:00";
                 } else {
                     $heure_fin = get_hour_from_sql($row['end']);
                 }
                 if (strcmp($heure_debut, "00:00") == 0 && strcmp($heure_fin, "24:00") == 0) {
                     $display = __('Day');
                 } else {
                     if (strcmp($heure_debut, "00:00") == 0) {
                         $display = sprintf(__('To %s'), $heure_fin);
                     } else {
                         if (strcmp($heure_fin, "24:00") == 0) {
                             $display = sprintf(__('From %s'), $heure_debut);
                         } else {
                             $display = $heure_debut . "-" . $heure_fin;
                         }
                     }
                 }
                 $rand = mt_rand();
                 $modif = $modif_end = "";
                 if ($resa->canEdit($row['id'])) {
                     $modif = "<a id='content_" . $ID . $rand . "'\n                                  href='reservation.form.php?id=" . $row['id'] . "'>";
                     $modif_end = "</a>";
                     $modif_end .= Html::showToolTip($row["comment"], array('applyto' => "content_" . $ID . $rand, 'display' => false));
                 }
                 echo "<td class='tab_resa center'>" . $modif . "<span>" . $display . "<br><span class='b'>" . formatUserName($user->fields["id"], $user->fields["name"], $user->fields["realname"], $user->fields["firstname"]);
                 echo "</span></span>";
                 echo $modif_end;
                 echo "</td></tr>\n";
             }
             echo "</table>\n";
         }
     }
 }
Example #25
0
 function post_addItem()
 {
     global $CFG_GLPI;
     $job = new Ticket();
     $mailsend = false;
     if ($job->getFromDB($this->fields["tickets_id"])) {
         // Set global validation to waiting
         if ($job->fields['global_validation'] == 'accepted' || $job->fields['global_validation'] == 'none') {
             $input['id'] = $this->fields["tickets_id"];
             $input['global_validation'] = 'waiting';
             // to fix lastupdater
             if (isset($this->input['_auto_update'])) {
                 $input['_auto_update'] = $this->input['_auto_update'];
             }
             // to know update by rules
             if (isset($this->input["_rule_process"])) {
                 $input['_rule_process'] = $this->input["_rule_process"];
             }
             // No update ticket notif on ticket add
             if (isset($this->input["_ticket_add"])) {
                 $input['_disablenotif'] = true;
             }
             $job->update($input);
         }
         if ($CFG_GLPI["use_mailing"]) {
             $options = array('validation_id' => $this->fields["id"], 'validation_status' => $this->fields["status"]);
             $mailsend = NotificationEvent::raiseEvent('validation', $job, $options);
         }
         if ($mailsend) {
             $user = new User();
             $user->getFromDB($this->fields["users_id_validate"]);
             $email = $user->getDefaultEmail();
             if (!empty($email)) {
                 //TRANS: %s is the user name
                 Session::addMessageAfterRedirect(sprintf(__('Approval request send to %s'), $user->getName()));
             } else {
                 Session::addMessageAfterRedirect(sprintf(__('The selected user (%s) has no valid email address. The request has been created, without email confirmation.'), $user->getName()), false, ERROR);
             }
         }
     }
     parent::post_addItem();
 }
Example #26
0
 /**
  * Show items for the group
  *
  * @param $tech   boolean  false search groups_id, true, search groups_id_tech
  **/
 function showItems($tech)
 {
     global $DB, $CFG_GLPI;
     $rand = mt_rand();
     $ID = $this->fields['id'];
     if ($tech) {
         $types = $CFG_GLPI['linkgroup_tech_types'];
         $field = 'groups_id_tech';
         $title = __('Managed items');
     } else {
         $types = $CFG_GLPI['linkgroup_types'];
         $field = 'groups_id';
         $title = __('Used items');
     }
     $tree = Session::getSavedOption(__CLASS__, 'tree', 0);
     $user = Session::getSavedOption(__CLASS__, 'user', 0);
     $type = Session::getSavedOption(__CLASS__, 'onlytype', '');
     if (!in_array($type, $types)) {
         $type = '';
     }
     echo "<div class='spaced'>";
     // Mini Search engine
     echo "<table class='tab_cadre_fixe'>";
     echo "<tr class='tab_bg_1'><th colspan='3'>{$title}</tr>";
     echo "<tr class='tab_bg_1'><td class='center'>";
     echo __('Type') . "&nbsp;";
     Dropdown::showItemType($types, array('value' => $type, 'name' => 'onlytype', 'plural' => true, 'on_change' => 'reloadTab("start=0&onlytype="+this.value)', 'checkright' => true));
     if ($this->haveChildren()) {
         echo "</td><td class='center'>" . __('Child groups') . "&nbsp;";
         Dropdown::showYesNo('tree', $tree, -1, array('on_change' => 'reloadTab("start=0&tree="+this.value)'));
     } else {
         $tree = 0;
     }
     if ($this->getField('is_usergroup')) {
         echo "</td><td class='center'>" . User::getTypeName(Session::getPluralNumber()) . "&nbsp;";
         Dropdown::showYesNo('user', $user, -1, array('on_change' => 'reloadTab("start=0&user="+this.value)'));
     } else {
         $user = 0;
     }
     echo "</td></tr></table>";
     $datas = array();
     if ($type) {
         $types = array($type);
     }
     $start = isset($_GET['start']) ? intval($_GET['start']) : 0;
     $nb = $this->getDataItems($types, $field, $tree, $user, $start, $datas);
     $nbcan = 0;
     if ($nb) {
         Html::printAjaxPager('', $start, $nb);
         Html::openMassiveActionsForm('mass' . __CLASS__ . $rand);
         echo Html::hidden('field', array('value' => $field, 'data-glpicore-ma-tags' => 'common'));
         $massiveactionparams = array('num_displayed' => $nb, 'check_itemtype' => 'Group', 'check_items_id' => $ID, 'container' => 'mass' . __CLASS__ . $rand, 'extraparams' => array('is_tech' => $tech, 'massive_action_fields' => array('field')), 'specific_actions' => array(__CLASS__ . MassiveAction::CLASS_ACTION_SEPARATOR . 'changegroup' => __('Move')));
         Html::showMassiveActions($massiveactionparams);
         echo "<table class='tab_cadre_fixehov'>";
         $header_begin = "<tr><th width='10'>";
         $header_top = Html::getCheckAllAsCheckbox('mass' . __CLASS__ . $rand);
         $header_bottom = Html::getCheckAllAsCheckbox('mass' . __CLASS__ . $rand);
         $header_end = '</th>';
         $header_end .= "<th>" . __('Type') . "</th><th>" . __('Name') . "</th><th>" . __('Entity') . "</th>";
         if ($tree || $user) {
             $header_end .= "<th>" . sprintf(__('%1$s / %2$s'), self::getTypeName(1), User::getTypeName(1)) . "</th>";
         }
         $header_end .= "</tr>";
         echo $header_begin . $header_top . $header_end;
         $tuser = new User();
         $group = new Group();
         foreach ($datas as $data) {
             if (!($item = getItemForItemtype($data['itemtype']))) {
                 continue;
             }
             echo "<tr class='tab_bg_1'><td>";
             if ($item->canEdit($data['items_id'])) {
                 Html::showMassiveActionCheckBox($data['itemtype'], $data['items_id']);
             }
             echo "</td><td>" . $item->getTypeName(1);
             echo "</td><td>" . $item->getLink(array('comments' => true));
             echo "</td><td>" . Dropdown::getDropdownName("glpi_entities", $item->getEntityID());
             if ($tree || $user) {
                 echo "</td><td>";
                 if ($grp = $item->getField($field)) {
                     if ($group->getFromDB($grp)) {
                         echo $group->getLink(array('comments' => true));
                     }
                 } else {
                     if ($usr = $item->getField(str_replace('groups', 'users', $field))) {
                         if ($tuser->getFromDB($usr)) {
                             echo $tuser->getLink(array('comments' => true));
                         }
                     }
                 }
             }
             echo "</td></tr>";
         }
         echo $header_begin . $header_bottom . $header_end;
         echo "</table>";
     } else {
         echo "<p class='center b'>" . __('No item found') . "</p>";
     }
     if ($nb) {
         $massiveactionparams['ontop'] = false;
         Html::showMassiveActions($massiveactionparams);
     }
     Html::closeForm();
     if ($nb) {
         Html::printAjaxPager('', $start, $nb);
     }
     echo "</div>";
 }
 /**
  * show tooltip for user notification information
  *
  * @param $type      integer  user type
  * @param $canedit   boolean  can edit ?
  * @param $options   array    options for default values ($options of showForm)
  *
  * @return nothing display
  **/
 function showUsersAssociated($type, $canedit, array $options = array())
 {
     global $CFG_GLPI;
     $showuserlink = 0;
     if (User::canView()) {
         $showuserlink = 2;
     }
     $usericon = self::getActorIcon('user', $type);
     $user = new User();
     $linkuser = new $this->userlinkclass();
     $itemtype = $this->getType();
     $typename = self::getActorFieldNameType($type);
     $candelete = true;
     $mandatory = '';
     // For ticket templates : mandatories
     if ($itemtype == 'Ticket' && isset($options['_tickettemplate'])) {
         $mandatory = $options['_tickettemplate']->getMandatoryMark("_users_id_" . $typename);
         if ($options['_tickettemplate']->isMandatoryField("_users_id_" . $typename) && isset($this->users[$type]) && count($this->users[$type]) == 1) {
             $candelete = false;
         }
     }
     if (isset($this->users[$type]) && count($this->users[$type])) {
         foreach ($this->users[$type] as $d) {
             $k = $d['users_id'];
             echo "{$mandatory}{$usericon}&nbsp;";
             if ($k) {
                 $userdata = getUserName($k, 2);
             } else {
                 $email = $d['alternative_email'];
                 $userdata = "<a href='mailto:{$email}'>{$email}</a>";
             }
             if ($k) {
                 $param = array('display' => false);
                 if ($showuserlink) {
                     $param['link'] = $userdata["link"];
                 }
                 echo $userdata['name'] . "&nbsp;" . Html::showToolTip($userdata["comment"], $param);
             } else {
                 echo $userdata;
             }
             if ($CFG_GLPI['use_mailing']) {
                 $text = __('Email followup') . "&nbsp;" . Dropdown::getYesNo($d['use_notification']) . '<br>';
                 if ($d['use_notification']) {
                     $uemail = $d['alternative_email'];
                     if (empty($uemail) && $user->getFromDB($d['users_id'])) {
                         $uemail = $user->getDefaultEmail();
                     }
                     $text .= sprintf(__('%1$s: %2$s'), __('Email'), $uemail);
                     if (!NotificationMail::isUserAddressValid($uemail)) {
                         $text .= "&nbsp;<span class='red'>" . __('Invalid email address') . "</span>";
                     }
                 }
                 echo "&nbsp;";
                 if ($canedit || $d['users_id'] == Session::getLoginUserID()) {
                     $opt = array('img' => $CFG_GLPI['root_doc'] . '/pics/edit.png', 'popup' => $linkuser->getFormURL() . "?id=" . $d['id']);
                     Html::showToolTip($text, $opt);
                 }
             }
             if ($canedit && $candelete) {
                 echo "&nbsp;";
                 Html::showSimpleForm($linkuser->getFormURL(), 'delete', _x('button', 'Delete permanently'), array('id' => $d['id']), $CFG_GLPI["root_doc"] . "/pics/delete.png");
             }
             echo "<br>";
         }
     }
 }
Example #28
0
 /**
  * Get entities for which a user have a right
  *
  * @param $user_ID         user ID
  * @param $is_recursive    check also using recursive rights (true by default)
  * @param $default_first   user default entity first (false by default)
  *
  * @return array of entities ID
  **/
 static function getUserEntities($user_ID, $is_recursive = true, $default_first = false)
 {
     global $DB;
     $query = "SELECT DISTINCT `entities_id`, `is_recursive`\n                FROM `glpi_profiles_users`\n                WHERE `users_id` = '{$user_ID}'";
     $result = $DB->query($query);
     if ($DB->numrows($result) > 0) {
         $entities = array();
         while ($data = $DB->fetch_assoc($result)) {
             if ($data['is_recursive'] && $is_recursive) {
                 $tab = getSonsOf('glpi_entities', $data['entities_id']);
                 $entities = array_merge($tab, $entities);
             } else {
                 $entities[] = $data['entities_id'];
             }
         }
         // Set default user entity at the begin
         if ($default_first) {
             $user = new User();
             if ($user->getFromDB($user_ID)) {
                 $ent = $user->getField('entities_id');
                 if (in_array($ent, $entities)) {
                     array_unshift($entities, $ent);
                 }
             }
         }
         return array_unique($entities);
     }
     return array();
 }
Example #29
0
 static function showListForUser($userID)
 {
     global $DB, $CFG_GLPI, $LANG;
     if (!haveRight("show_all_ticket", "1")) {
         return false;
     }
     $query = "SELECT " . self::getCommonSelect() . "\n                FROM `glpi_tickets` " . self::getCommonLeftJoin() . "\n                WHERE (`glpi_tickets_users`.`users_id` = '{$userID}'\n                        AND `glpi_tickets_users`.`type` = " . self::REQUESTER . ") " . getEntitiesRestrictRequest("AND", "glpi_tickets") . "\n                ORDER BY `glpi_tickets`.`date_mod` DESC\n                LIMIT " . intval($_SESSION['glpilist_limit']);
     $result = $DB->query($query);
     $number = $DB->numrows($result);
     echo "<div class='spaced'><table class='tab_cadre_fixe'>";
     if ($number > 0) {
         $user = new User();
         $user->getFromDB($userID);
         initNavigateListItems('Ticket', $LANG['common'][34] . " = " . $user->getName());
         $options['reset'] = 'reset';
         $options['field'][0] = 4;
         // status
         $options['searchtype'][0] = 'equals';
         $options['contains'][0] = $userID;
         $options['link'][0] = 'AND';
         echo "<tr><th colspan='11'>";
         if ($number == 1) {
             echo $LANG['job'][10] . "&nbsp;:&nbsp;" . $number;
             echo "<span class='small_space'><a href='" . $CFG_GLPI["root_doc"] . "/front/ticket.php?" . append_params($options, '&amp;') . "'>" . $LANG['buttons'][40] . "</a></SPAN>";
         } else {
             echo $LANG['job'][8] . "&nbsp;:&nbsp;" . $number;
             echo "<span class='small_space'><a href='" . $CFG_GLPI["root_doc"] . "/front/ticket.php?" . append_params($options, '&amp;') . "'>" . $LANG['buttons'][40] . "</a></SPAN>";
         }
         echo "</th></tr>";
         self::commonListHeader(HTML_OUTPUT);
         while ($data = $DB->fetch_assoc($result)) {
             addToNavigateListItems('Ticket', $data["id"]);
             self::showShort($data["id"], 0);
         }
     } else {
         echo "<tr><th>" . $LANG['joblist'][8] . "</th></tr>";
     }
     echo "</table></div>";
 }
Example #30
0
 function prepareInputForAdd($input)
 {
     global $CFG_GLPI;
     // save value before clean;
     $title = ltrim($input['name']);
     // Standard clean datas
     $input = parent::prepareInputForAdd($input);
     // Do not check mandatory on auto import (mailgates)
     if (!isset($input['_auto_import'])) {
         if (isset($input['_tickettemplates_id']) && $input['_tickettemplates_id']) {
             $tt = new TicketTemplate();
             if ($tt->getFromDBWithDatas($input['_tickettemplates_id'])) {
                 if (count($tt->mandatory)) {
                     $mandatory_missing = array();
                     $fieldsname = $tt->getAllowedFieldsNames(true);
                     foreach ($tt->mandatory as $key => $val) {
                         // for title if mandatory (restore initial value)
                         if ($key == 'name') {
                             $input['name'] = $title;
                         }
                         // Check only defined values : Not defined not in form
                         if (isset($input[$key])) {
                             // If content is also predefined need to be different from predefined value
                             if ($key == 'content' && isset($tt->predefined['content'])) {
                                 // Clean new lines to be fix encoding
                                 if (strcmp(preg_replace("/\r?\n/", "", Html::cleanPostForTextArea($input[$key])), preg_replace("/\r?\n/", "", $tt->predefined['content'])) == 0) {
                                     $mandatory_missing[$key] = $fieldsname[$val];
                                 }
                             }
                             if (empty($input[$key]) || $input[$key] == 'NULL') {
                                 $mandatory_missing[$key] = $fieldsname[$val];
                             }
                         }
                         // For due_date : check also slas_id
                         if ($key == 'due_date' && isset($input['slas_id']) && $input['slas_id'] > 0 && isset($mandatory_missing['due_date'])) {
                             unset($mandatory_missing['due_date']);
                         }
                     }
                     if (count($mandatory_missing)) {
                         //TRANS: %s are the fields concerned
                         $message = sprintf(__('Mandatory fields are not filled. Please correct: %s'), implode(", ", $mandatory_missing));
                         Session::addMessageAfterRedirect($message, false, ERROR);
                         return false;
                     }
                 }
             }
         }
     }
     if (!isset($input["requesttypes_id"])) {
         $input["requesttypes_id"] = RequestType::getDefault('helpdesk');
     }
     if (!isset($input['global_validation'])) {
         $input['global_validation'] = 'none';
     }
     // Set additional default dropdown
     $dropdown_fields = array('items_id', 'items_locations', 'users_locations');
     foreach ($dropdown_fields as $field) {
         if (!isset($input[$field])) {
             $input[$field] = 0;
         }
     }
     if (!isset($input['itemtype']) || !($input['items_id'] > 0)) {
         $input['itemtype'] = '';
     }
     $item = NULL;
     if ($input["items_id"] > 0 && !empty($input["itemtype"])) {
         if ($item = getItemForItemtype($input["itemtype"])) {
             if ($item->getFromDB($input["items_id"])) {
                 if ($item->isField('locations_id')) {
                     $input['items_locations'] = $item->fields['locations_id'];
                 }
             } else {
                 $item = NULL;
             }
         }
     }
     // Business Rules do not override manual SLA
     $manual_slas_id = 0;
     if (isset($input['slas_id']) && $input['slas_id'] > 0) {
         $manual_slas_id = $input['slas_id'];
     }
     // Process Business Rules
     $rules = new RuleTicketCollection($input['entities_id']);
     // Set unset variables with are needed
     $user = new User();
     if (isset($input["_users_id_requester"]) && $user->getFromDB($input["_users_id_requester"])) {
         $input['users_locations'] = $user->fields['locations_id'];
         $tmprequester = $input["_users_id_requester"];
     } else {
         $tmprequester = 0;
     }
     // Clean new lines before passing to rules
     if (isset($input["content"])) {
         $input["content"] = preg_replace('/\\\\r\\\\n/', "\n", $input['content']);
         $input["content"] = preg_replace('/\\\\n/', "\n", $input['content']);
     }
     $input = $rules->processAllRules(Toolbox::stripslashes_deep($input), Toolbox::stripslashes_deep($input), array('recursive' => true));
     // Recompute default values based on values computed by rules
     $input = $this->computeDefaultValuesForAdd($input);
     if (isset($input['_users_id_requester']) && $input['_users_id_requester'] != $tmprequester) {
         // if requester set by rule, clear address from mailcollector
         unset($input['_users_id_requester_notif']);
     }
     // Restore slas_id
     if ($manual_slas_id > 0) {
         $input['slas_id'] = $manual_slas_id;
     }
     // Manage auto assign
     $auto_assign_mode = Entity::getUsedConfig('auto_assign_mode', $input['entities_id']);
     switch ($auto_assign_mode) {
         case Entity::CONFIG_NEVER:
             break;
         case Entity::AUTO_ASSIGN_HARDWARE_CATEGORY:
             if ($item != NULL) {
                 // Auto assign tech from item
                 if ((!isset($input['_users_id_assign']) || $input['_users_id_assign'] == 0) && $item->isField('users_id_tech')) {
                     $input['_users_id_assign'] = $item->getField('users_id_tech');
                 }
                 // Auto assign group from item
                 if ((!isset($input['_groups_id_assign']) || $input['_groups_id_assign'] == 0) && $item->isField('groups_id_tech')) {
                     $input['_groups_id_assign'] = $item->getField('groups_id_tech');
                 }
             }
             // Auto assign tech/group from Category
             if ($input['itilcategories_id'] > 0 && (!isset($input['_users_id_assign']) || !$input['_users_id_assign'] || (!isset($input['_groups_id_assign']) || !$input['_groups_id_assign']))) {
                 $cat = new ITILCategory();
                 $cat->getFromDB($input['itilcategories_id']);
                 if ((!isset($input['_users_id_assign']) || !$input['_users_id_assign']) && $cat->isField('users_id')) {
                     $input['_users_id_assign'] = $cat->getField('users_id');
                 }
                 if ((!isset($input['_groups_id_assign']) || !$input['_groups_id_assign']) && $cat->isField('groups_id')) {
                     $input['_groups_id_assign'] = $cat->getField('groups_id');
                 }
             }
             break;
         case Entity::AUTO_ASSIGN_CATEGORY_HARDWARE:
             // Auto assign tech/group from Category
             if ($input['itilcategories_id'] > 0 && (!isset($input['_users_id_assign']) || !$input['_users_id_assign'] || (!isset($input['_groups_id_assign']) || !$input['_groups_id_assign']))) {
                 $cat = new ITILCategory();
                 $cat->getFromDB($input['itilcategories_id']);
                 if ((!isset($input['_users_id_assign']) || !$input['_users_id_assign']) && $cat->isField('users_id')) {
                     $input['_users_id_assign'] = $cat->getField('users_id');
                 }
                 if ((!isset($input['_groups_id_assign']) || !$input['_groups_id_assign']) && $cat->isField('groups_id')) {
                     $input['_groups_id_assign'] = $cat->getField('groups_id');
                 }
             }
             if ($item != NULL) {
                 // Auto assign tech from item
                 if ((!isset($input['_users_id_assign']) || $input['_users_id_assign'] == 0) && $item->isField('users_id_tech')) {
                     $input['_users_id_assign'] = $item->getField('users_id_tech');
                 }
                 // Auto assign group from item
                 if ((!isset($input['_groups_id_assign']) || $input['_groups_id_assign'] == 0) && $item->isField('groups_id_tech')) {
                     $input['_groups_id_assign'] = $item->getField('groups_id_tech');
                 }
             }
             break;
     }
     // Replay setting auto assign if set in rules engine or by auto_assign_mode
     if ((isset($input["_users_id_assign"]) && $input["_users_id_assign"] > 0 || isset($input["_groups_id_assign"]) && $input["_groups_id_assign"] > 0 || isset($input["_suppliers_id_assign"]) && $input["_suppliers_id_assign"] > 0) && in_array($input['status'], $this->getNewStatusArray())) {
         $input["status"] = self::ASSIGNED;
     }
     //// Manage SLA assignment
     // Manual SLA defined : reset due date
     // No manual SLA and due date defined : reset auto SLA
     if ($manual_slas_id == 0 && isset($input["due_date"]) && $input['due_date'] != 'NULL') {
         // Valid due date
         if ($input['due_date'] > $input['date']) {
             if (isset($input["slas_id"])) {
                 unset($input["slas_id"]);
             }
         } else {
             // Unset due date
             unset($input["due_date"]);
         }
     }
     if (isset($input["slas_id"]) && $input["slas_id"] > 0) {
         // Get datas to initialize SLA and set it
         $sla_data = $this->getDatasToAddSLA($input["slas_id"], $input['entities_id'], $input['date']);
         if (count($sla_data)) {
             foreach ($sla_data as $key => $val) {
                 $input[$key] = $val;
             }
         }
     }
     // auto set type if not set
     if (!isset($input["type"])) {
         $input['type'] = Entity::getUsedConfig('tickettype', $input['entities_id'], '', Ticket::INCIDENT_TYPE);
     }
     return $input;
 }