convDate() static public method

Convert a date YY-MM-DD to DD-MM-YY for calendar
static public convDate ( $time, $format = null )
$time date date to convert
$format (default null)
 function displayValue($output_type, $row)
 {
     if (isset($row[$this->name]) && $row[$this->name]) {
         return Html::convDate($row[$this->name]);
     }
     return '';
 }
Ejemplo n.º 2
0
 static function pdfForItem(PluginPdfSimplePDF $pdf, CommonDBTM $item)
 {
     global $DB, $CFG_GLPIG;
     if (!Session::haveRight("contract", "r")) {
         return false;
     }
     $type = $item->getType();
     $ID = $item->getField('id');
     $con = new Contract();
     $query = "SELECT *\n                FROM `glpi_contracts_items`\n                WHERE `glpi_contracts_items`.`items_id` = '" . $ID . "'\n                      AND `glpi_contracts_items`.`itemtype` = '" . $type . "'";
     $result = $DB->query($query);
     $number = $DB->numrows($result);
     $i = $j = 0;
     $pdf->setColumnsSize(100);
     if ($number > 0) {
         $pdf->displayTitle('<b>' . _N('Associated contract', 'Associated contracts', 2) . '</b>');
         $pdf->setColumnsSize(19, 19, 19, 16, 11, 16);
         $pdf->displayTitle(__('Name'), _x('phone', 'Number'), __('Contract type'), __('Supplier'), __('Start date'), __('Initial contract period'));
         $i++;
         while ($j < $number) {
             $cID = $DB->result($result, $j, "contracts_id");
             $assocID = $DB->result($result, $j, "id");
             if ($con->getFromDB($cID)) {
                 $pdf->displayLine(empty($con->fields["name"]) ? "(" . $con->fields["id"] . ")" : $con->fields["name"], $con->fields["num"], Html::clean(Dropdown::getDropdownName("glpi_contracttypes", $con->fields["contracttypes_id"])), str_replace("<br>", " ", $con->getSuppliersNames()), Html::convDate($con->fields["begin_date"]), sprintf(_n('%d month', '%d months', $con->fields["duration"]), $con->fields["duration"]));
             }
             $j++;
         }
     } else {
         $pdf->displayTitle("<b>" . __('No item found') . "</b>");
     }
     $pdf->displaySpace();
 }
Ejemplo n.º 3
0
 static function pdfForTicket(PluginPdfSimplePDF $pdf, Ticket $job)
 {
     global $CFG_GLPI, $DB;
     $ID = $job->getField('id');
     //////////////followups///////////
     $query = "SELECT *\n                FROM `glpi_ticketcosts`\n                WHERE `tickets_id` = '{$ID}'\n                ORDER BY `begin_date`";
     $result = $DB->query($query);
     if (!$DB->numrows($result)) {
         $pdf->setColumnsSize(100);
         $pdf->displayLine(__('No ticket cost for this ticket', 'pdf'));
     } else {
         $pdf->setColumnsSize(60, 20, 20);
         $pdf->displayTitle("<b>" . TicketCost::getTypeName($DB->numrows($result)), __('Ticket duration'), CommonITILObject::getActionTime($job->fields['actiontime']) . "</b>");
         $pdf->setColumnsSize(20, 10, 10, 10, 10, 10, 10, 10, 10);
         $pdf->setColumnsAlign('center', 'center', 'center', 'left', 'right', 'right', 'right', 'right', 'right');
         $pdf->displayTitle("<b><i>" . __('Name') . "</i></b>", "<b><i>" . __('Begin date') . "</i></b>", "<b><i>" . __('End date') . "</i></b>", "<b><i>" . __('Budget') . "</i></b>", "<b><i>" . __('Duration') . "</i></b>", "<b><i>" . __('Time cost') . "</i></b>", "<b><i>" . __('Fixed cost') . "</i></b>", "<b><i>" . __('Material cost') . "</i></b>", "<b><i>" . __('Total cost') . "</i></b>");
         while ($data = $DB->fetch_array($result)) {
             $cost = TicketCost::computeTotalCost($data['actiontime'], $data['cost_time'], $data['cost_fixed'], $data['cost_material']);
             $pdf->displayLine($data['name'], Html::convDate($data['begin_date']), Html::convDate($data['end_date']), Dropdown::getDropdownName('glpi_budgets', $data['budgets_id']), CommonITILObject::getActionTime($data['actiontime']), Html::formatNumber($data['cost_time']), Html::formatNumber($data['cost_fixed']), Html::formatNumber($data['cost_material']), Html::formatNumber($cost));
             $total_time += $data['actiontime'];
             $total_costtime += $data['actiontime'] * $data['cost_time'] / HOUR_TIMESTAMP;
             $total_fixed += $data['cost_fixed'];
             $total_material += $data['cost_material'];
             $total += $cost;
         }
         $pdf->setColumnsSize(50, 10, 10, 10, 10, 10);
         $pdf->setColumnsAlign('right', 'right', 'right', 'right', 'right', 'right');
         $pdf->displayLine('<b>' . __('Total'), CommonITILObject::getActionTime($total_time), Html::formatNumber($total_costtime), Html::formatNumber($total_fixed), Html::formatNumber($total_material), Html::formatNumber($total));
     }
     $pdf->displaySpace();
 }
Ejemplo n.º 4
0
 static function pdfMain(PluginPdfSimplePDF $pdf, SoftwareLicense $license, $main = true, $cpt = true)
 {
     global $DB;
     $ID = $license->getField('id');
     $pdf->setColumnsSize(100);
     $entity = '';
     if (Session::isMultiEntitiesMode() && !$main) {
         $entity = ' (' . Html::clean(Dropdown::getDropdownName('glpi_entities', $license->fields['entities_id'])) . ')';
     }
     $pdf->displayTitle('<b><i>' . sprintf(__('%1$s: %2$s'), __('ID') . "</i>", $ID . "</b>" . $entity));
     $pdf->setColumnsSize(50, 50);
     $pdf->displayLine('<b><i>' . sprintf(__('%1$s: %2$s'), Software::getTypeName(1) . '</i></b>', Html::clean(Dropdown::getDropdownName('glpi_softwares', $license->fields['softwares_id']))), '<b><i>' . sprintf(__('%1$s: %2$s'), __('Type') . '</i></b>', Html::clean(Dropdown::getDropdownName('glpi_softwarelicensetypes', $license->fields['softwarelicensetypes_id']))));
     $pdf->displayLine('<b><i>' . sprintf(__('%1$s: %2$s'), __('Name') . '</i></b>', $license->fields['name']), '<b><i>' . sprintf(__('%1$s: %2$s'), __('Serial number') . '</i></b>', $license->fields['serial']));
     $pdf->displayLine('<b><i>' . sprintf(__('%1$s: %2$s'), __('Purchase version') . '</i></b>', Html::clean(Dropdown::getDropdownName('glpi_softwareversions', $license->fields['softwareversions_id_buy']))), '<b><i>' . sprintf(__('%1$s: %2$s'), __('Inventory number') . '</i></b>', $license->fields['otherserial']));
     $pdf->displayLine('<b><i>' . sprintf(__('%1$s: %2$s'), __('Version in use') . '</i></b>', Html::clean(Dropdown::getDropdownName('glpi_softwareversions', $license->fields['softwareversions_id_use']))), '<b><i>' . sprintf(__('%1$s: %2$s'), __('Expiration') . '</i></b>', Html::convDate($license->fields['expire'])));
     $col2 = '';
     if ($cpt) {
         $col2 = '<b><i>' . sprintf(__('%1$s: %2$s'), __('Affected computers') . '</i></b>', Computer_SoftwareLicense::countForLicense($ID));
     }
     $pdf->displayLine('<b><i>' . sprintf(__('%1$s: %2$s'), _x('quantity', 'Number') . '</i></b>', $license->fields['number'] > 0 ? $license->fields['number'] : __('Unlimited')), $col2);
     $pdf->setColumnsSize(100);
     PluginPdfCommon::mainLine($pdf, $license, 'comment');
     if ($main) {
         $pdf->displaySpace();
     }
 }
Ejemplo n.º 5
0
 /**
  * Page footer
  *
  * @see TCPDF::Footer()
  **/
 public function Footer()
 {
     // Position at 15 mm from bottom
     $this->SetY(-15);
     $text = "GLPI PDF export - " . Html::convDate(date("Y-m-d")) . " - " . $this->getAliasNumPage() . "/" . $this->getAliasNbPages();
     // Page number
     $this->Cell(0, 10, $text, 0, false, 'C', 0, '', 0, false, 'T', 'M');
 }
Ejemplo n.º 6
0
 function getSubName()
 {
     //TODO
     global $LANG;
     $date = $this->getDate();
     $title = $this->getCriteriaLabel($this->getName());
     if (empty($title) && isset($LANG['plugin_reports']['subname'][$this->getName()])) {
         $title = $LANG['plugin_reports']['subname'][$this->getName()];
     }
     return $title . ' (' . Html::convDate($date) . ')';
 }
 function getDatasForTemplate($event, $options = array())
 {
     $this->datas['##certificate.entity##'] = Dropdown::getDropdownName('glpi_entities', $options['entities_id']);
     $this->datas['##lang.certificate.entity##'] = __('Entity');
     $this->datas['##certificate.action##'] = $event == "ExpiredCertificates" ? __('Expired certificates', 'certificates') : __('Expiring certificates', 'certificates');
     $this->datas['##lang.certificate.name##'] = __('Name');
     $this->datas['##lang.certificate.dateexpiration##'] = __('Expiration date');
     foreach ($options['certificates'] as $id => $certificate) {
         $tmp = array();
         $tmp['##certificate.name##'] = $certificate['name'];
         $tmp['##certificate.dateexpiration##'] = Html::convDate($certificate['date_expiration']);
         $this->datas['certificates'][] = $tmp;
     }
 }
 function getDatasForTemplate($event, $options = array())
 {
     global $CFG_GLPI;
     $this->datas['##domain.entity##'] = Dropdown::getDropdownName('glpi_entities', $options['entities_id']);
     $this->datas['##lang.domain.entity##'] = __('Entity');
     $this->datas['##domain.action##'] = $event == "ExpiredDomains" ? __('Expired domains', 'domains') : __('Expiring domains', 'domains');
     $this->datas['##lang.domain.name##'] = __('Name');
     $this->datas['##lang.domain.dateexpiration##'] = __('Expiration date');
     foreach ($options['domains'] as $id => $domain) {
         $tmp = array();
         $tmp['##domain.name##'] = $domain['name'];
         $tmp['##domain.dateexpiration##'] = Html::convDate($domain['date_expiration']);
         $this->datas['domains'][] = $tmp;
     }
 }
Ejemplo n.º 9
0
 private function setBackground()
 {
     $id_pdf = $this->pdf->openObject();
     $this->pdf->saveState();
     $this->pdf->ezStartPageNumbers($this->width - 20, 10, 10, 'left', Html::convDate(date("Y-m-d")) . " - {PAGENUM}/{TOTALPAGENUM}");
     $this->pdf->setStrokeColor(0, 0, 0);
     $this->pdf->setLineStyle(1, 'round', 'round');
     $this->pdf->rectangle(20, 20, $this->width - 40, $this->height - 40);
     $this->pdf->addJpegFromFile(GLPI_ROOT . "/plugins/pdf/pics/fd_logo.jpg", 25, $this->height - 50);
     // 61x25
     $this->pdf->selectFont(GLPI_ROOT . "/plugins/pdf/fonts/Times-Roman.afm");
     $this->pdf->setFontFamily('Times-Roman.afm', array('b' => 'Times-Bold.afm', 'i' => 'Times-Italic.afm', 'bi' => 'Times-BoldItalic.afm'));
     $this->pdf->restoreState();
     $this->pdf->closeObject();
     $this->pdf->addObject($id_pdf, 'all');
 }
Ejemplo n.º 10
0
 /**
  * @covers Html::convDate
  */
 public function testConvDate()
 {
     $this->assertNull(Html::convDate(null));
     $this->assertNull(Html::convDate('NULL'));
     $mydate = date('Y-m-d H:i:s');
     $expected = date('Y-m-d');
     unset($_SESSION['glpidate_format']);
     $this->assertEquals($expected, Html::convDate($mydate));
     $_SESSION['glpidate_format'] = 0;
     $this->assertEquals($expected, Html::convDate($mydate));
     $this->assertEquals($expected, Html::convDate(date('Y-m-d')));
     $expected = date('d-m-Y');
     $this->assertEquals($expected, Html::convDate($mydate, 1));
     $expected = date('m-d-Y');
     $this->assertEquals($expected, Html::convDate($mydate, 2));
 }
 function getDatasForTemplate($event, $options = array())
 {
     $this->datas['##badge.entity##'] = Dropdown::getDropdownName('glpi_entities', $options['entities_id']);
     $this->datas['##lang.badge.entity##'] = __('Entity');
     $this->datas['##badge.action##'] = $event == "ExpiredBadges" ? __('Badges at the end of the validity', 'badges') : __('Badges which expires', 'badges');
     $this->datas['##lang.badge.name##'] = __('Name');
     $this->datas['##lang.badge.dateexpiration##'] = __('Date of end of validity', 'badges');
     $this->datas['##lang.badge.serial##'] = __('Serial number');
     $this->datas['##lang.badge.users##'] = __('Allotted to', 'badges');
     foreach ($options['badges'] as $id => $badge) {
         $tmp = array();
         $tmp['##badge.name##'] = $badge['name'];
         $tmp['##badge.serial##'] = $badge['serial'];
         $tmp['##badge.users##'] = Html::clean(getUserName($badge["users_id"]));
         $tmp['##badge.dateexpiration##'] = Html::convDate($badge['date_expiration']);
         $this->datas['badges'][] = $tmp;
     }
 }
 /**
  * Get all data needed for template processing
  *
  * @param $event
  * @param $options   array
  **/
 function getDatasForTemplate($event, $options = array())
 {
     $events = $this->getAllEvents();
     $this->datas['##license.action##'] = $events[$event];
     $this->datas['##license.entity##'] = Dropdown::getDropdownName('glpi_entities', $options['entities_id']);
     foreach ($options['licenses'] as $id => $license) {
         $tmp = array();
         $tmp['##license.item##'] = $license['softname'];
         $tmp['##license.name##'] = $license['name'];
         $tmp['##license.serial##'] = $license['serial'];
         $tmp['##license.expirationdate##'] = Html::convDate($license["expire"]);
         $tmp['##license.url##'] = $this->formatURL($options['additionnaloption']['usertype'], "SoftwareLicense_" . $id);
         $this->datas['licenses'][] = $tmp;
     }
     $this->getTags();
     foreach ($this->tag_descriptions[NotificationTarget::TAG_LANGUAGE] as $tag => $values) {
         if (!isset($this->datas[$tag])) {
             $this->datas[$tag] = $values['label'];
         }
     }
 }
Ejemplo n.º 13
0
 static function pdfForItem(PluginPdfSimplePDF $pdf, CommonDBTM $item)
 {
     global $CFG_GLPI;
     $ID = $item->getField('id');
     if (!Session::haveRight("infocom", "r")) {
         return false;
     }
     $ic = new Infocom();
     $pdf->setColumnsSize(100);
     if ($ic->getFromDBforDevice(get_class($item), $ID)) {
         $pdf->displayTitle("<b>" . __('Financial and administrative information') . "</b>");
         $pdf->setColumnsSize(50, 50);
         $pdf->displayLine("<b><i>" . sprintf(__('%1$s: %2$s'), __('Supplier') . "</i></b>", Html::clean(Dropdown::getDropdownName("glpi_suppliers", $ic->fields["suppliers_id"]))), "<b><i>" . sprintf(__('%1$s: %2$s'), __('Budget') . "</i></b>", Html::clean(Dropdown::getDropdownName("glpi_budgets", $ic->fields["budgets_id"]))));
         $pdf->displayLine("<b><i>" . sprintf(__('%1$s: %2$s'), __('Order number') . "</i></b>", $ic->fields["order_number"]), "<b><i>" . sprintf(__('%1$s: %2$s'), __('Order date') . "</i></b>", Html::convDate($ic->fields["order_date"])));
         $pdf->displayLine("<b><i>" . sprintf(__('%1$s: %2$s'), __('Immobilization number') . "</i></b>", $ic->fields["immo_number"]), "<b><i>" . sprintf(__('%1$s: %2$s'), __('Date of purchase') . "</i></b>", Html::convDate($ic->fields["buy_date"])));
         $pdf->displayLine("<b><i>" . sprintf(__('%1$s: %2$s'), __('Invoice number') . "</i></b>", $ic->fields["bill"]), "<b><i>" . sprintf(__('%1$s: %2$s'), __('Delivery date') . "</i></b>", Html::convDate($ic->fields["delivery_date"])));
         $pdf->displayLine("<b><i>" . sprintf(__('%1$s: %2$s'), __('Delivery form') . "</i></b>", $ic->fields["delivery_number"]), "<b><i>" . sprintf(__('%1$s: %2$s'), __('Startup date') . "</i></b>", Html::convDate($ic->fields["use_date"])));
         $pdf->displayLine("<b><i>" . sprintf(__('%1$s: %2$s'), __('Value') . "</i></b>", Html::clean(Html::formatNumber($ic->fields["value"]))), "<b><i>" . sprintf(__('%1$s: %2$s'), _('Date of last physical inventory') . "</i></b>", Html::convDate($ic->fields["inventory_date"])));
         $pdf->displayLine("<b><i>" . sprintf(__('%1$s: %2$s'), __('Warranty extension value') . "</i></b>", Html::clean(Html::formatNumber($ic->fields["warranty_value"]))), "<b><i>" . sprintf(__('%1$s: %2$s'), __('Amortization duration') . "</i></b>", sprintf(__('%1$s (%2$s)'), sprintf(_n('%d year', '%d years', $ic->fields["sink_time"]), $ic->fields["sink_time"]), Infocom::getAmortTypeName($ic->fields["sink_type"]))));
         $pdf->displayLine("<b><i>" . sprintf(__('%1$s: %2$s'), __('Account net value') . "</i></b>", Infocom::Amort($ic->fields["sink_type"], $ic->fields["value"], $ic->fields["sink_time"], $ic->fields["sink_coeff"], $ic->fields["warranty_date"], $ic->fields["use_date"], $CFG_GLPI['date_tax'], "n")), "<b><i>" . sprintf(__('%1$s: %2$s'), __('Amortization coefficient') . "</i></b>", $ic->fields["sink_coeff"]));
         $pdf->displayLine("<b><i>" . sprintf(__('%1$s: %2$s'), __('TCO (value + tracking cost)') . "</i></b>", Html::clean(Infocom::showTco($item->getField('ticket_tco'), $ic->fields["value"]))), "<b><i>" . sprintf(__('%1$s: %2$s'), __('Monthly TCO') . "</i></b>", Html::clean(Infocom::showTco($item->getField('ticket_tco'), $ic->fields["value"], $ic->fields["warranty_date"]))));
         PluginPdfCommon::mainLine($pdf, $ic, 'comment');
         $pdf->setColumnsSize(100);
         $pdf->displayTitle("<b>" . __('Warranty information') . "</b>");
         $pdf->setColumnsSize(50, 50);
         $pdf->displayLine("<b><i>" . sprintf(__('%1$s: %2$s'), __('Start date of warranty') . "</i></b>", Html::convDate($ic->fields["warranty_date"])), "<b><i>" . sprintf(__('%1$s: %2$s'), __('Warranty duration') . "</i></b>", sprintf(__('%1$s - %2$s'), sprintf(_n('%d month', '%d months', $ic->fields["warranty_duration"]), $ic->fields["warranty_duration"]), sprintf(__('Valid to %s'), Infocom::getWarrantyExpir($ic->fields["buy_date"], $ic->fields["warranty_duration"])))));
         $col1 = "<b><i>" . __('Alarms on financial and administrative information') . "</i></b>";
         if ($ic->fields["alert"] == 0) {
             $col1 = sprintf(__('%1$s: %2$s'), $col1, __('No'));
         } else {
             if ($ic->fields["alert"] == 4) {
                 $col1 = sprintf(__('%1$s: %2$s'), $col1, __('Warranty expiration date'));
             }
         }
         $pdf->displayLine("<b><i>" . sprintf(__('%1$s: %2$s'), __('Warranty information') . "</i></b>", $ic->fields["warranty_info"]), $col1);
     } else {
         $pdf->displayTitle("<b>" . __('No financial information', 'pdf') . "</b>");
     }
     $pdf->displaySpace();
 }
 /**
  * Get all data needed for template processing
  *
  * @param $event
  * @param $options   array
  **/
 function getDatasForTemplate($event, $options = array())
 {
     global $CFG_GLPI;
     $events = $this->getAllEvents();
     $this->datas['##license.action##'] = $events[$event];
     $this->datas['##license.entity##'] = Dropdown::getDropdownName('glpi_entities', $options['entities_id']);
     foreach ($options['licenses'] as $id => $license) {
         $tmp = array();
         $tmp['##license.item##'] = $license['softname'];
         $tmp['##license.name##'] = $license['name'];
         $tmp['##license.serial##'] = $license['serial'];
         $tmp['##license.expirationdate##'] = Html::convDate($license["expire"]);
         $tmp['##license.url##'] = urldecode($CFG_GLPI["url_base"] . "/index.php?redirect=softwarelicense_" . $id);
         $this->datas['licenses'][] = $tmp;
     }
     $this->getTags();
     foreach ($this->tag_descriptions[NotificationTarget::TAG_LANGUAGE] as $tag => $values) {
         if (!isset($this->datas[$tag])) {
             $this->datas[$tag] = $values['label'];
         }
     }
 }
Ejemplo n.º 15
0
 /**
  * Generic Function to display Items
  *
  * @param $itemtype              item type
  * @param $ID                    ID of the SEARCH_OPTION item
  * @param $data            array containing data results
  * @param $num                   item num in the request
  * @param $meta                  is a meta item ? (default 0)
  * @param $addobjectparams array added parameters for union search
  *
  * @return string to print
  **/
 static function giveItem($itemtype, $ID, array $data, $num, $meta = 0, array $addobjectparams = array())
 {
     global $CFG_GLPI, $DB;
     $searchopt =& self::getOptions($itemtype);
     if (isset($CFG_GLPI["union_search_type"][$itemtype]) && $CFG_GLPI["union_search_type"][$itemtype] == $searchopt[$ID]["table"]) {
         if (isset($searchopt[$ID]['addobjectparams']) && $searchopt[$ID]['addobjectparams']) {
             return self::giveItem($data["TYPE"], $ID, $data, $num, $meta, $searchopt[$ID]['addobjectparams']);
         }
         return self::giveItem($data["TYPE"], $ID, $data, $num, $meta);
     }
     if (count($addobjectparams)) {
         $searchopt[$ID] = array_merge($searchopt[$ID], $addobjectparams);
     }
     // Plugin can override core definition for its type
     if ($plug = isPluginItemType($itemtype)) {
         $function = 'plugin_' . $plug['plugin'] . '_giveItem';
         if (function_exists($function)) {
             $out = $function($itemtype, $ID, $data, $num);
             if (!empty($out)) {
                 return $out;
             }
         }
     }
     $NAME = "ITEM_";
     //       if ($meta) {
     //          $NAME = "META_";
     //       }
     if (isset($searchopt[$ID]["table"])) {
         $table = $searchopt[$ID]["table"];
         $field = $searchopt[$ID]["field"];
         $linkfield = $searchopt[$ID]["linkfield"];
         /// TODO try to clean all specific cases using SpecificToDisplay
         switch ($table . '.' . $field) {
             case "glpi_users.name":
                 // USER search case
                 if ($itemtype != 'User' && isset($searchopt[$ID]["forcegroupby"]) && $searchopt[$ID]["forcegroupby"]) {
                     $out = "";
                     $count_display = 0;
                     $added = array();
                     $showuserlink = 0;
                     if (Session::haveRight('user', READ)) {
                         $showuserlink = 1;
                     }
                     for ($k = 0; $k < $data[$num]['count']; $k++) {
                         if (isset($data[$num][$k]['name']) && $data[$num][$k]['name'] > 0 || isset($data[$num][$k][2]) && $data[$num][$k][2] != '') {
                             if ($count_display) {
                                 $out .= self::LBBR;
                             }
                             if ($itemtype == 'Ticket') {
                                 if (isset($data[$num][$k]['name']) && $data[$num][$k]['name'] > 0) {
                                     $userdata = getUserName($data[$num][$k]['name'], 2);
                                     $tooltip = "";
                                     if (Session::haveRight('user', READ)) {
                                         $tooltip = Html::showToolTip($userdata["comment"], array('link' => $userdata["link"], 'display' => false));
                                     }
                                     $out .= sprintf(__('%1$s %2$s'), $userdata['name'], $tooltip);
                                     $count_display++;
                                 }
                             } else {
                                 $out .= getUserName($data[$num][$k]['name'], $showuserlink);
                                 $count_display++;
                             }
                             // Manage alternative_email for tickets_users
                             if ($itemtype == 'Ticket' && isset($data[$num][$k][2])) {
                                 $split = explode(self::LONGSEP, $data[$num][$k][2]);
                                 for ($l = 0; $l < count($split); $l++) {
                                     $split2 = explode(" ", $split[$l]);
                                     if (count($split2) == 2 && $split2[0] == 0 && !empty($split2[1])) {
                                         if ($count_display) {
                                             $out .= self::LBBR;
                                         }
                                         $count_display++;
                                         $out .= "<a href='mailto:" . $split2[1] . "'>" . $split2[1] . "</a>";
                                     }
                                 }
                             }
                         }
                     }
                     return $out;
                 }
                 if ($itemtype != 'User') {
                     $toadd = '';
                     if ($itemtype == 'Ticket' && $data[$num][0]['id'] > 0) {
                         $userdata = getUserName($data[$num][0]['id'], 2);
                         $toadd = Html::showToolTip($userdata["comment"], array('link' => $userdata["link"], 'display' => false));
                     }
                     $usernameformat = formatUserName($data[$num][0]['id'], $data[$num][0]['name'], $data[$num][0]['realname'], $data[$num][0]['firstname'], 1);
                     return sprintf(__('%1$s %2$s'), $usernameformat, $toadd);
                 }
                 break;
             case "glpi_profiles.name":
                 if ($itemtype == 'User' && $ID == 20) {
                     $out = "";
                     $count_display = 0;
                     $added = array();
                     for ($k = 0; $k < $data[$num]['count']; $k++) {
                         if (strlen(trim($data[$num][$k]['name'])) > 0) {
                             $text = sprintf(__('%1$s - %2$s'), $data[$num][$k]['name'], Dropdown::getDropdownName('glpi_entities', $data[$num][$k]['entities_id']));
                             $comp = '';
                             if ($data[$num][$k]['is_recursive']) {
                                 $comp = __('R');
                                 if ($data[$num][$k]['is_dynamic']) {
                                     $comp = sprintf(__('%1$s%2$s'), $comp, ", ");
                                 }
                             }
                             if ($data[$num][$k]['is_dynamic']) {
                                 $comp = sprintf(__('%1$s%2$s'), $comp, __('D'));
                             }
                             if (!empty($comp)) {
                                 $text = sprintf(__('%1$s %2$s'), $text, "(" . $comp . ")");
                             }
                             if (!in_array($text, $added)) {
                                 if ($count_display) {
                                     $out .= self::LBBR;
                                 }
                                 $count_display++;
                                 $out .= $text;
                                 $added[] = $text;
                             }
                         }
                     }
                     return $out;
                 }
                 break;
             case "glpi_entities.completename":
                 if ($itemtype == 'User') {
                     $out = "";
                     $added = array();
                     $count_display = 0;
                     for ($k = 0; $k < $data[$num]['count']; $k++) {
                         if (strlen(trim($data[$num][$k]['name'])) > 0) {
                             $text = sprintf(__('%1$s - %2$s'), $data[$num][$k]['name'], Dropdown::getDropdownName('glpi_profiles', $data[$num][$k]['profiles_id']));
                             $comp = '';
                             if ($data[$num][$k]['is_recursive']) {
                                 $comp = __('R');
                                 if ($data[$num][$k]['is_dynamic']) {
                                     $comp = sprintf(__('%1$s%2$s'), $comp, ", ");
                                 }
                             }
                             if ($data[$num][$k]['is_dynamic']) {
                                 $comp = sprintf(__('%1$s%2$s'), $comp, __('D'));
                             }
                             if (!empty($comp)) {
                                 $text = sprintf(__('%1$s %2$s'), $text, "(" . $comp . ")");
                             }
                             if (!in_array($text, $added)) {
                                 if ($count_display) {
                                     $out .= self::LBBR;
                                 }
                                 $count_display++;
                                 $out .= $text;
                                 $added[] = $text;
                             }
                         }
                     }
                     return $out;
                 }
                 break;
             case "glpi_documenttypes.icon":
                 if (!empty($data[$num][0]['name'])) {
                     return "<img class='middle' alt='' src='" . $CFG_GLPI["typedoc_icon_dir"] . "/" . $data[$num][0]['name'] . "'>";
                 }
                 return "&nbsp;";
             case "glpi_documents.filename":
                 $doc = new Document();
                 if ($doc->getFromDB($data['id'])) {
                     return $doc->getDownloadLink();
                 }
                 return NOT_AVAILABLE;
             case "glpi_tickets_tickets.tickets_id_1":
                 $out = "";
                 $displayed = array();
                 for ($k = 0; $k < $data[$num]['count']; $k++) {
                     $linkid = $data[$num][$k]['tickets_id_2'] == $data['id'] ? $data[$num][$k]['name'] : $data[$num][$k]['tickets_id_2'];
                     if ($linkid > 0 && !isset($displayed[$linkid])) {
                         $text = "<a ";
                         $text .= "href=\"" . $CFG_GLPI["root_doc"] . "/front/ticket.form.php?id={$linkid}\">";
                         $text .= Dropdown::getDropdownName('glpi_tickets', $linkid) . "</a>";
                         if (count($displayed)) {
                             $out .= self::LBBR;
                         }
                         $displayed[$linkid] = $linkid;
                         $out .= $text;
                     }
                 }
                 return $out;
             case "glpi_problems.id":
                 if ($searchopt[$ID]["datatype"] == 'count') {
                     if ($data[$num][0]['name'] > 0 && Session::haveRight("problem", Problem::READALL)) {
                         if ($itemtype == 'ITILCategory') {
                             $options['criteria'][0]['field'] = 7;
                             $options['criteria'][0]['searchtype'] = 'equals';
                             $options['criteria'][0]['value'] = $data['id'];
                             $options['criteria'][0]['link'] = 'AND';
                         } else {
                             $options['criteria'][0]['field'] = 12;
                             $options['criteria'][0]['searchtype'] = 'equals';
                             $options['criteria'][0]['value'] = 'all';
                             $options['criteria'][0]['link'] = 'AND';
                             $options['metacriteria'][0]['itemtype'] = $itemtype;
                             $options['metacriteria'][0]['field'] = self::getOptionNumber($itemtype, 'name');
                             $options['metacriteria'][0]['searchtype'] = 'equals';
                             $options['metacriteria'][0]['value'] = $data['id'];
                             $options['metacriteria'][0]['link'] = 'AND';
                         }
                         $options['reset'] = 'reset';
                         $out = "<a id='problem{$itemtype}" . $data['id'] . "' ";
                         $out .= "href=\"" . $CFG_GLPI["root_doc"] . "/front/problem.php?" . Toolbox::append_params($options, '&amp;') . "\">";
                         $out .= $data[$num][0]['name'] . "</a>";
                         return $out;
                     }
                 }
                 break;
             case "glpi_tickets.id":
                 if ($searchopt[$ID]["datatype"] == 'count') {
                     if ($data[$num][0]['name'] > 0 && Session::haveRight("ticket", Ticket::READALL)) {
                         if ($itemtype == 'User') {
                             // Requester
                             if ($ID == 60) {
                                 $options['criteria'][0]['field'] = 4;
                                 $options['criteria'][0]['searchtype'] = 'equals';
                                 $options['criteria'][0]['value'] = $data['id'];
                                 $options['criteria'][0]['link'] = 'AND';
                             }
                             // Writer
                             if ($ID == 61) {
                                 $options['criteria'][0]['field'] = 22;
                                 $options['criteria'][0]['searchtype'] = 'equals';
                                 $options['criteria'][0]['value'] = $data['id'];
                                 $options['criteria'][0]['link'] = 'AND';
                             }
                             // Assign
                             if ($ID == 64) {
                                 $options['criteria'][0]['field'] = 5;
                                 $options['criteria'][0]['searchtype'] = 'equals';
                                 $options['criteria'][0]['value'] = $data['id'];
                                 $options['criteria'][0]['link'] = 'AND';
                             }
                         } else {
                             if ($itemtype == 'ITILCategory') {
                                 $options['criteria'][0]['field'] = 7;
                                 $options['criteria'][0]['searchtype'] = 'equals';
                                 $options['criteria'][0]['value'] = $data['id'];
                                 $options['criteria'][0]['link'] = 'AND';
                             } else {
                                 $options['criteria'][0]['field'] = 12;
                                 $options['criteria'][0]['searchtype'] = 'equals';
                                 $options['criteria'][0]['value'] = 'all';
                                 $options['criteria'][0]['link'] = 'AND';
                                 $options['metacriteria'][0]['itemtype'] = $itemtype;
                                 $options['metacriteria'][0]['field'] = self::getOptionNumber($itemtype, 'name');
                                 $options['metacriteria'][0]['searchtype'] = 'equals';
                                 $options['metacriteria'][0]['value'] = $data['id'];
                                 $options['metacriteria'][0]['link'] = 'AND';
                             }
                         }
                         $options['reset'] = 'reset';
                         $out = "<a id='ticket{$itemtype}" . $data['id'] . "' ";
                         $out .= "href=\"" . $CFG_GLPI["root_doc"] . "/front/ticket.php?" . Toolbox::append_params($options, '&amp;') . "\">";
                         $out .= $data[$num][0]['name'] . "</a>";
                         return $out;
                     }
                 }
                 break;
             case "glpi_tickets.due_date":
             case "glpi_problems.due_date":
             case "glpi_changes.due_date":
                 // Due date + progress
                 if ($ID == 151) {
                     $out = Html::convDate($data[$num][0]['name']);
                     // No due date in waiting status
                     if ($data[$num][0]['status'] == CommonITILObject::WAITING) {
                         return '';
                     }
                     if (empty($data[$num][0]['name'])) {
                         return '';
                     }
                     if ($data[$num][0]['status'] == Ticket::SOLVED || $data[$num][0]['status'] == Ticket::CLOSED) {
                         return $out;
                     }
                     $itemtype = getItemTypeForTable($table);
                     $item = new $itemtype();
                     $item->getFromDB($data['id']);
                     $percentage = 0;
                     $totaltime = 0;
                     $currenttime = 0;
                     if ($item->isField('slas_id') && $item->fields['slas_id'] != 0) {
                         // Have SLA
                         $sla = new SLA();
                         $sla->getFromDB($item->fields['slas_id']);
                         $currenttime = $sla->getActiveTimeBetween($item->fields['date'], date('Y-m-d H:i:s'));
                         $totaltime = $sla->getActiveTimeBetween($item->fields['date'], $data[$num][0]['name']);
                     } else {
                         $calendars_id = Entity::getUsedConfig('calendars_id', $item->fields['entities_id']);
                         if ($calendars_id != 0) {
                             // Ticket entity have calendar
                             $calendar = new Calendar();
                             $calendar->getFromDB($calendars_id);
                             $currenttime = $calendar->getActiveTimeBetween($item->fields['date'], date('Y-m-d H:i:s'));
                             $totaltime = $calendar->getActiveTimeBetween($item->fields['date'], $data[$num][0]['name']);
                         } else {
                             // No calendar
                             $currenttime = strtotime(date('Y-m-d H:i:s')) - strtotime($item->fields['date']);
                             $totaltime = strtotime($data[$num][0]['name']) - strtotime($item->fields['date']);
                         }
                     }
                     if ($totaltime != 0) {
                         $percentage = round(100 * $currenttime / $totaltime);
                     } else {
                         // Total time is null : no active time
                         $percentage = 100;
                     }
                     if ($percentage > 100) {
                         $percentage = 100;
                     }
                     $percentage_text = $percentage;
                     if ($_SESSION['glpiduedatewarning_unit'] == '%') {
                         $less_warn_limit = $_SESSION['glpiduedatewarning_less'];
                         $less_warn = 100 - $percentage;
                     } else {
                         if ($_SESSION['glpiduedatewarning_unit'] == 'hour') {
                             $less_warn_limit = $_SESSION['glpiduedatewarning_less'] * HOUR_TIMESTAMP;
                             $less_warn = $totaltime - $currenttime;
                         } else {
                             if ($_SESSION['glpiduedatewarning_unit'] == 'day') {
                                 $less_warn_limit = $_SESSION['glpiduedatewarning_less'] * DAY_TIMESTAMP;
                                 $less_warn = $totaltime - $currenttime;
                             }
                         }
                     }
                     if ($_SESSION['glpiduedatecritical_unit'] == '%') {
                         $less_crit_limit = $_SESSION['glpiduedatecritical_less'];
                         $less_crit = 100 - $percentage;
                     } else {
                         if ($_SESSION['glpiduedatecritical_unit'] == 'hour') {
                             $less_crit_limit = $_SESSION['glpiduedatecritical_less'] * HOUR_TIMESTAMP;
                             $less_crit = $totaltime - $currenttime;
                         } else {
                             if ($_SESSION['glpiduedatecritical_unit'] == 'day') {
                                 $less_crit_limit = $_SESSION['glpiduedatecritical_less'] * DAY_TIMESTAMP;
                                 $less_crit = $totaltime - $currenttime;
                             }
                         }
                     }
                     $color = $_SESSION['glpiduedateok_color'];
                     if ($less_crit < $less_crit_limit) {
                         $color = $_SESSION['glpiduedatecritical_color'];
                     } else {
                         if ($less_warn < $less_warn_limit) {
                             $color = $_SESSION['glpiduedatewarning_color'];
                         }
                     }
                     //Calculate bar progress
                     $out .= "<div class='center' style='background-color: #ffffff; width: 100%;\n                            border: 1px solid #9BA563; position: relative;' >";
                     $out .= "<div style='position:absolute;'>&nbsp;" . $percentage_text . "%</div>";
                     $out .= "<div class='center' style='background-color: " . $color . ";\n                            width: " . $percentage . "%; height: 12px' ></div>";
                     $out .= "</div>";
                     return $out;
                 }
                 break;
             case "glpi_softwarelicenses.number":
                 if ($data[$num][0]['min'] == -1) {
                     return __('Unlimited');
                 }
                 if (empty($data[$num][0]['name'])) {
                     return 0;
                 }
                 return $data[$num][0]['name'];
             case "glpi_auth_tables.name":
                 return Auth::getMethodName($data[$num][0]['name'], $data[$num][0]['auths_id'], 1, $data[$num][0]['ldapname'] . $data[$num][0]['mailname']);
             case "glpi_reservationitems.comment":
                 if (empty($data[$num][0]['name'])) {
                     return "<a title=\"" . __s('Modify the comment') . "\"\n                           href='" . $CFG_GLPI["root_doc"] . "/front/reservationitem.form.php?id=" . $data["refID"] . "' >" . __('None') . "</a>";
                 }
                 return "<a title=\"" . __s('Modify the comment') . "\"\n                        href='" . $CFG_GLPI["root_doc"] . "/front/reservationitem.form.php?id=" . $data['refID'] . "' >" . Html::resume_text($data[$num][0]['name']) . "</a>";
             case 'glpi_crontasks.description':
                 $tmp = new CronTask();
                 return $tmp->getDescription($data[$num][0]['name']);
             case 'glpi_changes.status':
                 $status = Change::getStatus($data[$num][0]['name']);
                 return "<img src=\"" . Change::getStatusIconURL($data[$num][0]['name']) . "\"\n                        alt=\"{$status}\" title=\"{$status}\">&nbsp;{$status}";
             case 'glpi_problems.status':
                 $status = Problem::getStatus($data[$num][0]['name']);
                 return "<img src=\"" . Problem::getStatusIconURL($data[$num][0]['name']) . "\"\n                        alt=\"{$status}\" title=\"{$status}\">&nbsp;{$status}";
             case 'glpi_tickets.status':
                 $status = Ticket::getStatus($data[$num][0]['name']);
                 return "<img src=\"" . Ticket::getStatusIconURL($data[$num][0]['name']) . "\"\n                        alt=\"{$status}\" title=\"{$status}\">&nbsp;{$status}";
             case 'glpi_projectstates.name':
                 $out = '';
                 $query = "SELECT `color`\n                         FROM `glpi_projectstates`\n                         WHERE `name` = '" . $data[$num][0]['name'] . "'";
                 foreach ($DB->request($query) as $color) {
                     $color = $color['color'];
                     $out = "<div style=\"background-color:" . $color . ";\">";
                     $name = $data[$num][0]['name'];
                     if (isset($data[$num][0]['trans'])) {
                         $name = $data[$num][0]['trans'];
                     }
                     if ($itemtype == 'ProjectState') {
                         $out .= "<a href='" . $CFG_GLPI["root_doc"] . "/front/projectstate.form.php?id=" . $data[$num][0]["id"] . "'>" . $name . "</a></div>";
                     } else {
                         $out .= $name . "</div>";
                     }
                 }
                 return $out;
             case 'glpi_items_tickets.items_id':
             case 'glpi_items_problems.items_id':
                 if (!empty($data[$num])) {
                     $items = array();
                     foreach ($data[$num] as $key => $val) {
                         if (is_numeric($key)) {
                             if (!empty($val['itemtype']) && ($item = getItemForItemtype($val['itemtype']))) {
                                 if ($item->getFromDB($val['name'])) {
                                     $items[] = $item->getLink(array('comments' => true));
                                 }
                             }
                         }
                     }
                     if (!empty($items)) {
                         return implode("<br>", $items);
                     }
                 }
                 return '&nbsp;';
             case 'glpi_items_tickets.itemtype':
             case 'glpi_items_problems.itemtype':
                 if (!empty($data[$num])) {
                     $itemtypes = array();
                     foreach ($data[$num] as $key => $val) {
                         if (is_numeric($key)) {
                             if (!empty($val['name'])) {
                                 if (substr($val['name'], 0, 6) == 'Plugin') {
                                     $plug = new $val['name']();
                                     $name = $plug->getTypeName();
                                     $itemtypes[] = __($name);
                                 } else {
                                     $itemtypes[] = __($val['name']);
                                 }
                             }
                         }
                     }
                     if (!empty($itemtypes)) {
                         return implode("<br>", $itemtypes);
                     }
                 }
                 return '&nbsp;';
             case 'glpi_tickets.name':
             case 'glpi_problems.name':
             case 'glpi_changes.name':
                 if (isset($data[$num][0]['content']) && isset($data[$num][0]['id']) && isset($data[$num][0]['status'])) {
                     $link = Toolbox::getItemTypeFormURL($itemtype);
                     $out = "<a id='{$itemtype}" . $data[$num][0]['id'] . "' href=\"" . $link;
                     $out .= strstr($link, '?') ? '&amp;' : '?';
                     $out .= 'id=' . $data[$num][0]['id'];
                     // Force solution tab if solved
                     if ($item = getItemForItemtype($itemtype)) {
                         if (in_array($data[$num][0]['status'], $item->getSolvedStatusArray())) {
                             $out .= "&amp;forcetab={$itemtype}\$2";
                         }
                     }
                     $out .= "\">";
                     $name = $data[$num][0]['name'];
                     if ($_SESSION["glpiis_ids_visible"] || empty($data[$num][0]['name'])) {
                         $name = sprintf(__('%1$s (%2$s)'), $name, $data[$num][0]['id']);
                     }
                     $out .= $name . "</a>";
                     $hdecode = Html::entity_decode_deep($data[$num][0]['content']);
                     $content = Toolbox::unclean_cross_side_scripting_deep($hdecode);
                     $out = sprintf(__('%1$s %2$s'), $out, Html::showToolTip(nl2br(Html::Clean($content)), array('applyto' => $itemtype . $data[$num][0]['id'], 'display' => false)));
                     return $out;
                 }
             case 'glpi_ticketvalidations.status':
                 $out = '';
                 for ($k = 0; $k < $data[$num]['count']; $k++) {
                     if ($data[$num][$k]['name']) {
                         $status = TicketValidation::getStatus($data[$num][$k]['name']);
                         $bgcolor = TicketValidation::getStatusColor($data[$num][$k]['name']);
                         $out .= (empty($out) ? '' : self::LBBR) . "<div style=\"background-color:" . $bgcolor . ";\">" . $status . '</div>';
                     }
                 }
                 return $out;
             case 'glpi_ticketsatisfactions.satisfaction':
                 if (self::$output_type == self::HTML_OUTPUT) {
                     return TicketSatisfaction::displaySatisfaction($data[$num][0]['name']);
                 }
                 break;
             case 'glpi_projects._virtual_planned_duration':
                 return Html::timestampToString(ProjectTask::getTotalPlannedDurationForProject($data["id"]), false);
             case 'glpi_projects._virtual_effective_duration':
                 return Html::timestampToString(ProjectTask::getTotalEffectiveDurationForProject($data["id"]), false);
             case 'glpi_cartridgeitems._virtual':
                 return Cartridge::getCount($data["id"], $data[$num][0]['alarm_threshold'], self::$output_type != self::HTML_OUTPUT);
             case 'glpi_printers._virtual':
                 return Cartridge::getCountForPrinter($data["id"], self::$output_type != self::HTML_OUTPUT);
             case 'glpi_consumableitems._virtual':
                 return Consumable::getCount($data["id"], $data[$num][0]['alarm_threshold'], self::$output_type != self::HTML_OUTPUT);
             case 'glpi_links._virtual':
                 $out = '';
                 $link = new Link();
                 if (($item = getItemForItemtype($itemtype)) && $item->getFromDB($data['id']) && $link->getfromDB($data[$num][0]['id']) && $item->fields['entities_id'] == $link->fields['entities_id']) {
                     if (count($data[$num])) {
                         $count_display = 0;
                         foreach ($data[$num] as $val) {
                             if (is_array($val)) {
                                 $links = Link::getAllLinksFor($item, $val);
                                 foreach ($links as $link) {
                                     if ($count_display) {
                                         $out .= self::LBBR;
                                     }
                                     $out .= $link;
                                     $count_display++;
                                 }
                             }
                         }
                     }
                 }
                 return $out;
             case 'glpi_reservationitems._virtual':
                 if ($data[$num][0]['is_active']) {
                     return "<a href='reservation.php?reservationitems_id=" . $data["refID"] . "' title=\"" . __s('See planning') . "\">" . "<img src=\"" . $CFG_GLPI["root_doc"] . "/pics/reservation-3.png\" alt='' title=''></a>";
                 } else {
                     return "&nbsp;";
                 }
         }
     }
     //// Default case
     // Link with plugin tables : need to know left join structure
     if (isset($table)) {
         if (preg_match("/^glpi_plugin_([a-z0-9]+)/", $table . '.' . $field, $matches)) {
             if (count($matches) == 2) {
                 $plug = $matches[1];
                 $function = 'plugin_' . $plug . '_giveItem';
                 if (function_exists($function)) {
                     $out = $function($itemtype, $ID, $data, $num);
                     if (!empty($out)) {
                         return $out;
                     }
                 }
             }
         }
     }
     $unit = '';
     if (isset($searchopt[$ID]['unit'])) {
         $unit = $searchopt[$ID]['unit'];
     }
     // Preformat items
     if (isset($searchopt[$ID]["datatype"])) {
         switch ($searchopt[$ID]["datatype"]) {
             case "itemlink":
                 $linkitemtype = getItemTypeForTable($searchopt[$ID]["table"]);
                 $out = "";
                 $count_display = 0;
                 $separate = self::LBBR;
                 if (isset($searchopt[$ID]['splititems']) && $searchopt[$ID]['splititems']) {
                     $separate = self::LBHR;
                 }
                 for ($k = 0; $k < $data[$num]['count']; $k++) {
                     if (isset($data[$num][$k]['id'])) {
                         if ($count_display) {
                             $out .= $separate;
                         }
                         $count_display++;
                         $page = $linkitemtype::getFormUrl();
                         $page .= strpos($page, '?') ? '&id' : '?id';
                         $name = Dropdown::getValueWithUnit($data[$num][$k]['name'], $unit);
                         if ($_SESSION["glpiis_ids_visible"] || empty($data[$num][$k]['name'])) {
                             $name = sprintf(__('%1$s (%2$s)'), $name, $data[$num][$k]['id']);
                         }
                         $out .= "<a id='" . $linkitemtype . "_" . $data['id'] . "_" . $data[$num][$k]['id'] . "' href='{$page}=" . $data[$num][$k]['id'] . "'>" . $name . "</a>";
                     }
                 }
                 return $out;
             case "text":
                 $separate = self::LBBR;
                 if (isset($searchopt[$ID]['splititems']) && $searchopt[$ID]['splititems']) {
                     $separate = self::LBHR;
                 }
                 $out = '';
                 $count_display = 0;
                 for ($k = 0; $k < $data[$num]['count']; $k++) {
                     if (strlen(trim($data[$num][$k]['name'])) > 0) {
                         if ($count_display) {
                             $out .= $separate;
                         }
                         $count_display++;
                         $text = "";
                         if (isset($searchopt[$ID]['htmltext']) && $searchopt[$ID]['htmltext']) {
                             $text = Html::clean(Toolbox::unclean_cross_side_scripting_deep(nl2br($data[$num][$k]['name'])));
                         } else {
                             $text = nl2br($data[$num][$k]['name']);
                         }
                         if (self::$output_type == self::HTML_OUTPUT && Toolbox::strlen($text) > $CFG_GLPI['cut']) {
                             $rand = mt_rand();
                             $out .= sprintf(__('%1$s %2$s'), "<span id='text{$rand}'>" . Html::resume_text($text, $CFG_GLPI['cut']) . '</span>', Html::showToolTip($text, array('applyto' => "text{$rand}", 'display' => false)));
                         } else {
                             $out .= $text;
                         }
                     }
                 }
                 return $out;
             case "date":
             case "date_delay":
                 $out = '';
                 for ($k = 0; $k < $data[$num]['count']; $k++) {
                     if (is_null($data[$num][$k]['name']) && isset($searchopt[$ID]['emptylabel']) && $searchopt[$ID]['emptylabel']) {
                         $out .= (empty($out) ? '' : self::LBBR) . $searchopt[$ID]['emptylabel'];
                     } else {
                         $out .= (empty($out) ? '' : self::LBBR) . Html::convDate($data[$num][$k]['name']);
                     }
                 }
                 return $out;
             case "datetime":
                 $out = '';
                 for ($k = 0; $k < $data[$num]['count']; $k++) {
                     if (is_null($data[$num][$k]['name']) && isset($searchopt[$ID]['emptylabel']) && $searchopt[$ID]['emptylabel']) {
                         $out .= (empty($out) ? '' : self::LBBR) . $searchopt[$ID]['emptylabel'];
                     } else {
                         $out .= (empty($out) ? '' : self::LBBR) . Html::convDateTime($data[$num][$k]['name']);
                     }
                 }
                 return $out;
             case "timestamp":
                 $withseconds = false;
                 if (isset($searchopt[$ID]['withseconds'])) {
                     $withseconds = $searchopt[$ID]['withseconds'];
                 }
                 $withdays = true;
                 if (isset($searchopt[$ID]['withdays'])) {
                     $withdays = $searchopt[$ID]['withdays'];
                 }
                 $out = '';
                 for ($k = 0; $k < $data[$num]['count']; $k++) {
                     $out .= (empty($out) ? '' : '<br>') . Html::timestampToString($data[$num][$k]['name'], $withseconds, $withdays);
                 }
                 return $out;
             case "email":
                 $out = '';
                 $count_display = 0;
                 for ($k = 0; $k < $data[$num]['count']; $k++) {
                     if ($count_display) {
                         $out .= self::LBBR;
                     }
                     $count_display++;
                     if (!empty($data[$num][$k]['name'])) {
                         $out .= empty($out) ? '' : self::LBBR;
                         $out .= "<a href='mailto:" . $data[$num][$k]['name'] . "'>" . $data[$num][$k]['name'];
                         $out .= "</a>";
                     }
                 }
                 return empty($out) ? "&nbsp;" : $out;
             case "weblink":
                 $orig_link = trim($data[$num][0]['name']);
                 if (!empty($orig_link)) {
                     // strip begin of link
                     $link = preg_replace('/https?:\\/\\/(www[^\\.]*\\.)?/', '', $orig_link);
                     $link = preg_replace('/\\/$/', '', $link);
                     if (Toolbox::strlen($link) > $CFG_GLPI["url_maxlength"]) {
                         $link = Toolbox::substr($link, 0, $CFG_GLPI["url_maxlength"]) . "...";
                     }
                     return "<a href=\"" . formatOutputWebLink($orig_link) . "\" target='_blank'>{$link}</a>";
                 }
                 return "&nbsp;";
             case "count":
             case "number":
                 $out = "";
                 $count_display = 0;
                 for ($k = 0; $k < $data[$num]['count']; $k++) {
                     if (strlen(trim($data[$num][$k]['name'])) > 0) {
                         if ($count_display) {
                             $out .= self::LBBR;
                         }
                         $count_display++;
                         if (isset($searchopt[$ID]['toadd']) && isset($searchopt[$ID]['toadd'][$data[$num][$k]['name']])) {
                             $out .= $searchopt[$ID]['toadd'][$data[$num][$k]['name']];
                         } else {
                             $number = str_replace(' ', '&nbsp;', Html::formatNumber($data[$num][$k]['name'], false, 0));
                             $out .= Dropdown::getValueWithUnit($number, $unit);
                         }
                     }
                 }
                 return $out;
             case "decimal":
                 $out = "";
                 $count_display = 0;
                 for ($k = 0; $k < $data[$num]['count']; $k++) {
                     if (strlen(trim($data[$num][$k]['name'])) > 0) {
                         if ($count_display) {
                             $out .= self::LBBR;
                         }
                         $count_display++;
                         if (isset($searchopt[$ID]['toadd']) && isset($searchopt[$ID]['toadd'][$data[$num][$k]['name']])) {
                             $out .= $searchopt[$ID]['toadd'][$data[$num][$k]['name']];
                         } else {
                             $number = str_replace(' ', '&nbsp;', Html::formatNumber($data[$num][$k]['name']));
                             $out .= Dropdown::getValueWithUnit($number, $unit);
                         }
                     }
                 }
                 return $out;
             case "bool":
                 $out = "";
                 $count_display = 0;
                 for ($k = 0; $k < $data[$num]['count']; $k++) {
                     if (strlen(trim($data[$num][$k]['name'])) > 0) {
                         if ($count_display) {
                             $out .= self::LBBR;
                         }
                         $count_display++;
                         $out .= Dropdown::getValueWithUnit(Dropdown::getYesNo($data[$num][$k]['name']), $unit);
                     }
                 }
                 return $out;
             case "itemtypename":
                 if ($obj = getItemForItemtype($data[$num][0]['name'])) {
                     return $obj->getTypeName();
                 }
                 return "";
             case "language":
                 if (isset($CFG_GLPI['languages'][$data[$num][0]['name']])) {
                     return $CFG_GLPI['languages'][$data[$num][0]['name']][0];
                 }
                 return __('Default value');
         }
     }
     // Manage items with need group by / group_concat
     $out = "";
     $count_display = 0;
     $separate = self::LBBR;
     if (isset($searchopt[$ID]['splititems']) && $searchopt[$ID]['splititems']) {
         $separate = self::LBHR;
     }
     for ($k = 0; $k < $data[$num]['count']; $k++) {
         if (strlen(trim($data[$num][$k]['name'])) > 0) {
             if ($count_display) {
                 $out .= $separate;
             }
             $count_display++;
             // Get specific display if available
             $itemtype = getItemTypeForTable($table);
             if ($item = getItemForItemtype($itemtype)) {
                 $tmpdata = $data[$num][$k];
                 // Copy name to real field
                 $tmpdata[$field] = $data[$num][$k]['name'];
                 $specific = $item->getSpecificValueToDisplay($field, $tmpdata, array('html' => true, 'searchopt' => $searchopt[$ID]));
             }
             if (!empty($specific)) {
                 $out .= $specific;
             } else {
                 if (isset($searchopt[$ID]['toadd']) && isset($searchopt[$ID]['toadd'][$data[$num][$k]['name']])) {
                     $out .= $searchopt[$ID]['toadd'][$data[$num][$k]['name']];
                 } else {
                     // Empty is 0 or empty
                     if (empty($split[0]) && isset($searchopt[$ID]['emptylabel'])) {
                         $out .= $searchopt[$ID]['emptylabel'];
                     } else {
                         // Trans field exists
                         if (isset($data[$num][$k]['trans']) && !empty($data[$num][$k]['trans'])) {
                             $out .= Dropdown::getValueWithUnit($data[$num][$k]['trans'], $unit);
                         } else {
                             $out .= Dropdown::getValueWithUnit($data[$num][$k]['name'], $unit);
                         }
                     }
                 }
             }
         }
     }
     return $out;
     // Trans in group concat
     if (count($split) == 3 && !empty($split[1])) {
         return Dropdown::getValueWithUnit($split[1], $unit);
     }
     return Dropdown::getValueWithUnit($split[0], $unit);
 }
Ejemplo n.º 16
0
 /**
  * Get date using a begin date and a period in month
  *
  * @param $from            date     begin date
  * @param $addwarranty     integer  period in months
  * @param $deletenotice    integer  period in months of notice (default 0)
  * @param $color           boolean  if show expire date in red color (false by default)
  *
  * @return expiration date string
  **/
 static function getWarrantyExpir($from, $addwarranty, $deletenotice = 0, $color = false)
 {
     // Life warranty
     if ($addwarranty == -1 && $deletenotice == 0) {
         return __('Never');
     }
     if ($from == NULL || empty($from)) {
         return "";
     }
     $datetime = strtotime("{$from}+{$addwarranty} month -{$deletenotice} month");
     if ($color && $datetime < time()) {
         return "<span class='red'>" . Html::convDate(date("Y-m-d", $datetime)) . "</span>";
     }
     return Html::convDate(date("Y-m-d", $datetime));
 }
Ejemplo n.º 17
0
 /**
  * @param $pdf                PluginPdfSimplePDF object
  * @param $p                  Printer object
  * @param $old
  **/
 static function pdfForPrinter(PluginPdfSimplePDF $pdf, Printer $p, $old = false)
 {
     global $DB, $CFG_GLPI;
     $instID = $p->getField('id');
     if (!Session::haveRight("cartridge", "r")) {
         return false;
     }
     $dateout = "IS NULL ";
     if ($old) {
         $dateout = " IS NOT NULL ";
     }
     $query = "SELECT `glpi_cartridgeitems`.`id` AS tid,\n                       `glpi_cartridgeitems`.`ref`,\n                       `glpi_cartridgeitems`.`name`,\n                       `glpi_cartridges`.`id`,\n                       `glpi_cartridges`.`pages`,\n                       `glpi_cartridges`.`date_use`,\n                       `glpi_cartridges`.`date_out`,\n                       `glpi_cartridges`.`date_in`\n                FROM `glpi_cartridges`, `glpi_cartridgeitems`\n                WHERE `glpi_cartridges`.`date_out` " . $dateout . "\n                      AND `glpi_cartridges`.`printers_id` = '" . $instID . "'\n                      AND `glpi_cartridges`.`cartridgeitems_id` = `glpi_cartridgeitems`.`id`\n                ORDER BY `glpi_cartridges`.`date_out` ASC,\n                         `glpi_cartridges`.`date_use` DESC,\n                         `glpi_cartridges`.`date_in`";
     $result = $DB->query($query);
     $number = $DB->numrows($result);
     $i = 0;
     $pages = $p->fields['init_pages_counter'];
     $pdf->setColumnsSize(100);
     $pdf->displayTitle("<b>" . ($old ? __('Worn cartridges') : __('Used cartridges')) . "</b>");
     if (!$number) {
         $pdf->displayLine(__('No item found'));
     } else {
         $pdf->setColumnsSize(25, 13, 12, 12, 12, 26);
         $pdf->displayTitle('<b><i>' . __('Cartridge type'), __('State'), __('Add date'), __('Use date'), __('End date'), __('Printer counter') . '</b></i>');
         $stock_time = 0;
         $use_time = 0;
         $pages_printed = 0;
         $nb_pages_printed = 0;
         while ($data = $DB->fetch_array($result)) {
             $date_in = Html::convDate($data["date_in"]);
             $date_use = Html::convDate($data["date_use"]);
             $date_out = Html::convDate($data["date_out"]);
             $col1 = sprintf(__('%1$s - %2$s'), $data["name"], $data["ref"]);
             $col2 = Cartridge::getStatus($data["date_use"], $data["date_out"]);
             $col6 = '';
             $tmp_dbeg = explode("-", $data["date_in"]);
             $tmp_dend = explode("-", $data["date_use"]);
             $stock_time_tmp = mktime(0, 0, 0, $tmp_dend[1], $tmp_dend[2], $tmp_dend[0]) - mktime(0, 0, 0, $tmp_dbeg[1], $tmp_dbeg[2], $tmp_dbeg[0]);
             $stock_time += $stock_time_tmp;
             if ($old) {
                 $tmp_dbeg = explode("-", $data["date_use"]);
                 $tmp_dend = explode("-", $data["date_out"]);
                 $use_time_tmp = mktime(0, 0, 0, $tmp_dend[1], $tmp_dend[2], $tmp_dend[0]) - mktime(0, 0, 0, $tmp_dbeg[1], $tmp_dbeg[2], $tmp_dbeg[0]);
                 $use_time += $use_time_tmp;
                 $col6 = $data['pages'];
                 if ($pages < $data['pages']) {
                     $pages_printed += $data['pages'] - $pages;
                     $nb_pages_printed++;
                     $col6 = sprintf(__('%1$s (%2$s)'), $col6, __('%d printed pages'), $data['pages'] - $pages);
                     $pages = $data['pages'];
                 }
             }
             $pdf->displayLine($col1, $col2, $date_in, $date_use, $date_out, $col6);
         }
         // Each cartridge
     }
     if ($old) {
         if ($number > 0) {
             if ($nb_pages_printed == 0) {
                 $nb_pages_printed = 1;
             }
             $nbstock = round($stock_time / $number / 60 / 60 / 24 / 30.5, 1);
             $nbuse = round($use_time / $number / 60 / 60 / 24 / 30.5, 1);
             $pdf->setColumnsSize(33, 33, 34);
             $pdf->displayTitle("<b><i>" . sprintf(__('%1$s: %2$s'), __('Average time in stock') . "</i></b>", _n('%d month', '%d months', $nbstock), $nbstock), "<b><i>" . sprintf(__('%1$s: %2$s'), __('Average time in use') . "</i></b>", _n('%d month', '%d months', $nbuse), $nbuse), "<b><i>" . sprintf(__('%1$s: %2$s'), __('Average number of printed pages') . "</i></b>", round($pages_printed / $nb_pages_printed)));
         }
         $pdf->displaySpace();
     }
 }
Ejemplo n.º 18
0
 /**
  * Print an HTML array with contracts associated to the enterprise
  *
  * @since version 0.84
  *
  * @param $supplier   Supplier object
  *
  * @return Nothing (display)
  **/
 static function showForSupplier(Supplier $supplier)
 {
     global $DB, $CFG_GLPI;
     $ID = $supplier->fields['id'];
     if (!Session::haveRight("contract", "r") || !$supplier->can($ID, 'r')) {
         return false;
     }
     $canedit = $supplier->can($ID, 'w');
     $rand = mt_rand();
     $query = "SELECT `glpi_contracts`.*,\n                       `glpi_contracts_suppliers`.`id` AS assocID,\n                       `glpi_entities`.`id` AS entity\n                FROM `glpi_contracts_suppliers`, `glpi_contracts`\n                LEFT JOIN `glpi_entities` ON (`glpi_entities`.`id`=`glpi_contracts`.`entities_id`)\n                WHERE `glpi_contracts_suppliers`.`suppliers_id` = '{$ID}'\n                      AND `glpi_contracts_suppliers`.`contracts_id`=`glpi_contracts`.`id`" . getEntitiesRestrictRequest(" AND", "glpi_contracts", '', '', true) . "\n                ORDER BY `glpi_entities`.`completename`,\n                         `glpi_contracts`.`name`";
     $result = $DB->query($query);
     $contracts = array();
     $used = array();
     if ($number = $DB->numrows($result)) {
         while ($data = $DB->fetch_assoc($result)) {
             $contracts[$data['assocID']] = $data;
             $used[$data['id']] = $data['id'];
         }
     }
     if ($canedit) {
         echo "<div class='firstbloc'>";
         echo "<form name='contractsupplier_form{$rand}' id='contractsupplier_form{$rand}' method='post'\n                action='" . Toolbox::getItemTypeFormURL(__CLASS__) . "'>";
         echo "<input type='hidden' name='suppliers_id' value='{$ID}'>";
         echo "<table class='tab_cadre_fixe'>";
         echo "<tr class='tab_bg_2'><th colspan='2'>" . __('Add a contract') . "</th></tr>";
         echo "<tr class='tab_bg_1'><td class='right'>";
         Contract::dropdown(array('used' => $used, 'entity' => $supplier->fields["entities_id"], 'entity_sons' => $supplier->fields["is_recursive"], 'nochecklimit' => true));
         echo "</td><td class='center'>";
         echo "<input type='submit' name='add' value=\"" . _sx('button', 'Add') . "\" class='submit'>";
         echo "</td></tr>";
         echo "</table>";
         Html::closeForm();
         echo "</div>";
     }
     echo "<div class='spaced'>";
     if ($canedit && $number) {
         Html::openMassiveActionsForm('mass' . __CLASS__ . $rand);
         $massiveactionparams = array('num_displayed' => $number);
         Html::showMassiveActions(__CLASS__, $massiveactionparams);
     }
     echo "<table class='tab_cadre_fixe'>";
     echo "<tr>";
     if ($canedit && $number) {
         echo "<th width='10'>" . Html::getCheckAllAsCheckbox('mass' . __CLASS__ . $rand) . "</th>";
     }
     echo "<th>" . __('Name') . "</th>";
     echo "<th>" . __('Entity') . "</th>";
     echo "<th>" . _x('phone', 'Number') . "</th>";
     echo "<th>" . __('Contract type') . "</th>";
     echo "<th>" . __('Start date') . "</th>";
     echo "<th>" . __('Initial contract period') . "</th>";
     echo "</tr>";
     $used = array();
     foreach ($contracts as $data) {
         $cID = $data["id"];
         $used[$cID] = $cID;
         $assocID = $data["assocID"];
         echo "<tr class='tab_bg_1" . ($data["is_deleted"] ? "_2" : "") . "'>";
         if ($canedit) {
             echo "<td>";
             Html::showMassiveActionCheckBox(__CLASS__, $data["assocID"]);
             echo "</td>";
         }
         $name = $data["name"];
         if ($_SESSION["glpiis_ids_visible"] || empty($data["name"])) {
             $name = sprintf(__('%1$s (%2$s)'), $name, $data["id"]);
         }
         echo "<td class='center b'>\n               <a href='" . $CFG_GLPI["root_doc"] . "/front/contract.form.php?id={$cID}'>" . $name . "</a>";
         echo "</td>";
         echo "<td class='center'>" . Dropdown::getDropdownName("glpi_entities", $data["entity"]);
         echo "</td><td class='center'>" . $data["num"] . "</td>";
         echo "<td class='center'>" . Dropdown::getDropdownName("glpi_contracttypes", $data["contracttypes_id"]) . "</td>";
         echo "<td class='center'>" . Html::convDate($data["begin_date"]) . "</td>";
         echo "<td class='center'>";
         sprintf(_n('%d month', '%d months', $data["duration"]), $data["duration"]);
         if ($data["begin_date"] != '' && !empty($data["begin_date"])) {
             echo " -> " . Infocom::getWarrantyExpir($data["begin_date"], $data["duration"], 0, true);
         }
         echo "</td>";
         echo "</tr>";
     }
     echo "</table>";
     if ($canedit && $number) {
         $paramsma['ontop'] = false;
         Html::showMassiveActions(__CLASS__, $paramsma);
         Html::closeForm();
     }
     echo "</div>";
 }
Ejemplo n.º 19
0
 /**
  * Print the contract costs
  *
  * @param $contract               Contract object
  * @param $withtemplate  boolean  Template or basic item (default '')
  *
  * @return Nothing (call to classes members)
  **/
 static function showForContract(Contract $contract, $withtemplate = '')
 {
     global $DB, $CFG_GLPI;
     $ID = $contract->fields['id'];
     if (!$contract->getFromDB($ID) || !$contract->can($ID, READ)) {
         return false;
     }
     $canedit = $contract->can($ID, UPDATE);
     echo "<div class='center'>";
     $query = "SELECT *\n                FROM `glpi_contractcosts`\n                WHERE `contracts_id` = '{$ID}'\n                ORDER BY `begin_date`";
     $rand = mt_rand();
     if ($canedit) {
         echo "<div id='viewcost" . $ID . "_{$rand}'></div>\n";
         echo "<script type='text/javascript' >\n";
         echo "function viewAddCost" . $ID . "_{$rand}() {\n";
         $params = array('type' => __CLASS__, 'parenttype' => 'Contract', 'contracts_id' => $ID, 'id' => -1);
         Ajax::updateItemJsCode("viewcost" . $ID . "_{$rand}", $CFG_GLPI["root_doc"] . "/ajax/viewsubitem.php", $params);
         echo "};";
         echo "</script>\n";
         echo "<div class='center firstbloc'>" . "<a class='vsubmit' href='javascript:viewAddCost" . $ID . "_{$rand}();'>";
         echo __('Add a new cost') . "</a></div>\n";
     }
     if ($result = $DB->query($query)) {
         echo "<table class='tab_cadre_fixehov'>";
         echo "<tr><th colspan='5'>" . self::getTypeName($DB->numrows($result)) . "</th></tr>";
         if ($DB->numrows($result)) {
             echo "<tr><th>" . __('Name') . "</th>";
             echo "<th>" . __('Begin date') . "</th>";
             echo "<th>" . __('End date') . "</th>";
             echo "<th>" . __('Budget') . "</th>";
             echo "<th>" . __('Cost') . "</th>";
             echo "</tr>";
             Session::initNavigateListItems(__CLASS__, sprintf(__('%1$s = %2$s'), Contract::getTypeName(1), $contract->getName()));
             $total = 0;
             while ($data = $DB->fetch_assoc($result)) {
                 echo "<tr class='tab_bg_2' " . ($canedit ? "style='cursor:pointer' onClick=\"viewEditCost" . $data['contracts_id'] . "_" . $data['id'] . "_{$rand}();\"" : '') . ">";
                 $name = empty($data['name']) ? sprintf(__('%1$s (%2$s)'), $data['name'], $data['id']) : $data['name'];
                 echo "<td>";
                 printf(__('%1$s %2$s'), $name, Html::showToolTip($data['comment'], array('display' => false)));
                 if ($canedit) {
                     echo "\n<script type='text/javascript' >\n";
                     echo "function viewEditCost" . $data['contracts_id'] . "_" . $data["id"] . "_{$rand}() {\n";
                     $params = array('type' => __CLASS__, 'parenttype' => 'Contract', 'contracts_id' => $data["contracts_id"], 'id' => $data["id"]);
                     Ajax::updateItemJsCode("viewcost" . $ID . "_{$rand}", $CFG_GLPI["root_doc"] . "/ajax/viewsubitem.php", $params);
                     echo "};";
                     echo "</script>\n";
                 }
                 echo "</td>";
                 echo "<td>" . Html::convDate($data['begin_date']) . "</td>";
                 echo "<td>" . Html::convDate($data['end_date']) . "</td>";
                 echo "<td>" . Dropdown::getDropdownName('glpi_budgets', $data['budgets_id']) . "</td>";
                 echo "<td class='numeric'>" . Html::formatNumber($data['cost']) . "</td>";
                 $total += $data['cost'];
                 echo "</tr>";
                 Session::addToNavigateListItems(__CLASS__, $data['id']);
             }
             echo "<tr class='b noHover'><td colspan='3'>&nbsp;</td>";
             echo "<td class='right'>" . __('Total cost') . '</td>';
             echo "<td class='numeric'>" . Html::formatNumber($total) . '</td></tr>';
         } else {
             echo "<tr><th colspan='5'>" . __('No item found') . "</th></tr>";
         }
         echo "</table>";
     }
     echo "</div><br>";
 }
Ejemplo n.º 20
0
 /**
  * Cron action on contracts : alert depending of the config : on notice and expire
  *
  * @param $task for log, if NULL display (default NULL)
  **/
 static function cronContract($task = NULL)
 {
     global $DB, $CFG_GLPI;
     if (!$CFG_GLPI["use_mailing"]) {
         return 0;
     }
     $message = array();
     $items_notice = array();
     $items_end = array();
     $cron_status = 0;
     $contract_infos[Alert::END] = array();
     $contract_infos[Alert::NOTICE] = array();
     $contract_messages = array();
     foreach (Entity::getEntitiesToNotify('use_contracts_alert') as $entity => $value) {
         $before = Entity::getUsedConfig('send_contracts_alert_before_delay', $entity);
         $query_notice = "SELECT `glpi_contracts`.*\n                          FROM `glpi_contracts`\n                          LEFT JOIN `glpi_alerts`\n                              ON (`glpi_contracts`.`id` = `glpi_alerts`.`items_id`\n                                  AND `glpi_alerts`.`itemtype` = 'Contract'\n                                  AND `glpi_alerts`.`type`='" . Alert::NOTICE . "')\n                          WHERE (`glpi_contracts`.`alert` & " . pow(2, Alert::NOTICE) . ") >'0'\n                                AND `glpi_contracts`.`is_deleted` = '0'\n                                AND `glpi_contracts`.`begin_date` IS NOT NULL\n                                AND `glpi_contracts`.`duration` <> '0'\n                                AND `glpi_contracts`.`notice` <> '0'\n                                AND DATEDIFF(ADDDATE(`glpi_contracts`.`begin_date`,\n                                                     INTERVAL `glpi_contracts`.`duration` MONTH),\n                                             CURDATE()) > '0'\n                                AND DATEDIFF(ADDDATE(`glpi_contracts`.`begin_date`,\n                                                     INTERVAL (`glpi_contracts`.`duration`\n                                                                -`glpi_contracts`.`notice`) MONTH),\n                                             CURDATE()) < '{$before}'\n                                AND `glpi_alerts`.`date` IS NULL\n                                AND `glpi_contracts`.`entities_id` = '" . $entity . "'";
         $query_end = "SELECT `glpi_contracts`.*\n                       FROM `glpi_contracts`\n                       LEFT JOIN `glpi_alerts`\n                           ON (`glpi_contracts`.`id` = `glpi_alerts`.`items_id`\n                               AND `glpi_alerts`.`itemtype` = 'Contract'\n                               AND `glpi_alerts`.`type`='" . Alert::END . "')\n                       WHERE (`glpi_contracts`.`alert` & " . pow(2, Alert::END) . ") > '0'\n                             AND `glpi_contracts`.`is_deleted` = '0'\n                             AND `glpi_contracts`.`begin_date` IS NOT NULL\n                             AND `glpi_contracts`.`duration` <> '0'\n                             AND DATEDIFF(ADDDATE(`glpi_contracts`.`begin_date`,\n                                                  INTERVAL (`glpi_contracts`.`duration`) MONTH),\n                                          CURDATE()) < '{$before}'\n                             AND `glpi_alerts`.`date` IS NULL\n                             AND `glpi_contracts`.`entities_id` = '" . $entity . "'";
         $querys = array('notice' => $query_notice, 'end' => $query_end);
         foreach ($querys as $type => $query) {
             foreach ($DB->request($query) as $data) {
                 $entity = $data['entities_id'];
                 $message = sprintf(__('%1$s: %2$s') . "<br>\n", $data["name"], Infocom::getWarrantyExpir($data["begin_date"], $data["duration"], $data["notice"]));
                 $contract_infos[$type][$entity][$data['id']] = $data;
                 if (!isset($contract_messages[$type][$entity])) {
                     switch ($type) {
                         case 'notice':
                             $contract_messages[$type][$entity] = __('Contract entered in notice time') . "<br>";
                             break;
                         case 'end':
                             $contract_messages[$type][$entity] = __('Contract ended') . "<br>";
                             break;
                     }
                 }
                 $contract_messages[$type][$entity] .= $message;
             }
         }
         // Get contrats with periodicity alerts
         $query_periodicity = "SELECT `glpi_contracts`.*\n                               FROM `glpi_contracts`\n                               WHERE `glpi_contracts`.`alert` & " . pow(2, Alert::PERIODICITY) . " > '0'\n                                     AND `glpi_contracts`.`entities_id` = '" . $entity . "' ";
         // Foreach ones :
         foreach ($DB->request($query_periodicity) as $data) {
             $entity = $data['entities_id'];
             // Compute end date + 12 month : do not send alerts after
             $end_alert = date('Y-m-d', strtotime($data['begin_date'] . " +" . ($data['duration'] + 12) . " month"));
             if (!empty($data['begin_date']) && $data['periodicity'] && $end_alert > date('Y-m-d')) {
                 $todo = array('periodicity' => Alert::PERIODICITY);
                 if ($data['alert'] & pow(2, Alert::NOTICE)) {
                     $todo['periodicitynotice'] = Alert::NOTICE;
                 }
                 // Get previous alerts
                 foreach ($todo as $type => $event) {
                     $previous_alerts[$type] = Alert::getAlertDate(__CLASS__, $data['id'], $event);
                 }
                 // compute next alert date based on already send alerts (or not)
                 foreach ($todo as $type => $event) {
                     $next_alerts[$type] = date('Y-m-d', strtotime($data['begin_date'] . " -" . $before . " day"));
                     if ($type == Alert::NOTICE) {
                         $next_alerts[$type] = date('Y-m-d', strtotime($next_alerts[$type] . " -" . $data['notice'] . " month"));
                     }
                     $today_limit = date('Y-m-d', strtotime(date('Y-m-d') . " -" . $data['periodicity'] . " month"));
                     // Init previous by begin date if not set
                     if (empty($previous_alerts[$type])) {
                         $previous_alerts[$type] = $today_limit;
                     }
                     while ($next_alerts[$type] < $previous_alerts[$type] && $next_alerts[$type] < $end_alert) {
                         $next_alerts[$type] = date('Y-m-d', strtotime($next_alerts[$type] . " +" . $data['periodicity'] . " month"));
                     }
                     // If this date is passed : clean alerts and send again
                     if ($next_alerts[$type] <= date('Y-m-d')) {
                         $alert = new Alert();
                         $alert->clear(__CLASS__, $data['id'], $event);
                         $real_alert_date = date('Y-m-d', strtotime($next_alerts[$type] . " +" . $before . " day"));
                         $message = sprintf(__('%1$s: %2$s') . "<br>\n", $data["name"], Html::convDate($real_alert_date));
                         $data['alert_date'] = $real_alert_date;
                         $data['items'] = Contract_Item::getItemsForContract($data['id'], $entity);
                         $contract_infos[$type][$entity][$data['id']] = $data;
                         switch ($type) {
                             case 'periodicitynotice':
                                 $contract_messages[$type][$entity] = __('Contract entered in notice time for period') . "<br>";
                                 break;
                             case 'periodicity':
                                 $contract_messages[$type][$entity] = __('Contract period ended') . "<br>";
                                 break;
                         }
                         $contract_messages[$type][$entity] .= $message;
                     }
                 }
             }
         }
     }
     foreach (array('notice' => Alert::NOTICE, 'end' => Alert::END, 'periodicity' => Alert::PERIODICITY, 'periodicitynotice' => Alert::NOTICE) as $event => $type) {
         if (isset($contract_infos[$event]) && count($contract_infos[$event])) {
             foreach ($contract_infos[$event] as $entity => $contracts) {
                 if (NotificationEvent::raiseEvent($event, new self(), array('entities_id' => $entity, 'items' => $contracts))) {
                     $message = $contract_messages[$event][$entity];
                     $cron_status = 1;
                     $entityname = Dropdown::getDropdownName("glpi_entities", $entity);
                     if ($task) {
                         $task->log(sprintf(__('%1$s: %2$s') . "\n", $entityname, $message));
                         $task->addVolume(1);
                     } else {
                         Session::addMessageAfterRedirect(sprintf(__('%1$s: %2$s'), $entityname, $message));
                     }
                     $alert = new Alert();
                     $input["itemtype"] = __CLASS__;
                     $input["type"] = $type;
                     foreach ($contracts as $id => $contract) {
                         $input["items_id"] = $id;
                         $alert->add($input);
                         unset($alert->fields['id']);
                     }
                 } else {
                     $entityname = Dropdown::getDropdownName('glpi_entities', $entity);
                     //TRANS: %1$s is entity name, %2$s is the message
                     $msg = sprintf(__('%1$s: %2$s'), $entityname, __('send contract alert failed'));
                     if ($task) {
                         $task->log($msg);
                     } else {
                         Session::addMessageAfterRedirect($msg, false, ERROR);
                     }
                 }
             }
         }
     }
     return $cron_status;
 }
Ejemplo n.º 21
0
 /**
  * Show holidays for a calendar
  *
  * @param $calendar Calendar object
  **/
 static function showForCalendar(Calendar $calendar)
 {
     global $DB, $CFG_GLPI;
     $ID = $calendar->getField('id');
     if (!$calendar->can($ID, 'r')) {
         return false;
     }
     $canedit = $calendar->can($ID, 'w');
     $rand = mt_rand();
     $query = "SELECT DISTINCT `glpi_calendars_holidays`.`id` AS linkID,\n                                `glpi_holidays`.*\n                FROM `glpi_calendars_holidays`\n                LEFT JOIN `glpi_holidays`\n                     ON (`glpi_calendars_holidays`.`holidays_id` = `glpi_holidays`.`id`)\n                WHERE `glpi_calendars_holidays`.`calendars_id` = '{$ID}'\n                ORDER BY `glpi_holidays`.`name`";
     $result = $DB->query($query);
     $holidays = array();
     $used = array();
     if ($numrows = $DB->numrows($result)) {
         while ($data = $DB->fetch_assoc($result)) {
             $holidays[$data['id']] = $data;
             $used[$data['id']] = $data['id'];
         }
     }
     if ($canedit) {
         echo "<div class='firstbloc'>";
         echo "<form name='calendarsegment_form{$rand}' id='calendarsegment_form{$rand}' method='post'\n                action='";
         echo Toolbox::getItemTypeFormURL(__CLASS__) . "'>";
         echo "<table class='tab_cadre_fixe'>";
         echo "<tr class='tab_bg_1'><th colspan='7'>" . __('Add a close time') . "</tr>";
         echo "<tr class='tab_bg_2'><td class='right'  colspan='4'>";
         echo "<input type='hidden' name='calendars_id' value='{$ID}'>";
         Holiday::dropdown(array('used' => $used, 'entity' => $calendar->fields["entities_id"]));
         echo "</td><td class='center'>";
         echo "<input type='submit' name='add' value=\"" . _sx('button', 'Add') . "\" class='submit'>";
         echo "</td></tr>";
         echo "</table>";
         Html::closeForm();
         echo "</div>";
     }
     echo "<div class='spaced'>";
     if ($canedit && $numrows) {
         Html::openMassiveActionsForm('mass' . __CLASS__ . $rand);
         $paramsma = array('num_displayed' => $numrows);
         Html::showMassiveActions(__CLASS__, $paramsma);
     }
     echo "<table class='tab_cadre_fixehov'>";
     echo "<tr>";
     if ($canedit && $numrows) {
         echo "<th width='10'>";
         Html::checkAllAsCheckbox('mass' . __CLASS__ . $rand);
         echo "</th>";
     }
     echo "<th>" . __('Name') . "</th>";
     echo "<th>" . __('Start') . "</th>";
     echo "<th>" . __('End') . "</th>";
     echo "<th>" . __('Recurrent') . "</th>";
     echo "</tr>";
     $used = array();
     if ($numrows) {
         Session::initNavigateListItems('Holiday', sprintf(__('%1$s = %2$s'), Calendar::getTypeName(1), $calendar->fields["name"]));
         foreach ($holidays as $data) {
             Session::addToNavigateListItems('Holiday', $data["id"]);
             echo "<tr class='tab_bg_1'>";
             if ($canedit) {
                 echo "<td>";
                 Html::showMassiveActionCheckBox(__CLASS__, $data["linkID"]);
                 echo "</td>";
             }
             echo "<td><a href='" . Toolbox::getItemTypeFormURL('Holiday') . "?id=" . $data['id'] . "'>" . $data["name"] . "</a></td>";
             echo "<td>" . Html::convDate($data["begin_date"]) . "</td>";
             echo "<td>" . Html::convDate($data["end_date"]) . "</td>";
             echo "<td>" . Dropdown::getYesNo($data["is_perpetual"]) . "</td>";
             echo "</tr>";
         }
     }
     echo "</table>";
     if ($canedit && $numrows) {
         $paramsma['ontop'] = false;
         Html::showMassiveActions(__CLASS__, $paramsma);
         Html::closeForm();
     }
     echo "</div>";
 }
Ejemplo n.º 22
0
 public function showOrderReception($orders_id)
 {
     global $DB, $CFG_GLPI;
     $order_order = new PluginOrderOrder();
     $order_item = new PluginOrderOrder_Item();
     $reference = new PluginOrderReference();
     $order_order->getFromDB($orders_id);
     Session::initNavigateListItems($this->getType(), __("Order", "order") . " = " . $order_order->fields["name"]);
     $canedit = self::canCreate() && !$order_order->canUpdateOrder() && !$order_order->isCanceled();
     $result_ref = $order_item->queryDetail($orders_id);
     $numref = $DB->numrows($result_ref);
     while ($data_ref = $DB->fetch_array($result_ref)) {
         echo "<div class='center'><table class='tab_cadre_fixe'>";
         if (!$numref) {
             echo "<tr><th>" . __("No item to take delivery of", "order") . "</th></tr></table></div>";
         } else {
             $references_id = $data_ref["id"];
             $typeRef = $data_ref["itemtype"];
             $price_taxfree = $data_ref["price_taxfree"];
             $discount = $data_ref["discount"];
             $item = new $typeRef();
             $rand = mt_rand();
             echo "<tr><th><ul><li>";
             echo "<a href=\"javascript:showHideDiv('reception{$rand}','reception_img{$rand}', '" . $CFG_GLPI['root_doc'] . "/pics/plus.png','" . $CFG_GLPI['root_doc'] . "/pics/moins.png');\">";
             echo "<img alt='' name='reception_img{$rand}' src=\"" . $CFG_GLPI['root_doc'] . "/pics/plus.png\">";
             echo "</a>";
             echo "</li></ul></th>";
             echo "<th>" . __("Type") . "</th>";
             echo "<th>" . __("Manufacturer") . "</th>";
             echo "<th>" . __("Product reference", "order") . "</th>";
             echo "<th>" . __("Delivered items", "order") . "</th>";
             echo "</tr>";
             echo "<tr class='tab_bg_1 center'>";
             echo "<td></td>";
             echo "<td align='center'>" . $item->getTypeName() . "</td>";
             echo "<td align='center'>" . Dropdown::getDropdownName("glpi_manufacturers", $data_ref["manufacturers_id"]) . "</td>";
             echo "<td>" . $reference->getReceptionReferenceLink($data_ref) . "</td>";
             $total = $order_item->getTotalQuantityByRefAndDiscount($orders_id, $references_id, $data_ref["price_taxfree"], $data_ref["discount"]);
             echo "<td>" . $order_item->getDeliveredQuantity($orders_id, $references_id, $data_ref["price_taxfree"], $data_ref["discount"]) . " / " . $total . "</td>";
             echo "</tr></table>";
             echo "<div class='center' id='reception{$rand}' style='display:none'>";
             echo "<form method='post' name='order_reception_form{$rand}' id='order_reception_form{$rand}'" . " action=\"" . Toolbox::getItemTypeFormURL("PluginOrderReception") . "\">";
             echo "<table class='tab_cadre_fixe'>";
             echo "<tr>";
             echo "<th width='15'></th>";
             if ($typeRef != 'SoftwareLicense') {
                 echo "<th>" . __("ID") . "</th>";
             }
             echo "<th>" . __("Reference") . "</th>";
             echo "<th>" . __("Status") . "</th>";
             echo "<th>" . __("Delivery date") . "</th>";
             echo "<th>" . __("Delivery form") . "</th>";
             echo "<th>" . __("Delivery status", "order") . "</th>";
             echo "</tr>";
             $query = "SELECT `glpi_plugin_order_orders_items`.`id` AS IDD,\n                             `glpi_plugin_order_references`.`id` AS id,\n                             `glpi_plugin_order_references`.`templates_id`,\n                             `glpi_plugin_order_orders_items`.`states_id`,\n                             `glpi_plugin_order_orders_items`.`comment`,\n                             `glpi_plugin_order_orders_items`.`plugin_order_deliverystates_id`,\n                             `glpi_plugin_order_orders_items`.`delivery_date`,\n                             `glpi_plugin_order_orders_items`.`delivery_number`,\n                             `glpi_plugin_order_references`.`name`,\n                             `glpi_plugin_order_references`.`itemtype`,\n                             `glpi_plugin_order_orders_items`.`items_id`\n                    FROM `glpi_plugin_order_orders_items`, `glpi_plugin_order_references`\n                    WHERE `plugin_order_orders_id` = '{$orders_id}'\n                    AND `glpi_plugin_order_orders_items`.`plugin_order_references_id` = '" . $references_id . "'\n                    AND `glpi_plugin_order_orders_items`.`plugin_order_references_id` = `glpi_plugin_order_references`.`id`\n                    AND `glpi_plugin_order_orders_items`.`discount` LIKE '" . $discount . "'\n                    AND `glpi_plugin_order_orders_items`.`price_taxfree` LIKE '" . $price_taxfree . "' ";
             if ($typeRef == 'SoftwareLicense') {
                 $query .= " GROUP BY `glpi_plugin_order_references`.`name` ";
             }
             $query .= " ORDER BY `glpi_plugin_order_references`.`name` ";
             $result = $DB->query($query);
             $num = $DB->numrows($result);
             while ($data = $DB->fetch_array($result)) {
                 $random = mt_rand();
                 $detailID = $data["IDD"];
                 Session::addToNavigateListItems($this->getType(), $detailID);
                 echo "<tr class='tab_bg_2'>";
                 $status = 1;
                 if ($typeRef != 'SoftwareLicense') {
                     $status = $this->checkThisItemStatus($detailID, PluginOrderOrder::ORDER_DEVICE_NOT_DELIVRED);
                 }
                 if ($order_order->canDeliver() && $status) {
                     echo "<td width='15' align='left'>";
                     $sel = "";
                     if (isset($_GET["select"]) && $_GET["select"] == "all") {
                         $sel = "checked";
                     }
                     echo "<input type='checkbox' name='item[" . $detailID . "]' value='1' {$sel}>";
                     echo "</td>";
                 } else {
                     echo "<td width='15' align='left'></td>";
                 }
                 if ($typeRef != 'SoftwareLicense') {
                     echo "<td align='center'>" . $data["IDD"] . "&nbsp;";
                     Html::showTooltip($data['comment']);
                     echo "</td>";
                 }
                 echo "<td align='center'>" . $reference->getReceptionReferenceLink($data) . "</td>";
                 echo "<td align='center'>";
                 $link = Toolbox::getItemTypeFormURL($this->getType());
                 if ($canedit && $data["states_id"] == PluginOrderOrder::ORDER_DEVICE_DELIVRED) {
                     echo "<a href=\"" . $link . "?id=" . $data["IDD"] . "\">";
                 }
                 echo $this->getReceptionStatus($detailID);
                 if ($canedit && $data["states_id"] == PluginOrderOrder::ORDER_DEVICE_DELIVRED) {
                     echo "</a>";
                 }
                 echo "</td>";
                 echo "<td align='center'>" . Html::convDate($data["delivery_date"]) . "</td>";
                 echo "<td align='center'>" . $data["delivery_number"] . "</td>";
                 echo "<td align='center'>" . Dropdown::getDropdownName("glpi_plugin_order_deliverystates", $data["plugin_order_deliverystates_id"]) . "</td>";
                 echo "<input type='hidden' name='id[{$detailID}]' value='{$detailID}'>";
                 echo "<input type='hidden' name='name[{$detailID}]' value='" . $data["name"] . "'>";
                 echo "<input type='hidden' name='plugin_order_references_id[{$detailID}]' value='" . $data["id"] . "'>";
                 echo "<input type='hidden' name='itemtype[{$detailID}]' value='" . $data["itemtype"] . "'>";
                 echo "<input type='hidden' name='templates_id[{$detailID}]' value='" . $data["templates_id"] . "'>";
                 echo "<input type='hidden' name='states_id[{$detailID}]' value='" . $data["states_id"] . "'>";
             }
             echo "</table>";
             if ($order_order->canDeliver() && $this->checkItemStatus($orders_id, $references_id, PluginOrderOrder::ORDER_DEVICE_NOT_DELIVRED)) {
                 Html::openArrowMassives("order_reception_form{$rand}", true);
                 echo "<input type='hidden' name='plugin_order_orders_id' value='{$orders_id}'>";
                 $this->dropdownReceptionActions($typeRef, $references_id, $orders_id);
                 Html::closeArrowMassives(array());
                 $rand = mt_rand();
                 if ($typeRef != 'SoftwareLicense') {
                     echo "<div id='massreception" . $orders_id . $rand . "'></div>\n";
                     echo "<script type='text/javascript' >\n";
                     echo "function viewmassreception" . $orders_id . "{$rand}(){\n";
                     $params = array('plugin_order_orders_id' => $orders_id, 'plugin_order_references_id' => $references_id);
                     Ajax::updateItemJsCode("massreception" . $orders_id . $rand, $CFG_GLPI["root_doc"] . "/plugins/order/ajax/massreception.php", $params, false);
                     echo "};";
                     echo "</script>\n";
                     echo "<p><a href='javascript:viewmassreception" . $orders_id . "{$rand}();'>";
                     echo __("Take item delivery (bulk)", "order") . "</a></p><br>\n";
                 }
             }
             Html::closeForm();
             echo "</div>";
         }
         echo "<br>";
     }
 }
Ejemplo n.º 23
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>";
     }
 }
        if ($data["name"] == NULL) {
            $name .= "(" . $data["ID"] . ")";
        } else {
            $name .= $data["name"];
        }
        $name .= "</a>";
        echo Search::showItem($output_type, $name, $num, $key);
        echo Search::showItem($output_type, $data['firstname'], $num, $key);
        echo Search::showItem($output_type, $data['registration_number'], $num, $key);
        $link1 = Toolbox::getItemTypeFormURL("PluginResourcesProfession");
        $profName = "<a href='" . $link1 . "?id=" . $data["profID"] . "' target='_blank'>" . $data["profession"] . "</a>";
        echo Search::showItem($output_type, $profName, $num, $key);
        echo Search::showItem($output_type, Html::convDate($data['date_begin']), $num, $key);
        echo Search::showItem($output_type, Html::convDate($data['date_end']), $num, $key);
        echo Search::showItem($output_type, Html::convDate($data['begin_date']), $num, $key);
        echo Search::showItem($output_type, Html::convDate($data['end_date']), $num, $key);
        echo Search::showEndLine($output_type);
    }
    echo Search::showFooter($output_type, $title);
}
if ($output_type == Search::HTML_OUTPUT) {
    Html::footer();
}
/**
 * Display the column title and allow the sort
 *
 * @param $output_type
 * @param $num
 * @param $title
 * @param $columnname
 * @param bool $sort
Ejemplo n.º 25
0
 /**
  * Cron action on tasks : ExpiredTasks
  *
  * @param $task for log, if NULL display
  *
  **/
 static function cronResourcesTask($task = NULL)
 {
     global $DB, $CFG_GLPI;
     if (!$CFG_GLPI["use_mailing"]) {
         return 0;
     }
     $message = array();
     $cron_status = 0;
     $resourcetask = new self();
     $query_expired = $resourcetask->queryAlert();
     $querys = array(Alert::END => $query_expired);
     $task_infos = array();
     $task_messages = array();
     foreach ($querys as $type => $query) {
         $task_infos[$type] = array();
         foreach ($DB->request($query) as $data) {
             $entity = $data['entities_id'];
             $message = $data["name"] . ": " . Html::convDate($data["date_end"]) . "<br>\n";
             $task_infos[$type][$entity][] = $data;
             if (!isset($tasks_infos[$type][$entity])) {
                 $task_messages[$type][$entity] = __('Not finished tasks', 'resources') . "<br />";
             }
             $task_messages[$type][$entity] .= $message;
         }
     }
     foreach ($querys as $type => $query) {
         foreach ($task_infos[$type] as $entity => $tasks) {
             Plugin::loadLang('resources');
             if (NotificationEvent::raiseEvent("AlertExpiredTasks", new PluginResourcesResource(), array('entities_id' => $entity, 'tasks' => $tasks))) {
                 $message = $task_messages[$type][$entity];
                 $cron_status = 1;
                 if ($task) {
                     $task->log(Dropdown::getDropdownName("glpi_entities", $entity) . ":  {$message}\n");
                     $task->addVolume(1);
                 } else {
                     Session::addMessageAfterRedirect(Dropdown::getDropdownName("glpi_entities", $entity) . ":  {$message}");
                 }
             } else {
                 if ($task) {
                     $task->log(Dropdown::getDropdownName("glpi_entities", $entity) . ":  Send tasks alert failed\n");
                 } else {
                     Session::addMessageAfterRedirect(Dropdown::getDropdownName("glpi_entities", $entity) . ":  Send tasks alert failed", false, ERROR);
                 }
             }
         }
     }
     return $cron_status;
 }
Ejemplo n.º 26
0
 public function generateOrder($params)
 {
     global $DB;
     $ID = $params['id'];
     $template = $params['template'];
     $signature = $params['sign'];
     if ($template) {
         $config = array('PATH_TO_TMP' => GLPI_DOC_DIR . '/_tmp');
         $odf = new Odtphp\Odf(PLUGIN_ORDER_TEMPLATE_DIR . "{$template}", $config);
         $this->getFromDB($ID);
         if (file_exists(PLUGIN_ORDER_TEMPLATE_CUSTOM_DIR . "custom.php")) {
             include_once PLUGIN_ORDER_TEMPLATE_CUSTOM_DIR . "custom.php";
         }
         if (function_exists("plugin_order_getCustomFieldsForODT")) {
             plugin_order_getCustomFieldsForODT($ID, $template, $odf, $signature);
         } else {
             $PluginOrderOrder_Item = new PluginOrderOrder_Item();
             $PluginOrderReference_Supplier = new PluginOrderReference_Supplier();
             try {
                 $odf->setImage('logo', PLUGIN_ORDER_TEMPLATE_LOGO_DIR . '/logo.jpg');
             } catch (\Odtphp\Exceptions\OdfException $e) {
             }
             $values = array();
             $values['title_order'] = __("Order number", "order");
             $values['num_order'] = $this->fields["num_order"];
             $values['title_invoice_address'] = __("Invoice address", "order");
             $values['comment_order'] = $this->fields["comment"];
             $entity = new Entity();
             $entity->getFromDB($this->fields["entities_id"]);
             $town = '';
             if ($this->fields["entities_id"] != 0) {
                 $name_entity = $entity->fields["name"];
             } else {
                 $name_entity = __("Root entity");
             }
             $values['entity_name'] = $name_entity;
             if ($entity->getFromDB($this->fields["entities_id"])) {
                 $town = $entity->fields["town"];
                 $values['entity_address'] = $entity->fields["address"];
                 $values['entity_postcode'] = $entity->fields["postcode"];
                 $values['entity_town'] = $entity->fields["town"];
                 $values['entity_country'] = $entity->fields["country"];
             }
             $supplier = new Supplier();
             if ($supplier->getFromDB($this->fields["suppliers_id"])) {
                 $values['supplier_name'] = $supplier->fields["name"];
                 $values['supplier_address'] = $supplier->fields["address"];
                 $values['supplier_postcode'] = $supplier->fields["postcode"];
                 $values['supplier_town'] = $supplier->fields["town"];
                 $values['supplier_country'] = $supplier->fields["country"];
             }
             $location = new Location();
             if ($location->getFromDB($this->fields["locations_id"])) {
                 $values['title_delivery_address'] = __("Delivery address", "order");
                 $values['comment_delivery_address'] = $location->fields['comment'];
             }
             if ($town) {
                 $town = $town . ", ";
             }
             $order_date = Html::convDate($this->fields["order_date"]);
             $username = Html::clean(getUserName(Session::getLoginUserID()));
             $values['title_date_order'] = $town . __("The", "order") . " ";
             $values['date_order'] = $order_date;
             $values['title_sender'] = __("Issuer order", "order");
             $values['sender'] = $username;
             $values['title_budget'] = __("Budget");
             $budget = new Budget();
             if ($budget->getFromDB($this->fields["budgets_id"])) {
                 $values['budget'] = $budget->fields['name'];
             } else {
                 $values['budget'] = '';
             }
             $output = '';
             $contact = new Contact();
             if ($contact->getFromDB($this->fields["contacts_id"])) {
                 $output = formatUserName($contact->fields["id"], "", $contact->fields["name"], $contact->fields["firstname"]);
             }
             $values['title_recipient'] = __("Recipient", "order");
             $values['recipient'] = Html::clean($output);
             $values['nb'] = __("Quantity", "order");
             $values['title_item'] = __("Designation", "order");
             $values['title_ref'] = __("Reference");
             $values['HTPrice_item'] = __("Unit price", "order");
             $values['TVA_item'] = __("VAT", "order");
             $values['title_discount'] = __("Discount rate", "order");
             $values['HTPriceTotal_item'] = __("Sum tax free", "order");
             $values['ATIPriceTotal_item'] = __("Price ATI", "order");
             $listeArticles = array();
             $result = $PluginOrderOrder_Item->queryDetail($ID);
             $num = $DB->numrows($result);
             while ($data = $DB->fetch_array($result)) {
                 $quantity = $PluginOrderOrder_Item->getTotalQuantityByRefAndDiscount($ID, $data["id"], $data["price_taxfree"], $data["discount"]);
                 $listeArticles[] = array('quantity' => $quantity, 'ref' => utf8_decode($data["name"]), 'taxe' => Dropdown::getDropdownName(getTableForItemType("PluginOrderOrderTax"), $data["plugin_order_ordertaxes_id"]), 'refnumber' => $PluginOrderReference_Supplier->getReferenceCodeByReferenceAndSupplier($data["id"], $this->fields["suppliers_id"]), 'price_taxfree' => $data["price_taxfree"], 'discount' => $data["discount"], false, 0, 'price_discounted' => $data["price_discounted"] * $quantity, 'price_ati' => $data["price_ati"]);
             }
             $article = $odf->setSegment('articles');
             foreach ($listeArticles as $element) {
                 $article->nbA($element['quantity']);
                 $article->titleArticle($element['ref']);
                 $article->refArticle($element['refnumber']);
                 $article->TVAArticle($element['taxe']);
                 $article->HTPriceArticle(Html::clean(Html::formatNumber($element['price_taxfree'])));
                 if ($element['discount'] != 0) {
                     $article->discount(Html::clean(Html::formatNumber($element['discount'])) . " %");
                 } else {
                     $article->discount("");
                 }
                 $article->HTPriceTotalArticle(Html::clean(Html::formatNumber($element['price_discounted'])));
                 $total_TTC_Article = $element['price_discounted'] * (1 + $element['taxe'] / 100);
                 $article->ATIPriceTotalArticle(Html::clean(Html::formatNumber($total_TTC_Article)));
                 $article->merge();
             }
             $odf->mergeSegment($article);
             $prices = $PluginOrderOrder_Item->getAllPrices($ID);
             // total price (with postage)
             $postagewithTVA = $PluginOrderOrder_Item->getPricesATI($this->fields["port_price"], Dropdown::getDropdownName("glpi_plugin_order_ordertaxes", $this->fields["plugin_order_ordertaxes_id"]));
             $total_HT = $prices["priceHT"] + $this->fields["port_price"];
             $total_TVA = $prices["priceTVA"] + $postagewithTVA - $this->fields["port_price"];
             $total_TTC = $prices["priceTTC"] + $postagewithTVA;
             if ($signature) {
                 try {
                     $odf->setImage('sign', PLUGIN_ORDER_SIGNATURE_DIR . $signature);
                 } catch (\Odtphp\Exceptions\OdfException $e) {
                 }
             } else {
                 try {
                     $odf->setImage('sign', '../pics/nothing.gif');
                 } catch (\Odtphp\Exceptions\OdfException $e) {
                 }
             }
             $name = Dropdown::getDropdownName("glpi_plugin_order_orderpayments", $this->fields["plugin_order_orderpayments_id"]);
             $values['title_totalht'] = __("Price tax free", "order");
             $values['totalht'] = Html::clean(Html::formatNumber($prices['priceHT']));
             $values['title_port'] = __("Price tax free with postage", "order");
             $values['totalht_port_price'] = Html::clean(Html::formatNumber($total_HT));
             $values['title_price_port'] = __("Postage", "order");
             $values['price_port_tva'] = " (" . Html::clean(Dropdown::getDropdownName("glpi_plugin_order_ordertaxes", $this->fields["plugin_order_ordertaxes_id"])) . "%)";
             $values['port_price'] = Html::clean(Html::formatNumber($postagewithTVA));
             $values['title_tva'] = __("VAT", "order");
             $values['totaltva'] = Html::clean(Html::formatNumber($total_TVA));
             $values['title_totalttc'] = __("Price ATI", "order");
             $values['totalttc'] = Html::clean(Html::formatNumber($total_TTC));
             $values['title_money'] = __("€", "order");
             $values['title_sign'] = __("Signature of issuing order", "order");
             $values['title_conditions'] = __("Payment conditions", "order");
             $values['payment_conditions'] = $name;
             // Set variables in odt template
             foreach ($values as $field => $val) {
                 try {
                     $odf->setVars($field, $val, true, 'UTF-8');
                 } catch (\Odtphp\Exceptions\OdfException $e) {
                 }
             }
         }
         $message = "_";
         if (Session::isMultiEntitiesMode()) {
             $entity = new Entity();
             $entity->getFromDB($this->fields['entities_id']);
             $message .= $entity->getName();
         }
         $message .= "_" . $this->fields['num_order'] . "_";
         $message .= Html::convDateTime($_SESSION['glpi_currenttime']);
         $message = str_replace(" ", "_", $message);
         $outputfile = str_replace(".odt", $message . ".odt", $template);
         // We export the file
         $odf->exportAsAttachedFile($outputfile);
     }
 }
Ejemplo n.º 27
0
 /**
  * Show Licenses of a software
  *
  * @param $software Software object
  *
  * @return nothing
  **/
 static function showForSoftware(Software $software)
 {
     global $DB, $CFG_GLPI;
     $softwares_id = $software->getField('id');
     $license = new self();
     $computer = new Computer();
     if (!$software->can($softwares_id, READ)) {
         return false;
     }
     $columns = array('name' => __('Name'), 'entity' => __('Entity'), 'serial' => __('Serial number'), 'number' => _x('quantity', 'Number'), '_affected' => __('Affected computers'), 'typename' => __('Type'), 'buyname' => __('Purchase version'), 'usename' => __('Version in use'), 'expire' => __('Expiration'));
     if (!$software->isRecursive()) {
         unset($columns['entity']);
     }
     if (isset($_GET["start"])) {
         $start = $_GET["start"];
     } else {
         $start = 0;
     }
     if (isset($_GET["order"]) && $_GET["order"] == "DESC") {
         $order = "DESC";
     } else {
         $order = "ASC";
     }
     if (isset($_GET["sort"]) && !empty($_GET["sort"]) && isset($columns[$_GET["sort"]])) {
         $sort = "`" . $_GET["sort"] . "`";
     } else {
         $sort = "`entity` {$order}, `name`";
     }
     // Righ type is enough. Can add a License on a software we have Read access
     $canedit = Software::canUpdate();
     $showmassiveactions = $canedit;
     // Total Number of events
     $number = countElementsInTable("glpi_softwarelicenses", "glpi_softwarelicenses.softwares_id = {$softwares_id} " . getEntitiesRestrictRequest('AND', 'glpi_softwarelicenses', '', '', true));
     echo "<div class='spaced'>";
     Session::initNavigateListItems('SoftwareLicense', sprintf(__('%1$s = %2$s'), Software::getTypeName(1), $software->getName()));
     if ($canedit) {
         echo "<div class='center firstbloc'>";
         echo "<a class='vsubmit' href='softwarelicense.form.php?softwares_id={$softwares_id}'>" . _x('button', 'Add a license') . "</a>";
         echo "</div>";
     }
     $rand = mt_rand();
     $query = "SELECT `glpi_softwarelicenses`.*,\n                       `buyvers`.`name` AS buyname,\n                       `usevers`.`name` AS usename,\n                       `glpi_entities`.`completename` AS entity,\n                       `glpi_softwarelicensetypes`.`name` AS typename\n                FROM `glpi_softwarelicenses`\n                LEFT JOIN `glpi_softwareversions` AS buyvers\n                     ON (`buyvers`.`id` = `glpi_softwarelicenses`.`softwareversions_id_buy`)\n                LEFT JOIN `glpi_softwareversions` AS usevers\n                     ON (`usevers`.`id` = `glpi_softwarelicenses`.`softwareversions_id_use`)\n                LEFT JOIN `glpi_entities`\n                     ON (`glpi_entities`.`id` = `glpi_softwarelicenses`.`entities_id`)\n                LEFT JOIN `glpi_softwarelicensetypes`\n                     ON (`glpi_softwarelicensetypes`.`id`\n                          = `glpi_softwarelicenses`.`softwarelicensetypes_id`)\n                WHERE (`glpi_softwarelicenses`.`softwares_id` = '{$softwares_id}') " . getEntitiesRestrictRequest('AND', 'glpi_softwarelicenses', '', '', true) . "\n                ORDER BY {$sort} {$order}\n                LIMIT " . intval($start) . "," . intval($_SESSION['glpilist_limit']);
     if ($result = $DB->query($query)) {
         if ($num_displayed = $DB->numrows($result)) {
             // Display the pager
             Html::printAjaxPager(self::getTypeName(Session::getPluralNumber()), $start, $number);
             if ($showmassiveactions) {
                 Html::openMassiveActionsForm('mass' . __CLASS__ . $rand);
                 $massiveactionparams = array('num_displayed' => $num_displayed, 'container' => 'mass' . __CLASS__ . $rand, 'extraparams' => array('options' => array('glpi_softwareversions.name' => array('condition' => "`glpi_softwareversions`.`softwares_id`\n                                                                  = {$softwares_id}"), 'glpi_softwarelicenses.name' => array('itemlink_as_string' => true))));
                 Html::showMassiveActions($massiveactionparams);
             }
             $sort_img = "<img src=\"" . $CFG_GLPI["root_doc"] . "/pics/" . ($order == "DESC" ? "puce-down.png" : "puce-up.png") . "\" alt='' title=''>";
             $sort_img = "<img src=\"" . $CFG_GLPI["root_doc"] . "/pics/" . ($order == "DESC" ? "puce-down.png" : "puce-up.png") . "\" alt='' title=''>";
             echo "<table class='tab_cadre_fixehov'>";
             $header_begin = "<tr><th>";
             $header_top = Html::getCheckAllAsCheckbox('mass' . __CLASS__ . $rand);
             $header_bottom = Html::getCheckAllAsCheckbox('mass' . __CLASS__ . $rand);
             $header_end = '';
             foreach ($columns as $key => $val) {
                 // Non order column
                 if ($key[0] == '_') {
                     $header_end .= "<th>{$val}</th>";
                 } else {
                     $header_end .= "<th>" . ($sort == "`{$key}`" ? $sort_img : "") . "<a href='javascript:reloadTab(\"sort={$key}&amp;order=" . ($order == "ASC" ? "DESC" : "ASC") . "&amp;start=0\");'>{$val}</a></th>";
                 }
             }
             $header_end .= "</tr>\n";
             echo $header_begin . $header_top . $header_end;
             $tot_assoc = 0;
             for ($tot = 0; $data = $DB->fetch_assoc($result);) {
                 Session::addToNavigateListItems('SoftwareLicense', $data['id']);
                 $expired = true;
                 if (is_null($data['expire']) || $data['expire'] > date('Y-m-d')) {
                     $expired = false;
                 }
                 echo "<tr class='tab_bg_2" . ($expired ? '_2' : '') . "'>";
                 if ($license->canEdit($data['id'])) {
                     echo "<td>" . Html::getMassiveActionCheckBox(__CLASS__, $data["id"]) . "</td>";
                 } else {
                     echo "<td>&nbsp;</td>";
                 }
                 echo "<td><a href='softwarelicense.form.php?id=" . $data['id'] . "'>" . $data['name'] . (empty($data['name']) ? "(" . $data['id'] . ")" : "") . "</a></td>";
                 if (isset($columns['entity'])) {
                     echo "<td>";
                     echo $data['entity'];
                     echo "</td>";
                 }
                 echo "<td>" . $data['serial'] . "</td>";
                 echo "<td class='numeric'>" . ($data['number'] > 0 ? $data['number'] : __('Unlimited')) . "</td>";
                 $nb_assoc = Computer_SoftwareLicense::countForLicense($data['id']);
                 $tot_assoc += $nb_assoc;
                 $color = $data['is_valid'] ? 'green' : 'red';
                 echo "<td class='numeric {$color}'>" . $nb_assoc . "</td>";
                 echo "<td>" . $data['typename'] . "</td>";
                 echo "<td>" . $data['buyname'] . "</td>";
                 echo "<td>" . $data['usename'] . "</td>";
                 echo "<td class='center'>" . Html::convDate($data['expire']) . "</td>";
                 echo "</tr>";
                 if ($data['number'] < 0) {
                     // One illimited license, total is illimited
                     $tot = -1;
                 } else {
                     if ($tot >= 0) {
                         // Expire license not count
                         if (!$expired) {
                             // Not illimited, add the current number
                             $tot += $data['number'];
                         }
                     }
                 }
             }
             echo "<tr class='tab_bg_1 noHover'>";
             echo "<td colspan='" . ($software->isRecursive() ? 4 : 3) . "' class='right b'>" . __('Total') . "</td>";
             echo "<td class='numeric'>" . ($tot > 0 ? $tot . "" : __('Unlimited')) . "</td>";
             $color = $software->fields['is_valid'] ? 'green' : 'red';
             echo "<td class='numeric {$color}'>" . $tot_assoc . "</td><td></td><td></td><td></td><td></td>";
             echo "</tr>";
             echo "</table>\n";
             if ($showmassiveactions) {
                 $massiveactionparams['ontop'] = false;
                 Html::showMassiveActions($massiveactionparams);
                 Html::closeForm();
             }
             Html::printAjaxPager(self::getTypeName(Session::getPluralNumber()), $start, $number);
         } else {
             echo "<table class='tab_cadre_fixe'><tr><th>" . __('No item found') . "</th></tr></table>";
         }
     }
     echo "</div>";
 }
Ejemplo n.º 28
0
 /**
  * Show the availability of a user
  *
  * @since version 0.83
  *
  * @param $who    ID of the user
  * @param $begin  begin date to check (default '')
  * @param $end    end date to check (default '')
  *
  * @return Nothing (display function)
  **/
 static function checkAvailability($who, $begin = '', $end = '')
 {
     global $CFG_GLPI, $DB;
     if (empty($who)) {
         return false;
     }
     if (empty($begin)) {
         $begin = date("Y-m-d");
     }
     if (empty($end)) {
         $end = date("Y-m-d");
     }
     if ($end < $begin) {
         $end = $begin;
     }
     $realbegin = $begin . " " . $CFG_GLPI["planning_begin"];
     $realend = $end . " " . $CFG_GLPI["planning_end"];
     // Use get method to check availability
     echo "<div class='center'><form method='GET' name='form' action='planning.php'>\n";
     echo "<table class='tab_cadre'>";
     echo "<tr class='tab_bg_1'><th colspan='2'>" . __('Availability') . "</th>";
     echo "<th colspan='3'>" . getUserName($who) . "</th></tr>";
     echo "<tr class='tab_bg_1'>";
     echo "<td>" . __('Start') . "</td>\n";
     echo "<td>";
     Html::showDateFormItem("begin", $begin, false);
     echo "</td>\n";
     echo "<td>" . __('End') . "</td>\n";
     echo "<td>";
     Html::showDateFormItem("end", $end, false);
     echo "</td>\n";
     echo "<td rowspan='2' class='center'>";
     echo "<input type='hidden' name='users_id' value=\"{$who}\">";
     echo "<input type='submit' class='submit' name='checkavailability' value=\"" . _sx('button', 'Search') . "\">";
     echo "</td>\n";
     echo "</tr>";
     echo "</table>";
     Html::closeForm();
     echo "</div>\n";
     $params = array('who' => $who, 'who_group' => 0, 'begin' => $realbegin, 'end' => $realend);
     $interv = array();
     foreach ($CFG_GLPI['planning_types'] as $itemtype) {
         $interv = array_merge($interv, $itemtype::populatePlanning($params));
     }
     // Print Headers
     echo "<br><div class='center'><table class='tab_cadre_fixe'>";
     $colnumber = 1;
     $plan_begin = explode(":", $CFG_GLPI["planning_begin"]);
     $plan_end = explode(":", $CFG_GLPI["planning_end"]);
     $begin_hour = intval($plan_begin[0]);
     $end_hour = intval($plan_end[0]);
     if ($plan_end[1] != 0) {
         $end_hour++;
     }
     $colsize = floor((100 - 15) / ($end_hour - $begin_hour));
     // Print Headers
     echo "<tr class='tab_bg_1'><th width='15%'>&nbsp;</th>";
     for ($i = $begin_hour; $i < $end_hour; $i++) {
         $from = ($i < 10 ? '0' : '') . $i;
         //          $to   = ((($i+1) < 10)?'0':'').($i+1);
         echo "<th width='{$colsize}%' colspan='4'>" . $from . ":00</th>";
         $colnumber += 4;
     }
     echo "</tr>";
     $day_begin = strtotime($realbegin);
     $day_end = strtotime($realend);
     for ($time = $day_begin; $time < $day_end; $time += DAY_TIMESTAMP) {
         $current_day = date('Y-m-d', $time);
         echo "<tr><th>" . Html::convDate($current_day) . "</th>";
         $begin_quarter = $begin_hour * 4;
         $end_quarter = $end_hour * 4;
         for ($i = $begin_quarter; $i < $end_quarter; $i++) {
             $begin_time = date("Y-m-d H:i:s", strtotime($current_day) + $i * HOUR_TIMESTAMP / 4);
             $end_time = date("Y-m-d H:i:s", strtotime($current_day) + ($i + 1) * HOUR_TIMESTAMP / 4);
             // Init activity interval
             $begin_act = $end_time;
             $end_act = $begin_time;
             reset($interv);
             while ($data = current($interv)) {
                 if ($data["begin"] >= $begin_time && $data["end"] <= $end_time) {
                     // In
                     if ($begin_act > $data["begin"]) {
                         $begin_act = $data["begin"];
                     }
                     if ($end_act < $data["end"]) {
                         $end_act = $data["end"];
                     }
                     unset($interv[key($interv)]);
                 } else {
                     if ($data["begin"] < $begin_time && $data["end"] > $end_time) {
                         // Through
                         $begin_act = $begin_time;
                         $end_act = $end_time;
                         next($interv);
                     } else {
                         if ($data["begin"] >= $begin_time && $data["begin"] < $end_time) {
                             // Begin
                             if ($begin_act > $data["begin"]) {
                                 $begin_act = $data["begin"];
                             }
                             $end_act = $end_time;
                             next($interv);
                         } else {
                             if ($data["end"] > $begin_time && $data["end"] <= $end_time) {
                                 //End
                                 $begin_act = $begin_time;
                                 if ($end_act < $data["end"]) {
                                     $end_act = $data["end"];
                                 }
                                 unset($interv[key($interv)]);
                             } else {
                                 // Defautl case
                                 next($interv);
                             }
                         }
                     }
                 }
             }
             if ($begin_act < $end_act) {
                 if ($begin_act <= $begin_time && $end_act >= $end_time) {
                     // Activity in quarter
                     echo "<td class='notavailable'>&nbsp;</td>";
                 } else {
                     // Not all the quarter
                     if ($begin_act <= $begin_time) {
                         echo "<td class='partialavailableend'>&nbsp;</td>";
                     } else {
                         echo "<td class='partialavailablebegin'>&nbsp;</td>";
                     }
                 }
             } else {
                 // No activity
                 echo "<td class='available'>&nbsp;</td>";
             }
         }
         echo "</tr>";
     }
     echo "<tr class='tab_bg_1'><td colspan='{$colnumber}'>&nbsp;</td></tr>";
     echo "<tr class='tab_bg_1'>";
     echo "<th>" . __('Caption') . "</th>";
     echo "<td class='available' colspan=8>" . __('Available') . "</td>";
     echo "<td class='notavailable' colspan=8>" . __('Unavailable') . "</td>";
     echo "<td colspan='" . ($colnumber - 17) . "'>&nbsp;</td></tr>";
     echo "</table></div>";
 }
Ejemplo n.º 29
0
/**
 * Display all device for a group
 *
 * @param $type      the objet type
 * @param $result    the resultset of all the devices found
**/
function displayUserDevices($type, $result)
{
    global $DB, $CFG_GLPI;
    $item = new $type();
    while ($data = $DB->fetch_array($result)) {
        $link = $data["name"];
        $url = Toolbox::getItemTypeFormURL("{$type}");
        $link = "<a href='" . $url . "?id=" . $data["id"] . "'>" . $link . ($CFG_GLPI["is_ids_visible"] || empty($link) ? " (" . $data["id"] . ")" : "") . "</a>";
        $linktype = "";
        if (isset($groups[$data["groups_id"]])) {
            $linktype = sprintf(__('%1$s %2$s'), __('Group'), $groups[$data["groups_id"]]);
        }
        echo "<tr class='tab_bg_1'><td class='center'>" . $item->getTypeName() . "</td>" . "<td class='center'>{$link}</td>";
        echo "<td class='center'>";
        if (isset($data["serial"]) && !empty($data["serial"])) {
            echo $data["serial"];
        } else {
            echo '&nbsp;';
        }
        echo "</td><td class='center'>";
        if (isset($data["otherserial"]) && !empty($data["otherserial"])) {
            echo $data["otherserial"];
        } else {
            echo '&nbsp;';
        }
        echo "</td><td class='center'>";
        if (isset($data["immo_number"]) && !empty($data["immo_number"])) {
            echo $data["immo_number"];
        } else {
            echo '&nbsp;';
        }
        echo "</td><td class='center'>";
        if (isset($data["suppliers_id"]) && !empty($data["suppliers_id"])) {
            echo Dropdown::getDropdownName("glpi_suppliers", $data["suppliers_id"]);
        } else {
            echo '&nbsp;';
        }
        echo "</td><td class='center'>";
        if (isset($data["buy_date"]) && !empty($data["buy_date"])) {
            echo Html::convDate($data["buy_date"]);
        } else {
            echo '&nbsp;';
        }
        echo "</td></tr>";
    }
}
Ejemplo n.º 30
0
                    echo "<td> " . Html::convDate($data['buy_date']) . " </td>";
                    if ($data["warranty_duration"]) {
                        echo "<td> " . Infocom::getWarrantyExpir($data["buy_date"], $data["warranty_duration"]) . " </td>";
                    } else {
                        echo "<td> " . NOT_AVAILABLE . " </td>";
                    }
                } else {
                    echo "<td> " . NOT_AVAILABLE . " </td><td> " . NOT_AVAILABLE . " </td>";
                }
                if ($data['type']) {
                    echo "<td class='b'> " . $data['type'] . " </td>";
                } else {
                    echo "<td> " . NOT_AVAILABLE . " </td>";
                }
                if ($data['begin_date']) {
                    echo "<td> " . Html::convDate($data['begin_date']) . " </td>";
                    if ($data["duration"]) {
                        echo "<td> " . Infocom::getWarrantyExpir($data["begin_date"], $data["duration"]) . " </td>";
                    } else {
                        echo "<td> " . NOT_AVAILABLE . " </td>";
                    }
                } else {
                    echo "<td> " . NOT_AVAILABLE . " </td><td> " . NOT_AVAILABLE . " </td>";
                }
                echo "</tr>\n";
            }
            echo "</table><br><hr><br>";
        }
    }
}
Html::footer();