Exemple #1
0
 /**
  * @covers ::getSonsOf
  * @covers ::getAncestorsOf
  */
 public function testSonsAncestors()
 {
     $ent0 = getItemByTypeName('Entity', '_test_root_entity');
     $this->assertEquals('Root entity > _test_root_entity', $ent0->getField('completename'));
     $ent1 = getItemByTypeName('Entity', '_test_child_1');
     $this->assertEquals('Root entity > _test_root_entity > _test_child_1', $ent1->getField('completename'));
     $ent2 = getItemByTypeName('Entity', '_test_child_2');
     $this->assertEquals('Root entity > _test_root_entity > _test_child_2', $ent2->getField('completename'));
     $this->assertEquals([0], array_keys(getAncestorsOf('glpi_entities', $ent0->getID())));
     $this->assertEquals([0], array_values(getAncestorsOf('glpi_entities', $ent0->getID())));
     $this->assertEquals([$ent0->getID(), $ent1->getID(), $ent2->getID()], array_keys(getSonsOf('glpi_entities', $ent0->getID())));
     $this->assertEquals([$ent0->getID(), $ent1->getID(), $ent2->getID()], array_values(getSonsOf('glpi_entities', $ent0->getID())));
     $this->assertEquals([0, $ent0->getID()], array_keys(getAncestorsOf('glpi_entities', $ent1->getID())));
     $this->assertEquals([0, $ent0->getID()], array_values(getAncestorsOf('glpi_entities', $ent1->getID())));
     $this->assertEquals([$ent1->getID()], array_keys(getSonsOf('glpi_entities', $ent1->getID())));
     $this->assertEquals([$ent1->getID()], array_values(getSonsOf('glpi_entities', $ent1->getID())));
     $this->assertEquals([0, $ent0->getID()], array_keys(getAncestorsOf('glpi_entities', $ent2->getID())));
     $this->assertEquals([0, $ent0->getID()], array_values(getAncestorsOf('glpi_entities', $ent2->getID())));
     $this->assertEquals([$ent2->getID()], array_keys(getSonsOf('glpi_entities', $ent2->getID())));
     $this->assertEquals([$ent2->getID()], array_values(getSonsOf('glpi_entities', $ent2->getID())));
 }
 /**
  * Show the central personal view
  *
  *
  **/
 static function showMyView()
 {
     global $LANG, $DB;
     $showticket = haveRight("show_all_ticket", "1") || haveRight("show_assign_ticket", "1");
     echo "<table class='tab_cadre_central'>";
     if ($DB->isSlave() && !$DB->first_connection) {
         echo "<tr><th colspan='2'><br>";
         displayTitle(GLPI_ROOT . "/pics/warning.png", $LANG['setup'][809], $LANG['setup'][809]);
         echo "</th></tr>";
     }
     echo "<tr><td class='top'><table>";
     if (haveRight('validate_ticket', 1)) {
         echo "<tr><td class='top' width='450px'><br>";
         Ticket::showCentralList(0, "tovalidate", false);
         echo "</td></tr>";
     }
     echo "<tr><td class='top' width='450px'>";
     Ticket::showCentralList(0, "toapprove", false);
     echo "</td></tr>";
     echo "<tr><td class='top' width='450px'>";
     Ticket::showCentralList(0, "requestbyself", false);
     echo "</td></tr>";
     if ($showticket) {
         echo "<tr><td class='top' width='450px'>";
         Ticket::showCentralList(0, "process", false);
         echo "</td></tr>";
         echo "<tr><td class='top' width='450px'>";
         Ticket::showCentralList(0, "waiting", false);
         echo "</td></tr>";
     }
     echo "</table></td>";
     echo "<td class='top'><table><tr>";
     echo "<td class='top' width='450px'><br>";
     Planning::showCentral(getLoginUserID());
     echo "</td></tr>";
     echo "<tr><td class='top' width='450px'>";
     Reminder::showListForCentral();
     echo "</td></tr>";
     if (haveRight("reminder_public", "r")) {
         echo "<tr><td class='top' width='450px'>";
         Reminder::showListForCentral($_SESSION["glpiactive_entity"]);
         $entities = array_reverse(getAncestorsOf("glpi_entities", $_SESSION["glpiactive_entity"]));
         foreach ($entities as $entity) {
             Reminder::showListForCentral($entity, true);
         }
         foreach ($_SESSION["glpiactiveentities"] as $entity) {
             if ($entity != $_SESSION["glpiactive_entity"]) {
                 Reminder::showListForCentral($entity, false);
             }
         }
         echo "</td></tr>";
     }
     echo "</table></td></tr></table>";
 }
 /**
  * Copy (if needed) One software to the destination entity
  *
  * @param $ID of the software
  *
  * @return $ID of the new software (could be the same)
  **/
 function copySingleSoftware($ID)
 {
     global $DB;
     if (isset($this->already_transfer['Software'][$ID])) {
         return $this->already_transfer['Software'][$ID];
     }
     $soft = new Software();
     if ($soft->getFromDB($ID)) {
         if ($soft->fields['is_recursive'] && in_array($soft->fields['entities_id'], getAncestorsOf("glpi_entities", $this->to))) {
             // no need to copy
             $newsoftID = $ID;
         } else {
             $query = "SELECT *\n                      FROM `glpi_softwares`\n                      WHERE `entities_id` = " . $this->to . "\n                            AND `name` = '" . addslashes($soft->fields['name']) . "'";
             if ($data = $DB->request($query)->next()) {
                 $newsoftID = $data["id"];
             } else {
                 // create new item (don't check if move possible => clean needed)
                 unset($soft->fields['id']);
                 $input = $soft->fields;
                 $input['entities_id'] = $this->to;
                 unset($soft->fields);
                 $newsoftID = $soft->add($input);
             }
         }
         $this->addToAlreadyTransfer('Software', $ID, $newsoftID);
         return $newsoftID;
     }
     return -1;
 }
Exemple #4
0
   /**
    * sons / ancestors for CommonTreeDropdown
    */
   public function testTree() {

      $entity = $this->sharedFixture['entity'][0];
      $loc = new Location();

      // A
      $id[0] = $loc->add(array('entities_id'  => $entity,
                               'locations_id' => 0,
                               'name'         => 'A'));
      $this->assertGreaterThan(0, $id[0]);

      // A > AA
      $id[1] = $loc->add(array('entities_id'  => $entity,
                               'locations_id' => $id[0],
                               'name'         => 'AA'));
      $this->assertGreaterThan(0, $id[1]);
      $this->assertTrue($loc->getFromDB($id[1]));
      $this->assertEquals('A > AA', $loc->fields['completename']);

      // A > BB
      $id[2] = $loc->add(array('entities_id'  => $entity,
                               'locations_id' => $id[0],
                               'name'         => 'BB'));
      $this->assertGreaterThan(0, $id[2]);
      $this->assertTrue($loc->getFromDB($id[2]));
      $this->assertEquals('A > BB', $loc->fields['completename']);

      // Sons of A (A, AA, BB)
      $sons = getSonsOf('glpi_locations',$id[0]);
      $this->assertEquals(3, count($sons));
      $this->assertArrayHasKey($id[0], $sons);
      $this->assertArrayHasKey($id[1], $sons);
      $this->assertArrayHasKey($id[2], $sons);

      // Ancestors of A (none)
      $parent = getAncestorsOf('glpi_locations', $id[0]);
      $this->assertEquals(0, count($parent));

      // Ancestors of AA (A)
      $parent = getAncestorsOf('glpi_locations', $id[1]);
      $this->assertEquals(1, count($parent));
      $this->assertArrayHasKey($id[0], $parent);

      // Ancestors of BB (none)
      $parent = getAncestorsOf('glpi_locations', $id[2]);
      $this->assertEquals(1, count($parent));
      $this->assertArrayHasKey($id[0], $parent);

      // B
      $id[3] = $loc->add(array('entities_id'  => $entity,
                               'locations_id' => 0,
                               'name'         => 'B'));
      $this->assertGreaterThan(0, $id[3]);

      // B > CC
      $id[4] = $loc->add(array('entities_id'  => $entity,
                               'locations_id' => $id[3],
                               'name'         => 'CC'));
      $this->assertGreaterThan(0, $id[4]);
      $this->assertTrue($loc->getFromDB($id[4]));
      $this->assertEquals('B > CC', $loc->fields['completename']);

      $sons = getSonsOf('glpi_locations',$id[3]);
      $this->assertEquals(2, count($sons));
      $this->assertArrayHasKey($id[4], $sons);

      // B > CC > XXX
      $id[5] = $loc->add(array('entities_id'  => $entity,
                               'locations_id' => $id[4],
                               'name'         => 'XXX'));
      $this->assertGreaterThan(0, $id[5]);
      $this->assertTrue($loc->getFromDB($id[5]));
      $this->assertEquals('B > CC > XXX', $loc->fields['completename']);

      // B > CC => A > CC
      $res = $loc->update(array('id'           => $id[4],
                                'locations_id' => $id[0]));
      $this->assertTrue($res);
      $this->assertTrue($loc->getFromDB($id[4]));
      $this->assertEquals('A > CC', $loc->fields['completename']);

      // B > CC > XXX => A > CC > XXX
      $this->assertTrue($loc->getFromDB($id[5]));
      $this->assertEquals('A > CC > XXX', $loc->fields['completename']);

      // New parent of CC (A)
      $parent = getAncestorsOf('glpi_locations', $id[4]);
      $this->assertEquals(1, count($parent));
      $this->assertArrayHasKey($id[0], $parent);

      // New sons of B (only B)
      $sons = getSonsOf('glpi_locations',$id[3]);
      $this->assertEquals(1, count($sons));
      $this->assertArrayHasKey($id[3], $sons);

      // New sons of A (A, AA, BB, CC)
      $sons = getSonsOf('glpi_locations',$id[0]);
      $this->assertEquals(5, count($sons));
      $this->assertArrayHasKey($id[4], $sons);
      $this->assertArrayHasKey($id[5], $sons);

      // Rename A => C
      $res = $loc->update(array('id'   => $id[0],
                                'name' => 'C'));
      $this->assertTrue($res);

      // Check complete name of sons
      $this->assertTrue($loc->getFromDB($id[4]));
      $this->assertEquals('C > CC', $loc->fields['completename']);

      $this->assertTrue($loc->getFromDB($id[5]));
      $this->assertEquals('C > CC > XXX', $loc->fields['completename']);
      $this->assertEquals(3, $loc->fields['level']);

      // Delete CC and move child under B
      $res = $loc->delete(array('id' => $id[4],
                                '_replace_by' => $id[3]));
      $this->assertTrue($res);

      // Sons of B (B and XXX)
      $sons = getSonsOf('glpi_locations',$id[3]);
      $this->assertEquals(2, count($sons));
      $this->assertArrayHasKey($id[5], $sons);

      $this->assertTrue($loc->getFromDB($id[5]));
      $this->assertEquals('B > XXX', $loc->fields['completename']);
      $this->assertEquals(2, $loc->fields['level']);
   }
Exemple #5
0
 /**
  * Make a select box for Ticket my devices
  *
  * @param $userID          User ID for my device section (default 0)
  * @param $entity_restrict restrict to a specific entity (default -1)
  * @param $itemtype        of selected item (default 0)
  * @param $items_id        of selected item (default 0)
  *
  * @return nothing (print out an HTML select box)
  **/
 static function dropdownMyDevices($userID = 0, $entity_restrict = -1, $itemtype = 0, $items_id = 0)
 {
     global $DB, $CFG_GLPI;
     if ($userID == 0) {
         $userID = Session::getLoginUserID();
     }
     $rand = mt_rand();
     $already_add = array();
     if ($_SESSION["glpiactiveprofile"]["helpdesk_hardware"] & pow(2, self::HELPDESK_MY_HARDWARE)) {
         $my_devices = "";
         $my_item = $itemtype . '_' . $items_id;
         // My items
         foreach ($CFG_GLPI["linkuser_types"] as $itemtype) {
             if (($item = getItemForItemtype($itemtype)) && parent::isPossibleToAssignType($itemtype)) {
                 $itemtable = getTableForItemType($itemtype);
                 $query = "SELECT *\n                             FROM `{$itemtable}`\n                             WHERE `users_id` = '{$userID}'";
                 if ($item->maybeDeleted()) {
                     $query .= " AND `is_deleted` = '0' ";
                 }
                 if ($item->maybeTemplate()) {
                     $query .= " AND `is_template` = '0' ";
                 }
                 if (in_array($itemtype, $CFG_GLPI["helpdesk_visible_types"])) {
                     $query .= " AND `is_helpdesk_visible` = '1' ";
                 }
                 $query .= getEntitiesRestrictRequest("AND", $itemtable, "", $entity_restrict, $item->maybeRecursive()) . "\n                         ORDER BY `name` ";
                 $result = $DB->query($query);
                 $nb = $DB->numrows($result);
                 if ($DB->numrows($result) > 0) {
                     $type_name = $item->getTypeName($nb);
                     while ($data = $DB->fetch_assoc($result)) {
                         $output = $data["name"];
                         if (empty($output) || $_SESSION["glpiis_ids_visible"]) {
                             $output = sprintf(__('%1$s (%2$s)'), $output, $data['id']);
                         }
                         $output = sprintf(__('%1$s - %2$s'), $type_name, $output);
                         if ($itemtype != 'Software') {
                             if (!empty($data['serial'])) {
                                 $output = sprintf(__('%1$s - %2$s'), $output, $data['serial']);
                             }
                             if (!empty($data['otherserial'])) {
                                 $output = sprintf(__('%1$s - %2$s'), $output, $data['otherserial']);
                             }
                         }
                         $my_devices .= "<option title=\"{$output}\" value='" . $itemtype . "_" . $data["id"] . "' " . ($my_item == $itemtype . "_" . $data["id"] ? "selected" : "") . ">" . Toolbox::substr($output, 0, $_SESSION["glpidropdown_chars_limit"]) . "</option>";
                         $already_add[$itemtype][] = $data["id"];
                     }
                 }
             }
         }
         if (!empty($my_devices)) {
             $my_devices = "<optgroup label=\"" . __s('My devices') . "\">" . $my_devices . "</optgroup>";
         }
         // My group items
         if (Session::haveRight("show_group_hardware", "1")) {
             $group_where = "";
             $query = "SELECT `glpi_groups_users`.`groups_id`, `glpi_groups`.`name`\n                            FROM `glpi_groups_users`\n                            LEFT JOIN `glpi_groups`\n                              ON (`glpi_groups`.`id` = `glpi_groups_users`.`groups_id`)\n                            WHERE `glpi_groups_users`.`users_id` = '{$userID}' " . getEntitiesRestrictRequest("AND", "glpi_groups", "", $entity_restrict, true);
             $result = $DB->query($query);
             $first = true;
             if ($DB->numrows($result) > 0) {
                 while ($data = $DB->fetch_assoc($result)) {
                     if ($first) {
                         $first = false;
                     } else {
                         $group_where .= " OR ";
                     }
                     $a_groups = getAncestorsOf("glpi_groups", $data["groups_id"]);
                     $a_groups[$data["groups_id"]] = $data["groups_id"];
                     $group_where .= " `groups_id` IN (" . implode(',', $a_groups) . ") ";
                 }
                 $tmp_device = "";
                 foreach ($CFG_GLPI["linkgroup_types"] as $itemtype) {
                     if (($item = getItemForItemtype($itemtype)) && parent::isPossibleToAssignType($itemtype)) {
                         $itemtable = getTableForItemType($itemtype);
                         $query = "SELECT *\n                                    FROM `{$itemtable}`\n                                    WHERE ({$group_where}) " . getEntitiesRestrictRequest("AND", $itemtable, "", $entity_restrict, $item->maybeRecursive());
                         if ($item->maybeDeleted()) {
                             $query .= " AND `is_deleted` = '0' ";
                         }
                         if ($item->maybeTemplate()) {
                             $query .= " AND `is_template` = '0' ";
                         }
                         $result = $DB->query($query);
                         if ($DB->numrows($result) > 0) {
                             $type_name = $item->getTypeName();
                             if (!isset($already_add[$itemtype])) {
                                 $already_add[$itemtype] = array();
                             }
                             while ($data = $DB->fetch_assoc($result)) {
                                 if (!in_array($data["id"], $already_add[$itemtype])) {
                                     $output = '';
                                     if (isset($data["name"])) {
                                         $output = $data["name"];
                                     }
                                     if (empty($output) || $_SESSION["glpiis_ids_visible"]) {
                                         $output = sprintf(__('%1$s (%2$s)'), $output, $data['id']);
                                     }
                                     $output = sprintf(__('%1$s - %2$s'), $type_name, $output);
                                     if (isset($data['serial'])) {
                                         $output = sprintf(__('%1$s - %2$s'), $output, $data['serial']);
                                     }
                                     if (isset($data['otherserial'])) {
                                         $output = sprintf(__('%1$s - %2$s'), $output, $data['otherserial']);
                                     }
                                     $tmp_device .= "<option title=\"{$output}\" value='" . $itemtype . "_" . $data["id"] . "' " . ($my_item == $itemtype . "_" . $data["id"] ? "selected" : "") . ">" . Toolbox::substr($output, 0, $_SESSION["glpidropdown_chars_limit"]) . "</option>";
                                     $already_add[$itemtype][] = $data["id"];
                                 }
                             }
                         }
                     }
                 }
                 if (!empty($tmp_device)) {
                     $my_devices .= "<optgroup label=\"" . __s('Devices own by my groups') . "\">" . $tmp_device . "</optgroup>";
                 }
             }
         }
         // Get linked items to computers
         if (isset($already_add['Computer']) && count($already_add['Computer'])) {
             $search_computer = " XXXX IN (" . implode(',', $already_add['Computer']) . ') ';
             $tmp_device = "";
             // Direct Connection
             $types = array('Monitor', 'Peripheral', 'Phone', 'Printer');
             foreach ($types as $itemtype) {
                 if (in_array($itemtype, $_SESSION["glpiactiveprofile"]["helpdesk_item_type"]) && ($item = getItemForItemtype($itemtype))) {
                     $itemtable = getTableForItemType($itemtype);
                     if (!isset($already_add[$itemtype])) {
                         $already_add[$itemtype] = array();
                     }
                     $query = "SELECT DISTINCT `{$itemtable}`.*\n                            FROM `glpi_computers_items`\n                            LEFT JOIN `{$itemtable}`\n                                 ON (`glpi_computers_items`.`items_id` = `{$itemtable}`.`id`)\n                            WHERE `glpi_computers_items`.`itemtype` = '{$itemtype}'\n                                  AND  " . str_replace("XXXX", "`glpi_computers_items`.`computers_id`", $search_computer);
                     if ($item->maybeDeleted()) {
                         $query .= " AND `{$itemtable}`.`is_deleted` = '0' ";
                     }
                     if ($item->maybeTemplate()) {
                         $query .= " AND `{$itemtable}`.`is_template` = '0' ";
                     }
                     $query .= getEntitiesRestrictRequest("AND", $itemtable, "", $entity_restrict) . "\n                            ORDER BY `{$itemtable}`.`name`";
                     $result = $DB->query($query);
                     if ($DB->numrows($result) > 0) {
                         $type_name = $item->getTypeName();
                         while ($data = $DB->fetch_assoc($result)) {
                             if (!in_array($data["id"], $already_add[$itemtype])) {
                                 $output = $data["name"];
                                 if (empty($output) || $_SESSION["glpiis_ids_visible"]) {
                                     $output = sprintf(__('%1$s (%2$s)'), $output, $data['id']);
                                 }
                                 $output = sprintf(__('%1$s - %2$s'), $type_name, $output);
                                 if ($itemtype != 'Software') {
                                     $output = sprintf(__('%1$s - %2$s'), $output, $data['otherserial']);
                                 }
                                 $tmp_device .= "<option title=\"{$output}\" value='" . $itemtype . "_" . $data["id"] . "' " . ($my_item == $itemtype . "_" . $data["id"] ? "selected" : "") . ">" . Toolbox::substr($output, 0, $_SESSION["glpidropdown_chars_limit"]) . "</option>";
                                 $already_add[$itemtype][] = $data["id"];
                             }
                         }
                     }
                 }
             }
             if (!empty($tmp_device)) {
                 $my_devices .= "<optgroup label=\"" . __s('Connected devices') . "\">" . $tmp_device . "</optgroup>";
             }
             // Software
             if (in_array('Software', $_SESSION["glpiactiveprofile"]["helpdesk_item_type"])) {
                 $query = "SELECT DISTINCT `glpi_softwareversions`.`name` AS version,\n                                `glpi_softwares`.`name` AS name, `glpi_softwares`.`id`\n                         FROM `glpi_computers_softwareversions`, `glpi_softwares`,\n                              `glpi_softwareversions`\n                         WHERE `glpi_computers_softwareversions`.`softwareversions_id` =\n                                   `glpi_softwareversions`.`id`\n                               AND `glpi_softwareversions`.`softwares_id` = `glpi_softwares`.`id`\n                               AND " . str_replace("XXXX", "`glpi_computers_softwareversions`.`computers_id`", $search_computer) . "\n                               AND `glpi_softwares`.`is_helpdesk_visible` = '1' " . getEntitiesRestrictRequest("AND", "glpi_softwares", "", $entity_restrict) . "\n                         ORDER BY `glpi_softwares`.`name`";
                 $result = $DB->query($query);
                 if ($DB->numrows($result) > 0) {
                     $tmp_device = "";
                     $item = new Software();
                     $type_name = $item->getTypeName();
                     if (!isset($already_add['Software'])) {
                         $already_add['Software'] = array();
                     }
                     while ($data = $DB->fetch_assoc($result)) {
                         if (!in_array($data["id"], $already_add['Software'])) {
                             $output = sprintf(__('%1$s - %2$s'), $type_name, $data["name"]);
                             $output = sprintf(__('%1$s (%2$s)'), $output, sprintf(__('%1$s: %2$s'), __('version'), $data["version"]));
                             if ($_SESSION["glpiis_ids_visible"]) {
                                 $output = sprintf(__('%1$s (%2$s)'), $output, $data["id"]);
                             }
                             $tmp_device .= "<option title=\"{$output}\" value='Software_" . $data["id"] . "' " . ($my_item == 'Software' . "_" . $data["id"] ? "selected" : "") . ">" . Toolbox::substr($output, 0, $_SESSION["glpidropdown_chars_limit"]) . "</option>";
                             $already_add['Software'][] = $data["id"];
                         }
                     }
                     if (!empty($tmp_device)) {
                         $my_devices .= "<optgroup label=\"" . _sn('Installed software', 'Installed software', 2) . "\">";
                         $my_devices .= $tmp_device . "</optgroup>";
                     }
                 }
             }
         }
         echo "<div id='tracking_my_devices'>";
         echo "<select id='my_items' name='_my_items'>";
         echo "<option value=''>--- ";
         echo __('General') . " ---</option>{$my_devices}</select></div>";
         // Auto update summary of active or just solved tickets
         $params = array('my_items' => '__VALUE__');
         Ajax::updateItemOnSelectEvent("my_items", "item_ticket_selection_information", $CFG_GLPI["root_doc"] . "/ajax/ticketiteminformation.php", $params);
     }
 }
 /**
  * Replay dictionnary on one software
  *
  * @param &$new_softs      array containing new softwares already computed
  * @param $res_rule        array of rule results
  * @param $ID                    ID of the software
  * @param $entity                working entity ID
  * @param $name                  softwrae name
  * @param $manufacturer          manufacturer name
  * @param &$soft_ids       array containing replay software need to be dustbined
  **/
 function replayDictionnaryOnOneSoftware(array &$new_softs, array $res_rule, $ID, $entity, $name, $manufacturer, array &$soft_ids)
 {
     global $DB;
     $input["name"] = $name;
     $input["manufacturer"] = $manufacturer;
     $input["entities_id"] = $entity;
     if (empty($res_rule)) {
         $res_rule = $this->processAllRules($input, array(), array());
     }
     $soft = new Software();
     if (isset($res_rules['_ignore_import']) && $res_rules['_ignore_import'] == 1) {
         $soft->putInTrash($ID, __('Software deleted by GLPI dictionary rules'));
         return;
     }
     //Software's name has changed or entity
     if (isset($res_rule["name"]) && $res_rule["name"] != $name || !isset($res_rule["name"]) && isset($res_rule['new_entities_id']) && in_array($res_rule['new_entities_id'], getAncestorsOf('glpi_entities', $entity))) {
         if (isset($res_rule["name"])) {
             $new_name = $res_rule["name"];
         } else {
             $new_name = addslashes($name);
         }
         if (isset($res_rule["manufacturer"]) && $res_rule["manufacturer"]) {
             $manufacturer = $res_rule["manufacturer"];
         } else {
             $manufacturer = addslashes($manufacturer);
         }
         //New software not already present in this entity
         if (!isset($new_softs[$entity][$new_name])) {
             // create new software or restore it from dustbin
             $new_software_id = $soft->addOrRestoreFromTrash($new_name, $manufacturer, $entity, '', true);
             $new_softs[$entity][$new_name] = $new_software_id;
         } else {
             $new_software_id = $new_softs[$entity][$new_name];
         }
         // Move licenses to new software
         $this->moveLicenses($ID, $new_software_id);
     } else {
         $new_software_id = $ID;
         $res_rule["id"] = $ID;
         if (isset($res_rule["manufacturer"]) && $res_rule["manufacturer"]) {
             $res_rule["manufacturers_id"] = Dropdown::importExternal('Manufacturer', $res_rule["manufacturer"]);
             unset($res_rule["manufacturer"]);
         }
         $soft->update($res_rule);
     }
     // Add to software to deleted list
     if ($new_software_id != $ID) {
         $soft_ids[] = $ID;
     }
     //Get all the different versions for a software
     $result = $DB->query("SELECT *\n                            FROM `glpi_softwareversions`\n                            WHERE `softwares_id` = '{$ID}'");
     while ($version = $DB->fetch_assoc($result)) {
         $input["version"] = addslashes($version["name"]);
         $old_version_name = $input["version"];
         if (isset($res_rule["version"]) && $res_rule["version"] != '') {
             $new_version_name = $res_rule["version"];
         } else {
             $new_version_name = $version["name"];
         }
         if ($ID != $new_software_id || $new_version_name != $old_version_name) {
             $this->moveVersions($ID, $new_software_id, $version["id"], $old_version_name, $new_version_name, $entity);
         }
     }
 }
 /**
  * @since version 0.84
  *
  * @param $method
  * @param $methodNotItem
  * @param $check_entity            (true by default)
  * @param $forceCheckBoth boolean  force check both items (false by default)
  *
  * @return boolean
  **/
 function canRelationItem($method, $methodNotItem, $check_entity = true, $forceCheckBoth = false)
 {
     $OneWriteIsEnough = !$forceCheckBoth && (static::HAVE_SAME_RIGHT_ON_ITEM == static::$checkItem_1_Rights || static::HAVE_SAME_RIGHT_ON_ITEM == static::$checkItem_2_Rights);
     try {
         $item1 = NULL;
         $can1 = $this->canConnexityItem($method, $methodNotItem, static::$checkItem_1_Rights, static::$itemtype_1, static::$items_id_1, $item1);
         if ($OneWriteIsEnough) {
             $view1 = $this->canConnexityItem($method, $methodNotItem, static::HAVE_VIEW_RIGHT_ON_ITEM, static::$itemtype_1, static::$items_id_1, $item1);
         }
     } catch (CommonDBConnexityItemNotFound $e) {
         if (static::$mustBeAttached_1 && !static::isAttach1Valid($this->fields)) {
             return false;
         }
         $can1 = true;
         $view1 = true;
         $check_entity = false;
         // If no item, then, we cannot check entities
     }
     try {
         $item2 = NULL;
         $can2 = $this->canConnexityItem($method, $methodNotItem, static::$checkItem_2_Rights, static::$itemtype_2, static::$items_id_2, $item2);
         if ($OneWriteIsEnough) {
             $view2 = $this->canConnexityItem($method, $methodNotItem, static::HAVE_VIEW_RIGHT_ON_ITEM, static::$itemtype_2, static::$items_id_2, $item2);
         }
     } catch (CommonDBConnexityItemNotFound $e) {
         if (static::$mustBeAttached_2 && !static::isAttach2Valid($this->fields)) {
             return false;
         }
         $can2 = true;
         $view2 = true;
         $check_entity = false;
         // If no item, then, we cannot check entities
     }
     if ($OneWriteIsEnough) {
         if (!$can1 && !$can2 || $can1 && !$view2 || $can2 && !$view1) {
             return false;
         }
     } else {
         if (!$can1 || !$can2) {
             return false;
         }
     }
     // Check coherency of entities
     if ($check_entity && static::$check_entity_coherency) {
         // If one of both extremity is not valid => not allowed !
         // (default is only to check on create and update not for view and delete)
         if (!$item1 instanceof CommonDBTM || !$item2 instanceof CommonDBTM) {
             return false;
         }
         if ($item1->isEntityAssign() && $item2->isEntityAssign()) {
             $entity1 = $item1->getEntityID();
             $entity2 = $item2->getEntityID();
             if ($entity1 == $entity2) {
                 return true;
             }
             if ($item1->isRecursive() && in_array($entity1, getAncestorsOf("glpi_entities", $entity2))) {
                 return true;
             }
             if ($item2->isRecursive() && in_array($entity2, getAncestorsOf("glpi_entities", $entity1))) {
                 return true;
             }
             return false;
         }
     }
     return true;
 }
 /**
  * Print the Software / license form
  *
  * @param $ID        integer  Id of the version or the template to print
  * @param $options   array    of possible options:
  *     - target form target
  *     - softwares_id ID of the software for add process
  *
  * @return true if displayed  false if item not found or not right to display
  **/
 function showForm($ID, $options = array())
 {
     global $CFG_GLPI;
     $softwares_id = -1;
     if (isset($options['softwares_id'])) {
         $softwares_id = $options['softwares_id'];
     }
     if (!Session::haveRight("software", "w")) {
         return false;
     }
     if ($ID < 0) {
         // Create item
         $this->fields['softwares_id'] = $softwares_id;
         $this->fields['number'] = 1;
         $soft = new Software();
         if ($soft->getFromDB($softwares_id) && in_array($_SESSION['glpiactive_entity'], getAncestorsOf('glpi_entities', $soft->getEntityID()))) {
             $options['entities_id'] = $soft->getEntityID();
         }
     }
     $this->initForm($ID, $options);
     $this->showTabs($options);
     $this->showFormHeader($options);
     echo "<tr class='tab_bg_1'>";
     echo "<td>" . Software::getTypeName(1) . "</td>";
     echo "<td>";
     if ($ID > 0) {
         $softwares_id = $this->fields["softwares_id"];
     } else {
         echo "<input type='hidden' name='softwares_id' value='{$softwares_id}'>";
     }
     echo "<a href='software.form.php?id=" . $softwares_id . "'>" . Dropdown::getDropdownName("glpi_softwares", $softwares_id) . "</a>";
     echo "</td>";
     echo "<td>" . __('Type') . "</td>";
     echo "<td>";
     SoftwareLicenseType::dropdown(array('value' => $this->fields["softwarelicensetypes_id"]));
     echo "</td></tr>\n";
     echo "<tr class='tab_bg_1'>";
     echo "<td>" . __('Name') . "</td>";
     echo "<td>";
     Html::autocompletionTextField($this, "name");
     echo "</td>";
     echo "<td>" . __('Serial number') . "</td>";
     echo "<td>";
     Html::autocompletionTextField($this, "serial");
     echo "</td></tr>\n";
     echo "<tr class='tab_bg_1'>";
     echo "<td>" . __('Purchase version') . "</td>";
     echo "<td>";
     SoftwareVersion::dropdown(array('name' => "softwareversions_id_buy", 'softwares_id' => $this->fields["softwares_id"], 'value' => $this->fields["softwareversions_id_buy"]));
     echo "</td>";
     echo "<td>" . __('Inventory number') . "</td>";
     echo "<td>";
     Html::autocompletionTextField($this, "otherserial");
     echo "</td></tr>\n";
     echo "<tr class='tab_bg_1'>";
     echo "<td>" . __('Version in use') . "</td>";
     echo "<td>";
     SoftwareVersion::dropdown(array('name' => "softwareversions_id_use", 'softwares_id' => $this->fields["softwares_id"], 'value' => $this->fields["softwareversions_id_use"]));
     echo "</td>";
     echo "<td rowspan='" . ($ID > 0 ? '4' : '3') . "' class='middle'>" . __('Comments') . "</td>";
     echo "<td class='center middle' rowspan='" . ($ID > 0 ? '4' : '3') . "'>";
     echo "<textarea cols='45' rows='5' name='comment' >" . $this->fields["comment"] . "</textarea>";
     echo "</td></tr>\n";
     echo "<tr class='tab_bg_1'>";
     echo "<td>" . _x('quantity', 'Number') . "</td>";
     echo "<td>";
     Dropdown::showInteger("number", $this->fields["number"], 1, 1000, 1, array(-1 => __('Unlimited')));
     echo "</td></tr>\n";
     echo "<tr class='tab_bg_1'>";
     echo "<td>" . __('Expiration') . "</td>";
     echo "<td>";
     Html::showDateFormItem('expire', $this->fields["expire"]);
     Alert::displayLastAlert('SoftwareLicense', $ID);
     echo "</td></tr>\n";
     if ($ID > 0) {
         echo "<tr class='tab_bg_1'>";
         echo "<td>" . __('Last update') . "</td>";
         echo "<td>" . ($this->fields["date_mod"] ? Html::convDateTime($this->fields["date_mod"]) : __('Never'));
         echo "</td></tr>";
     }
     $this->showFormButtons($options);
     $this->addDivForTabs();
     return true;
 }
Exemple #9
0
 /**
  * Search networks relative to a given network
  *
  * @param $relation        type of relation ("is contained by", "equals" or "contains")
  *                         regarding the networks given as parameter
  * @param $condition array of elements to select the good arrays (see Parameters above)
  *    - fields : the fields of the network we wish to retrieve (single field or array of
  *               fields). This parameter will impact the result of the function
  *    - address (see \ref parameterType) : the address for the query
  *    - netmask (see \ref parameterType) : the netmask for the query
  *    - exclude IDs : the IDs to exclude from the query (for instance, $this->getID())
  *    - where : filters to add to the SQL request
  *
  * @param $entityID        the entity on which the selection should occur (-1 => the current active
  *                         entity) (default -1)
  * @param $recursive       set to false to only search in current entity, otherwise, all visible
  *                         entities will be search (true by default)
  * @param $version         version of IP to look (only use when using arrays or string as input for
  *                         address or netmask n(default 0)
  *
  * @return array of networks found. If we want request several field, the return value will be
  *                 an array of array
  *
  * \warning The order of the elements inside the result are ordered from the nearest one to the
  *          further. (ie. 0.0.0.0 is the further of whatever network if you lool for ones that
  *          contains the current network.
  **/
 static function searchNetworks($relation, $condition, $entityID = -1, $recursive = true, $version = 0)
 {
     global $DB;
     if (empty($relation)) {
         return false;
     }
     if (empty($condition["fields"])) {
         $fields = 'id';
     } else {
         $fields = $condition["fields"];
     }
     if (!is_array($fields)) {
         $fields = array($fields);
     }
     $FIELDS = "`" . implode("`, `", $fields) . "`";
     $startIndex = $version == 4 ? 3 : 1;
     $addressDB = array('address_0', 'address_1', 'address_2', 'address_3');
     $netmaskDB = array('netmask_0', 'netmask_1', 'netmask_2', 'netmask_3');
     $WHERE = "";
     if (isset($condition["address"]) && isset($condition["netmask"])) {
         $addressPa = new IPAddress($condition["address"]);
         // Check version equality ...
         if ($version != $addressPa->getVersion()) {
             if ($version != 0) {
                 return false;
             }
             $version = $addressPa->getVersion();
         }
         $netmaskPa = new IPNetmask($condition["netmask"], $version);
         // Get the array of the adresses
         $addressPa = $addressPa->getBinary();
         $netmaskPa = $netmaskPa->getBinary();
         // Check the binary is valid
         if (!is_array($addressPa) || count($addressPa) != 4) {
             return false;
         }
         if (!is_array($netmaskPa) || count($netmaskPa) != 4) {
             return false;
         }
         $startIndex = $version == 4 ? 3 : 0;
         if ($relation == "equals") {
             for ($i = $startIndex; $i < 4; ++$i) {
                 $WHERE .= " AND (`" . $addressDB[$i] . "` & '" . $netmaskPa[$i] . "')=\n                               ('" . $addressPa[$i] . "' & '" . $netmaskPa[$i] . "')\n                           AND ('" . $netmaskPa[$i] . "' = `" . $netmaskDB[$i] . "`)";
             }
         } else {
             for ($i = $startIndex; $i < 4; ++$i) {
                 if ($relation == "is contained by") {
                     $globalNetmask = "'" . $netmaskPa[$i] . "'";
                 } else {
                     $globalNetmask = "`" . $netmaskDB[$i] . "`";
                 }
                 $WHERE .= " AND (`" . $addressDB[$i] . "` & {$globalNetmask})=\n                               ('" . $addressPa[$i] . "' & {$globalNetmask})\n                           AND ('" . $netmaskPa[$i] . "' & `" . $netmaskDB[$i] . "`)={$globalNetmask}";
             }
         }
     }
     $WHERE = "`version`='{$version}' {$WHERE}";
     if ($entityID < 0) {
         $entityID = $_SESSION['glpiactive_entity'];
     }
     $entitiesID = array();
     switch ($relation) {
         case "is contained by":
             $ORDER_ORIENTATION = 'ASC';
             if ($recursive) {
                 $entitiesID = getSonsOf('glpi_entities', $entityID);
             }
             break;
         case "contains":
             $ORDER_ORIENTATION = 'DESC';
             if ($recursive) {
                 $entitiesID = getAncestorsOf('glpi_entities', $entityID);
             }
             break;
         case "equals":
             $ORDER_ORIENTATION = '';
             if ($recursive) {
                 $entitiesID = getSonsAndAncestorsOf('glpi_entities', $entityID);
             }
             break;
     }
     $entitiesID[] = $entityID;
     if (count($entitiesID) > 1) {
         // At least the current entity is defined
         $WHERE .= " AND `entities_id` IN ('" . implode("', '", $entitiesID) . "')";
     } else {
         $WHERE .= " AND `entities_id` = '" . $entitiesID[0] . "'";
     }
     if (!empty($condition["exclude IDs"])) {
         if (is_array($condition["exclude IDs"])) {
             if (count($condition["exclude IDs"]) > 1) {
                 $WHERE .= " AND `id` NOT IN ('" . implode("', '", $condition["exclude IDs"]) . "')";
             } else {
                 $WHERE .= " AND `id` <> '" . $condition["exclude IDs"][0] . "'";
             }
         } else {
             $WHERE .= " AND `id` <> '" . $condition["exclude IDs"] . "'";
         }
     }
     $ORDER = array();
     for ($i = $startIndex; $i < 4; ++$i) {
         $ORDER[] = "BIT_COUNT(`" . $netmaskDB[$i] . "`) {$ORDER_ORIENTATION}";
     }
     if (!empty($condition["where"])) {
         $WHERE .= " AND " . $condition["where"];
     }
     $query = "SELECT {$FIELDS}\n                FROM `glpi_ipnetworks`\n                WHERE {$WHERE}\n                ORDER BY " . implode(', ', $ORDER);
     // By ordering on the netmask, we ensure that the first element is the nearest one (ie:
     // the last should be 0.0.0.0/0.0.0.0 of x.y.z.a/255.255.255.255 regarding the interested
     // element)
     $returnValues = array();
     if ($result = $DB->query($query)) {
         while ($data = $DB->fetch_assoc($result)) {
             if (count($fields) > 1) {
                 $returnValue = array();
                 foreach ($fields as $field) {
                     $returnValue[$field] = $data[$field];
                 }
             } else {
                 $returnValue = $data[$fields[0]];
             }
             $returnValues[] = $returnValue;
         }
     }
     return $returnValues;
 }
 if (isset($searchopt[$_POST["id_field"]])) {
     /// Infocoms case
     if (!isPluginItemType($_POST["itemtype"]) && Search::isInfocomOption($_POST["itemtype"], $_POST["id_field"])) {
         $ic = new Infocom();
         $link_entity_type = -1;
         /// Specific entity item
         if ($searchopt[$_POST["id_field"]]["table"] == "glpi_suppliers") {
             $ent = new Supplier();
             if ($ent->getFromDB($_POST[$_POST["field"]])) {
                 $link_entity_type = $ent->fields["entities_id"];
             }
         }
         foreach ($_POST["item"] as $key => $val) {
             if ($val == 1) {
                 if ($item->getFromDB($key)) {
                     if ($link_entity_type < 0 || $link_entity_type == $item->getEntityID() || $ent->fields["is_recursive"] && in_array($link_entity_type, getAncestorsOf("glpi_entities", $item->getEntityID()))) {
                         // Add infocom if not exists
                         if (!$ic->getFromDBforDevice($_POST["itemtype"], $key)) {
                             $input2["items_id"] = $key;
                             $input2["itemtype"] = $_POST["itemtype"];
                             unset($ic->fields);
                             $ic->add($input2);
                             $ic->getFromDBforDevice($_POST["itemtype"], $key);
                         }
                         $id = $ic->fields["id"];
                         unset($ic->fields);
                         $ic->update(array('id' => $id, $_POST["field"] => $_POST[$_POST["field"]]));
                     }
                 }
             }
         }
 function post_updateItem($history = 1)
 {
     $ID = $this->getID();
     $changeParent = in_array($this->getForeignKeyField(), $this->updates);
     $this->regenerateTreeUnderID($ID, in_array('name', $this->updates), $changeParent);
     $this->recursiveCleanSonsAboveID($ID);
     if ($changeParent) {
         $oldParentID = $this->oldvalues[$this->getForeignKeyField()];
         $newParentID = $this->fields[$this->getForeignKeyField()];
         $oldParentNameID = '';
         $newParentNameID = '';
         $parent = clone $this;
         if ($oldParentID > 0) {
             $this->recursiveCleanSonsAboveID($oldParentID);
             if ($history) {
                 if ($parent->getFromDB($oldParentID)) {
                     $oldParentNameID = $parent->getNameID();
                 }
                 $changes[0] = '0';
                 $changes[1] = addslashes($this->getNameID());
                 $changes[2] = '';
                 Log::history($oldParentID, $this->getType(), $changes, $this->getType(), Log::HISTORY_DELETE_SUBITEM);
             }
         }
         if ($newParentID > 0) {
             if ($history) {
                 if ($parent->getFromDB($newParentID)) {
                     $newParentNameID = $parent->getNameID();
                 }
                 $changes[0] = '0';
                 $changes[1] = '';
                 $changes[2] = addslashes($this->getNameID());
                 Log::history($newParentID, $this->getType(), $changes, $this->getType(), Log::HISTORY_ADD_SUBITEM);
             }
         }
         if ($history) {
             $changes[0] = '0';
             $changes[1] = $oldParentNameID;
             $changes[2] = $newParentNameID;
             Log::history($ID, $this->getType(), $changes, $this->getType(), Log::HISTORY_UPDATE_SUBITEM);
         }
         getAncestorsOf(getTableForItemType($this->getType()), $ID);
     }
 }
 /**
  * Can I change recusvive flag to false
  * check if there is "linked" object in another entity
  *
  * May be overloaded if needed
  *
  * @return booleen
  **/
 function canUnrecurs()
 {
     global $DB, $CFG_GLPI;
     $ID = $this->fields['id'];
     if ($ID < 0 || !$this->fields['is_recursive']) {
         return true;
     }
     $entities = "('" . $this->fields['entities_id'] . "'";
     foreach (getAncestorsOf("glpi_entities", $this->fields['entities_id']) as $papa) {
         $entities .= ",'{$papa}'";
     }
     $entities .= ")";
     $RELATION = getDbRelations();
     if ($this instanceof CommonTreeDropdown) {
         $f = getForeignKeyFieldForTable($this->getTable());
         if (countElementsInTable($this->getTable(), "`{$f}`='{$ID}' AND entities_id NOT IN {$entities}") > 0) {
             return false;
         }
     }
     if (isset($RELATION[$this->getTable()])) {
         foreach ($RELATION[$this->getTable()] as $tablename => $field) {
             $itemtype = getItemTypeForTable($tablename);
             $item = new $itemtype();
             if ($item->isEntityAssign()) {
                 // 1->N Relation
                 if (is_array($field)) {
                     foreach ($field as $f) {
                         if (countElementsInTable($tablename, "`{$f}`='{$ID}' AND entities_id NOT IN {$entities}") > 0) {
                             return false;
                         }
                     }
                 } else {
                     if (countElementsInTable($tablename, "`{$field}`='{$ID}' AND entities_id NOT IN {$entities}") > 0) {
                         return false;
                     }
                 }
             } else {
                 foreach ($RELATION as $othertable => $rel) {
                     // Search for a N->N Relation with devices
                     if ($othertable == "_virtual_device" && isset($rel[$tablename])) {
                         $devfield = $rel[$tablename][0];
                         // items_id...
                         $typefield = $rel[$tablename][1];
                         // itemtype...
                         $sql = "SELECT DISTINCT `{$typefield}` AS itemtype\n                             FROM `{$tablename}`\n                             WHERE `{$field}`='{$ID}'";
                         $res = $DB->query($sql);
                         // Search linked device of each type
                         if ($res) {
                             while ($data = $DB->fetch_assoc($res)) {
                                 $itemtype = $data["itemtype"];
                                 $itemtable = getTableForItemType($itemtype);
                                 $item = new $itemtype();
                                 if ($item->isEntityAssign()) {
                                     if (countElementsInTable(array($tablename, $itemtable), "`{$tablename}`.`{$field}`='{$ID}'\n                                                        AND `{$tablename}`.`{$typefield}`='{$itemtype}'\n                                                        AND `{$tablename}`.`{$devfield}`=`{$itemtable}`.id\n                                                        AND `{$itemtable}`.`entities_id`\n                                                             NOT IN {$entities}") > '0') {
                                         return false;
                                     }
                                 }
                             }
                         }
                         // Search for another N->N Relation
                     } else {
                         if ($othertable != $this->getTable() && isset($rel[$tablename])) {
                             $itemtype = getItemTypeForTable($othertable);
                             $item = new $itemtype();
                             if ($item->isEntityAssign()) {
                                 if (is_array($rel[$tablename])) {
                                     foreach ($rel[$tablename] as $otherfield) {
                                         if (countElementsInTable(array($tablename, $othertable), "`{$tablename}`.`{$field}`='{$ID}'\n                                                        AND `{$tablename}`.`{$otherfield}`\n                                                                  =`{$othertable}`.id\n                                                        AND `{$othertable}`.`entities_id`\n                                                                  NOT IN {$entities}") > '0') {
                                             return false;
                                         }
                                     }
                                 } else {
                                     $otherfield = $rel[$tablename];
                                     if (countElementsInTable(array($tablename, $othertable), "`{$tablename}`.`{$field}`={$ID}\n                                                     AND `{$tablename}`.`{$otherfield}`=`{$othertable}`.id\n                                                     AND `{$othertable}`.`entities_id`\n                                                               NOT IN {$entities}") > '0') {
                                         return false;
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     // Doc links to this item
     if ($this->getType() > 0 && countElementsInTable(array('glpi_documents_items', 'glpi_documents'), "`glpi_documents_items`.`items_id`='{$ID}'\n                                   AND `glpi_documents_items`.`itemtype`=" . $this->getType() . "\n                                   AND `glpi_documents_items`.`documents_id`=`glpi_documents`.`id`\n                                   AND `glpi_documents`.`entities_id` NOT IN {$entities}") > '0') {
         return false;
     }
     // TODO : do we need to check all relations in $RELATION["_virtual_device"] for this item
     return true;
 }
Exemple #13
0
 /**
  * Check if you could access (read) to the entity of id = $ID
  *
  * @param $ID                    ID of the entity
  * @param $is_recursive boolean  if recursive item (default 0)
  *
  * @return Boolean : read access to entity
  **/
 static function haveAccessToEntity($ID, $is_recursive = 0)
 {
     // Quick response when passing wrong ID : default value of getEntityID is -1
     if ($ID < 0) {
         return false;
     }
     if (!isset($_SESSION['glpiactiveentities'])) {
         return false;
     }
     if (!$is_recursive) {
         return in_array($ID, $_SESSION['glpiactiveentities']);
     }
     if (in_array($ID, $_SESSION['glpiactiveentities'])) {
         return true;
     }
     /// Recursive object
     foreach ($_SESSION['glpiactiveentities'] as $ent) {
         if (in_array($ID, getAncestorsOf("glpi_entities", $ent))) {
             return true;
         }
     }
     return false;
 }
 /**
  * Show KB categories
  *
  * @param $options   $_GET
  *
  * @return nothing (display the form)
  **/
 static function showFirstLevel($options)
 {
     global $DB, $CFG_GLPI;
     $faq = !Session::haveRight("knowbase", "r");
     // Default values of parameters
     $params["knowbaseitemcategories_id"] = "0";
     $params["target"] = $_SERVER['PHP_SELF'];
     if (is_array($options) && count($options)) {
         foreach ($options as $key => $val) {
             $params[$key] = $val;
         }
     }
     $faq_limit = '';
     $parameters = '';
     // Manage search solution
     if (isset($options['item_itemtype']) && isset($options['item_items_id'])) {
         $parameters = "&amp;item_items_id=" . $options['item_items_id'] . "&amp;item_itemtype=" . $options['item_itemtype'];
     }
     if ($faq) {
         if (!$CFG_GLPI["use_public_faq"] && !Session::haveRight("faq", "r")) {
             return false;
         }
         if (Session::getLoginUserID()) {
             $faq_limit = getEntitiesRestrictRequest("AND", "glpi_knowbaseitemcategories", "", "", true);
         } else {
             // Anonymous access
             if (Session::isMultiEntitiesMode()) {
                 $faq_limit = " AND (`glpi_knowbaseitemcategories`.`entities_id` = '0'\n                                   AND `glpi_knowbaseitemcategories`.`is_recursive` = '1')";
             }
         }
         // Get All FAQ categories
         if (!isset($_SESSION['glpi_faqcategories'])) {
             $_SESSION['glpi_faqcategories'] = '(0)';
             $tmp = array();
             $query = "SELECT DISTINCT `glpi_knowbaseitems`.`knowbaseitemcategories_id`\n                      FROM `glpi_knowbaseitems`\n                      " . KnowbaseItem::addVisibilityJoins() . "\n                      LEFT JOIN `glpi_knowbaseitemcategories`\n                           ON (`glpi_knowbaseitemcategories`.`id`\n                                 = `glpi_knowbaseitems`.`knowbaseitemcategories_id`)\n                      WHERE `glpi_knowbaseitems`.`is_faq` = '1'\n                            AND " . KnowbaseItem::addVisibilityRestrict() . "\n                            {$faq_limit}";
             if ($result = $DB->query($query)) {
                 if ($DB->numrows($result)) {
                     while ($data = $DB->fetch_assoc($result)) {
                         if (!in_array($data['knowbaseitemcategories_id'], $tmp)) {
                             $tmp[] = $data['knowbaseitemcategories_id'];
                             $tmp = array_merge($tmp, getAncestorsOf('glpi_knowbaseitemcategories', $data['knowbaseitemcategories_id']));
                         }
                     }
                 }
                 if (count($tmp)) {
                     $_SESSION['glpi_faqcategories'] = "('" . implode("','", $tmp) . "')";
                 }
             }
         }
         $query = "SELECT DISTINCT `glpi_knowbaseitemcategories`.*\n                   FROM `glpi_knowbaseitemcategories`\n                   WHERE `glpi_knowbaseitemcategories`.`id` IN " . $_SESSION['glpi_faqcategories'] . "\n                         AND (`glpi_knowbaseitemcategories`.`knowbaseitemcategories_id`\n                                 = '" . $params["knowbaseitemcategories_id"] . "')\n                         {$faq_limit}\n                   ORDER BY `name` ASC";
     } else {
         if (!Session::haveRight("knowbase", "r")) {
             return false;
         }
         $faq_limit = getEntitiesRestrictRequest("AND", "glpi_knowbaseitemcategories", "entities_id", $_SESSION['glpiactiveentities'], true);
         $query = "SELECT *\n                   FROM `glpi_knowbaseitemcategories`\n                   WHERE `glpi_knowbaseitemcategories`.`knowbaseitemcategories_id`\n                              = '" . $params["knowbaseitemcategories_id"] . "'\n                         {$faq_limit}\n                   ORDER BY `name` ASC";
     }
     // Show category
     if ($result = $DB->query($query)) {
         echo "<table class='tab_cadre_central'>";
         echo "<tr><td colspan='3'><a href='" . $params['target'] . "?knowbaseitemcategories_id=0{$parameters}'>";
         echo "<img alt='' src='" . $CFG_GLPI["root_doc"] . "/pics/folder-open.png' class='bottom'></a>";
         // Display Category
         if ($params["knowbaseitemcategories_id"] != 0) {
             $tmpID = $params["knowbaseitemcategories_id"];
             $todisplay = "";
             while ($tmpID != 0) {
                 $query2 = "SELECT *\n                          FROM `glpi_knowbaseitemcategories`\n                          WHERE `glpi_knowbaseitemcategories`.`id` = '{$tmpID}'\n                                {$faq_limit}";
                 $result2 = $DB->query($query2);
                 if ($DB->numrows($result2) == 1) {
                     $data = $DB->fetch_assoc($result2);
                     $tmpID = $data["knowbaseitemcategories_id"];
                     $todisplay = "<a href='" . $params['target'] . "?knowbaseitemcategories_id=" . $data["id"] . "{$parameters}'>" . $data["name"] . "</a>" . (empty($todisplay) ? "" : " > ") . $todisplay;
                 } else {
                     $tmpID = 0;
                 }
             }
             echo " > " . $todisplay;
         }
         if ($DB->numrows($result) > 0) {
             $i = 0;
             while ($row = $DB->fetch_assoc($result)) {
                 // on affiche les résultats sur trois colonnes
                 if ($i % 3 == 0) {
                     echo "<tr>";
                 }
                 $ID = $row["id"];
                 echo "<td class='tdkb_result'>";
                 echo "<img alt='' src='" . $CFG_GLPI["root_doc"] . "/pics/folder.png' hspace='5'>";
                 echo "<span class='b'>" . "<a href='" . $params['target'] . "?knowbaseitemcategories_id=" . $row["id"] . "{$parameters}'>" . $row["name"] . "</a></span>";
                 echo "<div class='kb_resume'>" . Html::resume_text($row['comment'], 60) . "</div>";
                 if ($i % 3 == 2) {
                     echo "</tr>";
                 }
                 $i++;
             }
         }
         echo "<tr><td colspan='3'>&nbsp;</td></tr></table><br>";
     }
 }
GLPI is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with GLPI. If not, see <http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------
*/
/** @file
* @brief
* @since version 0.85
*/
$AJAX_INCLUDE = 1;
include "../inc/includes.php";
header("Content-Type: text/html; charset=UTF-8");
Html::header_nocache();
Session::checkLoginUser();
$res = array();
if (isset($_POST['search_string'])) {
    $query = "SELECT *\n             FROM `glpi_entities`\n             WHERE `name` LIKE '%" . $_POST['search_string'] . "%'\n             ORDER BY `completename`";
    foreach ($DB->request($query) as $data) {
        $ancestors = getAncestorsOf('glpi_entities', $data['id']);
        foreach ($ancestors as $val) {
            $res[] = '#ent' . $val;
        }
    }
}
$res = json_encode($res);
echo $res;
Exemple #16
0
* @brief
*/
$AJAX_INCLUDE = 1;
include "../inc/includes.php";
header("Content-Type: text/html; charset=UTF-8");
Html::header_nocache();
Session::checkLoginUser();
if (isset($_GET['node'])) {
    if ($_SESSION['glpiactiveprofile']['interface'] == 'helpdesk') {
        $target = "helpdesk.public.php";
    } else {
        $target = "central.php";
    }
    $nodes = array();
    // Get ancestors of current entity
    $ancestors = getAncestorsOf('glpi_entities', $_SESSION['glpiactive_entity']);
    // Root node
    if ($_GET['node'] == -1) {
        $pos = 0;
        foreach ($_SESSION['glpiactiveprofile']['entities'] as $entity) {
            $path = array();
            $ID = $entity['id'];
            $is_recursive = $entity['is_recursive'];
            $path['data']['title'] = Dropdown::getDropdownName("glpi_entities", $ID);
            $path['attr']['id'] = 'ent' . $ID;
            $path['data']['attr']['href'] = $CFG_GLPI["root_doc"] . "/front/{$target}?active_entity=" . $ID;
            if ($is_recursive) {
                $query2 = "SELECT count(*)\n                       FROM `glpi_entities`\n                       WHERE `entities_id` = '{$ID}'";
                $result2 = $DB->query($query2);
                if ($DB->result($result2, 0, 0) > 0) {
                    $path['data']['title'] .= "&nbsp;<a title=\"" . __s('Show all') . "\" href='" . $CFG_GLPI["root_doc"] . "/front/" . $target . "?active_entity=" . $ID . "&amp;is_recursive=1'>" . "<img alt=\"" . __s('Show all') . "\" src='" . $CFG_GLPI["root_doc"] . "/pics/entity_all.png'></a>";
Exemple #17
0
 /**
  * Can I change recusvive flag to false
  * check if there is "linked" object in another entity
  *
  * Overloaded from CommonDBTM
  *
  * @return booleen
  **/
 function canUnrecurs()
 {
     global $DB, $CFG_GLPI;
     $ID = $this->fields['id'];
     if ($ID < 0 || !$this->fields['is_recursive']) {
         return true;
     }
     if (!parent::canUnrecurs()) {
         return false;
     }
     $entities = "(" . $this->fields['entities_id'];
     foreach (getAncestorsOf("glpi_entities", $this->fields['entities_id']) as $papa) {
         $entities .= ",{$papa}";
     }
     $entities .= ")";
     // RELATION : printers -> _port -> _wire -> _port -> device
     // Evaluate connection in the 2 ways
     for ($tabend = array("networkports_id_1" => "networkports_id_2", "networkports_id_2" => "networkports_id_1"); list($enda, $endb) = each($tabend);) {
         $sql = "SELECT `itemtype`,\n                        GROUP_CONCAT(DISTINCT `items_id`) AS ids\n                 FROM `glpi_networkports_networkports`,\n                      `glpi_networkports`\n                 WHERE `glpi_networkports_networkports`.`{$endb}` = `glpi_networkports`.`id`\n                       AND `glpi_networkports_networkports`.`{$enda}`\n                            IN (SELECT `id`\n                                FROM `glpi_networkports`\n                                WHERE `itemtype` = '" . $this->getType() . "'\n                                      AND `items_id` = '{$ID}')\n                 GROUP BY `itemtype`";
         $res = $DB->query($sql);
         if ($res) {
             while ($data = $DB->fetch_assoc($res)) {
                 $itemtable = getTableForItemType($data["itemtype"]);
                 if ($item = getItemForItemtype($data["itemtype"])) {
                     // For each itemtype which are entity dependant
                     if ($item->isEntityAssign()) {
                         if (countElementsInTable($itemtable, "`id` IN (" . $data["ids"] . ")\n                                              AND `entities_id` NOT IN {$entities}") > 0) {
                             return false;
                         }
                     }
                 }
             }
         }
     }
     return true;
 }
Exemple #18
0
 function transfer($new_entity)
 {
     global $DB;
     if ($this->fields['id'] > 0 && $this->fields['entities_id'] != $new_entity) {
         //Update entity for this object
         $tmp['id'] = $this->fields['id'];
         $tmp['entities_id'] = $new_entity;
         $this->update($tmp);
         $toupdate = array('id' => $this->fields['id']);
         foreach (PluginGenericobjectSingletonObjectField::getInstance(get_called_class()) as $field => $data) {
             $table = getTableNameForForeignKeyField($field);
             //It is a dropdown table !
             if ($field != 'entities_id' && $table != '' && isset($this->fields[$field]) && $this->fields[$field] > 0) {
                 //Instanciate a new dropdown object
                 $dropdown_itemtype = getItemTypeForTable($table);
                 $dropdown = new $dropdown_itemtype();
                 $dropdown->getFromDB($this->fields[$field]);
                 //If dropdown is only accessible in the other entity
                 //do not go further
                 if (!$dropdown->isEntityAssign() || in_array($new_entity, getAncestorsOf('glpi_entities', $dropdown->getEntityID()))) {
                     continue;
                 } else {
                     $tmp = array();
                     $where = "";
                     if ($dropdown instanceof CommonTreeDropdown) {
                         $tmp['completename'] = $dropdown->fields['completename'];
                         $where = "`completename`='" . addslashes_deep($tmp['completename']) . "'";
                     } else {
                         $tmp['name'] = $dropdown->fields['name'];
                         $where = "`name`='" . addslashes_deep($tmp['name']) . "'";
                     }
                     $tmp['entities_id'] = $new_entity;
                     $where .= " AND `entities_id`='" . $tmp['entities_id'] . "'";
                     //There's a dropdown value in the target entity
                     if ($found = $this->find($where)) {
                         $myfound = array_pop($found);
                         if ($myfound['id'] != $this->fields[$field]) {
                             $toupdate[$field] = $myfound['id'];
                         }
                     } else {
                         $clone = $dropdown->fields;
                         if ($dropdown instanceof CommonTreeDropdown) {
                             unset($clone['completename']);
                         }
                         unset($clone['id']);
                         $clone['entities_id'] = $new_entity;
                         $new_id = $dropdown->import($clone);
                         $toupdate[$field] = $new_id;
                     }
                 }
             }
         }
         $this->update($toupdate);
     }
     return true;
 }
Exemple #19
0
 /**
  * @since version 0.84 (before in entitydata.class)
  *
  * @param $entity Entity object
  **/
 static function showInventoryOptions(Entity $entity)
 {
     $ID = $entity->getField('id');
     if (!$entity->can($ID, READ)) {
         return false;
     }
     // Notification right applied
     $canedit = Infocom::canUpdate() && Session::haveAccessToEntity($ID);
     echo "<div class='spaced'>";
     if ($canedit) {
         echo "<form method='post' name=form action='" . Toolbox::getItemTypeFormURL(__CLASS__) . "'>";
     }
     echo "<table class='tab_cadre_fixe'>";
     echo "<tr><th colspan='4'>" . __('Autofill dates for financial and administrative information') . "</th></tr>";
     $options[0] = __('No autofill');
     if ($ID > 0) {
         $options[self::CONFIG_PARENT] = __('Inheritance of the parent entity');
     }
     foreach (getAllDatasFromTable('glpi_states') as $state) {
         $options[Infocom::ON_STATUS_CHANGE . '_' . $state['id']] = sprintf(__('Fill when shifting to state %s'), $state['name']);
     }
     $options[Infocom::COPY_WARRANTY_DATE] = __('Copy the start date of warranty');
     //Buy date
     echo "<tr class='tab_bg_2'>";
     echo "<td> " . __('Date of purchase') . "</td>";
     echo "<td>";
     Dropdown::showFromArray('autofill_buy_date', $options, array('value' => $entity->getField('autofill_buy_date')));
     echo "</td>";
     //Order date
     echo "<td> " . __('Order date') . "</td>";
     echo "<td>";
     $options[Infocom::COPY_BUY_DATE] = __('Copy the date of purchase');
     Dropdown::showFromArray('autofill_order_date', $options, array('value' => $entity->getField('autofill_order_date')));
     echo "</td></tr>";
     //Delivery date
     echo "<tr class='tab_bg_2'>";
     echo "<td> " . __('Delivery date') . "</td>";
     echo "<td>";
     $options[Infocom::COPY_ORDER_DATE] = __('Copy the order date');
     Dropdown::showFromArray('autofill_delivery_date', $options, array('value' => $entity->getField('autofill_delivery_date')));
     echo "</td>";
     //Use date
     echo "<td> " . __('Startup date') . " </td>";
     echo "<td>";
     $options[Infocom::COPY_DELIVERY_DATE] = __('Copy the delivery date');
     Dropdown::showFromArray('autofill_use_date', $options, array('value' => $entity->getField('autofill_use_date')));
     echo "</td></tr>";
     //Warranty date
     echo "<tr class='tab_bg_2'>";
     echo "<td> " . __('Start date of warranty') . "</td>";
     echo "<td>";
     $options = array(0 => __('No autofill'), Infocom::COPY_BUY_DATE => __('Copy the date of purchase'), Infocom::COPY_ORDER_DATE => __('Copy the order date'), Infocom::COPY_DELIVERY_DATE => __('Copy the delivery date'));
     if ($ID > 0) {
         $options[self::CONFIG_PARENT] = __('Inheritance of the parent entity');
     }
     Dropdown::showFromArray('autofill_warranty_date', $options, array('value' => $entity->getField('autofill_warranty_date')));
     echo "</td><td colspan='2'></td></tr>";
     echo "<tr><th colspan='4'>" . _n('Software', 'Software', Session::getPluralNumber()) . "</th></tr>";
     echo "<tr class='tab_bg_2'>";
     echo "<td> " . __('Entity for software creation') . "</td>";
     echo "<td>";
     $toadd = array(self::CONFIG_NEVER => __('No change of entity'));
     // Keep software in PC entity
     if ($ID > 0) {
         $toadd[self::CONFIG_PARENT] = __('Inheritance of the parent entity');
     }
     $entities = array($entity->fields['entities_id']);
     foreach (getAncestorsOf('glpi_entities', $entity->fields['entities_id']) as $ent) {
         if (Session::haveAccessToEntity($ent)) {
             $entities[] = $ent;
         }
     }
     self::dropdown(array('name' => 'entities_id_software', 'value' => $entity->getField('entities_id_software'), 'toadd' => $toadd, 'entity' => $entities, 'comments' => false));
     if ($entity->fields['entities_id_software'] == self::CONFIG_PARENT) {
         $tid = self::getUsedConfig('entities_id_software', $entity->getField('entities_id'));
         echo "<font class='green'>&nbsp;&nbsp;";
         echo self::getSpecificValueToDisplay('entities_id_software', $tid);
         echo "</font>";
     }
     echo "</td><td colspan='2'></td></tr>";
     if ($canedit) {
         echo "<tr>";
         echo "<td class='tab_bg_2 center' colspan='4'>";
         echo "<input type='hidden' name='id' value='" . $entity->fields["id"] . "'>";
         echo "<input type='submit' name='update' value=\"" . _sx('button', 'Save') . "\" class='submit'>";
         echo "</td></tr>";
         echo "</table>";
         Html::closeForm();
     } else {
         echo "</table>";
     }
     echo "</div>";
 }
Exemple #20
0
 /**
  * @see CommonDBTM::processMassiveActionsForOneItemtype()
  **/
 static function processMassiveActionsForOneItemtype(MassiveAction $ma, CommonDBTM $item, array $ids)
 {
     global $CFG_GLPI;
     $action = $ma->getAction();
     switch ($action) {
         case 'delete':
             foreach ($ids as $id) {
                 if ($item->can($id, DELETE)) {
                     if ($item->delete(array("id" => $id))) {
                         $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_OK);
                     } else {
                         $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_KO);
                         $ma->addMessage($item->getErrorMessage(ERROR_ON_ACTION));
                     }
                 } else {
                     $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_NORIGHT);
                     $ma->addMessage($item->getErrorMessage(ERROR_RIGHT));
                 }
             }
             break;
         case 'restore':
             foreach ($ids as $id) {
                 if ($item->can($id, PURGE)) {
                     if ($item->restore(array("id" => $id))) {
                         $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_OK);
                     } else {
                         $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_KO);
                         $ma->addMessage($item->getErrorMessage(ERROR_ON_ACTION));
                     }
                 } else {
                     $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_NORIGHT);
                     $ma->addMessage($item->getErrorMessage(ERROR_RIGHT));
                 }
             }
             break;
         case 'purge_item_but_devices':
         case 'purge_but_item_linked':
         case 'purge':
             foreach ($ids as $id) {
                 if ($item->can($id, PURGE)) {
                     $force = 1;
                     // Only mark deletion for
                     if ($item->maybeDeleted() && $item->useDeletedToLockIfDynamic() && $item->isDynamic()) {
                         $force = 0;
                     }
                     $delete_array = array('id' => $id);
                     if ($action == 'purge_item_but_devices') {
                         $delete_array['keep_devices'] = true;
                     }
                     if ($item instanceof CommonDropdown) {
                         if ($item->haveChildren()) {
                             if ($action != 'purge_but_item_linked') {
                                 $force = 0;
                                 $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_KO);
                                 $ma->addMessage(__("You can't delete that item by massive actions, because it has sub-items"));
                                 $ma->addMessage(__("but you can do it by the form of the item"));
                                 continue;
                             }
                         }
                         if ($item->isUsed()) {
                             if ($action != 'purge_but_item_linked') {
                                 $force = 0;
                                 $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_KO);
                                 $ma->addMessage(__("You can't delete that item, because it is used for one or more items"));
                                 $ma->addMessage(__("but you can do it by the form of the item"));
                                 continue;
                             }
                         }
                     }
                     if ($item->delete($delete_array, $force)) {
                         $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_OK);
                     } else {
                         $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_KO);
                         $ma->addMessage($item->getErrorMessage(ERROR_ON_ACTION));
                     }
                 } else {
                     $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_NORIGHT);
                     $ma->addMessage($item->getErrorMessage(ERROR_RIGHT));
                 }
             }
             break;
         case 'update':
             if (!isset($ma->POST['search_options']) || !isset($ma->POST['search_options'][$item->getType()])) {
                 return false;
             }
             $index = $ma->POST['search_options'][$item->getType()];
             $searchopt = Search::getCleanedOptions($item->getType(), UPDATE);
             $input = $ma->POST;
             if (isset($searchopt[$index])) {
                 /// Infocoms case
                 if (!isPluginItemType($item->getType()) && Search::isInfocomOption($item->getType(), $index)) {
                     $ic = new Infocom();
                     $link_entity_type = -1;
                     /// Specific entity item
                     if ($searchopt[$index]["table"] == "glpi_suppliers") {
                         $ent = new Supplier();
                         if ($ent->getFromDB($input[$input["field"]])) {
                             $link_entity_type = $ent->fields["entities_id"];
                         }
                     }
                     foreach ($ids as $key) {
                         if ($item->getFromDB($key)) {
                             if ($link_entity_type < 0 || $link_entity_type == $item->getEntityID() || $ent->fields["is_recursive"] && in_array($link_entity_type, getAncestorsOf("glpi_entities", $item->getEntityID()))) {
                                 $input2["items_id"] = $key;
                                 $input2["itemtype"] = $item->getType();
                                 if ($ic->can(-1, CREATE, $input2)) {
                                     // Add infocom if not exists
                                     if (!$ic->getFromDBforDevice($item->getType(), $key)) {
                                         $input2["items_id"] = $key;
                                         $input2["itemtype"] = $item->getType();
                                         unset($ic->fields);
                                         $ic->add($input2);
                                         $ic->getFromDBforDevice($item->getType(), $key);
                                     }
                                     $id = $ic->fields["id"];
                                     unset($ic->fields);
                                     if ($ic->update(array('id' => $id, $input["field"] => $input[$input["field"]]))) {
                                         $ma->itemDone($item->getType(), $key, MassiveAction::ACTION_OK);
                                     } else {
                                         $ma->itemDone($item->getType(), $key, MassiveAction::ACTION_KO);
                                         $ma->addMessage($item->getErrorMessage(ERROR_ON_ACTION));
                                     }
                                 } else {
                                     $ma->itemDone($item->getType(), $key, MassiveAction::ACTION_NORIGHT);
                                     $ma->addMessage($item->getErrorMessage(ERROR_RIGHT));
                                 }
                             } else {
                                 $ma->itemDone($item->getType(), $key, MassiveAction::ACTION_KO);
                                 $ma->addMessage($item->getErrorMessage(ERROR_COMPAT));
                             }
                         } else {
                             $ma->itemDone($item->getType(), $key, MassiveAction::ACTION_KO);
                             $ma->addMessage($item->getErrorMessage(ERROR_NOT_FOUND));
                         }
                     }
                 } else {
                     /// Not infocoms
                     $link_entity_type = array();
                     /// Specific entity item
                     $itemtable = getTableForItemType($item->getType());
                     $itemtype2 = getItemTypeForTable($searchopt[$index]["table"]);
                     if ($item2 = getItemForItemtype($itemtype2)) {
                         if ($index != 80 && $searchopt[$index]["table"] != $itemtable && $item2->isEntityAssign() && $item->isEntityAssign()) {
                             if ($item2->getFromDB($input[$input["field"]])) {
                                 if (isset($item2->fields["entities_id"]) && $item2->fields["entities_id"] >= 0) {
                                     if (isset($item2->fields["is_recursive"]) && $item2->fields["is_recursive"]) {
                                         $link_entity_type = getSonsOf("glpi_entities", $item2->fields["entities_id"]);
                                     } else {
                                         $link_entity_type[] = $item2->fields["entities_id"];
                                     }
                                 }
                             }
                         }
                     }
                     foreach ($ids as $key) {
                         if ($item->canEdit($key) && $item->canMassiveAction($action, $input['field'], $input[$input["field"]])) {
                             if (count($link_entity_type) == 0 || in_array($item->fields["entities_id"], $link_entity_type)) {
                                 if ($item->update(array('id' => $key, $input["field"] => $input[$input["field"]]))) {
                                     $ma->itemDone($item->getType(), $key, MassiveAction::ACTION_OK);
                                 } else {
                                     $ma->itemDone($item->getType(), $key, MassiveAction::ACTION_KO);
                                     $ma->addMessage($item->getErrorMessage(ERROR_ON_ACTION));
                                 }
                             } else {
                                 $ma->itemDone($item->getType(), $key, MassiveAction::ACTION_KO);
                                 $ma->addMessage($item->getErrorMessage(ERROR_COMPAT));
                             }
                         } else {
                             $ma->itemDone($item->getType(), $key, MassiveAction::ACTION_NORIGHT);
                             $ma->addMessage($item->getErrorMessage(ERROR_RIGHT));
                         }
                     }
                 }
             }
             break;
         case 'add_transfer_list':
             $itemtype = $item->getType();
             if (!isset($_SESSION['glpitransfer_list'])) {
                 $_SESSION['glpitransfer_list'] = array();
             }
             if (!isset($_SESSION['glpitransfer_list'][$itemtype])) {
                 $_SESSION['glpitransfer_list'][$itemtype] = array();
             }
             foreach ($ids as $id) {
                 $_SESSION['glpitransfer_list'][$itemtype][$id] = $id;
                 $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_OK);
             }
             $ma->setRedirect($CFG_GLPI['root_doc'] . '/front/transfer.action.php');
             break;
     }
 }
 function getDevicesOfIPRange($items_id)
 {
     global $DB;
     $devicesList = array();
     $pfIPRange = new PluginFusioninventoryIPRange();
     // get all snmpauth
     $a_snmpauth = getAllDatasFromTable("glpi_plugin_fusioninventory_configsecurities");
     $pfIPRange->getFromDB($items_id);
     // Search NetworkEquipment
     $query = "SELECT `glpi_networkequipments`.`id` AS `gID`,\n                         `glpi_ipaddresses`.`name` AS `gnifaddr`,\n                         `plugin_fusioninventory_configsecurities_id`\n                  FROM `glpi_networkequipments`\n                  LEFT JOIN `glpi_plugin_fusioninventory_networkequipments`\n                       ON `networkequipments_id`=`glpi_networkequipments`.`id`\n                  LEFT JOIN `glpi_networkports`\n                       ON `glpi_networkports`.`items_id`=`glpi_networkequipments`.`id`\n                          AND `glpi_networkports`.`itemtype`='NetworkEquipment'\n                  LEFT JOIN `glpi_networknames`\n                       ON `glpi_networknames`.`items_id`=`glpi_networkports`.`id`\n                          AND `glpi_networknames`.`itemtype`='NetworkPort'\n                  LEFT JOIN `glpi_ipaddresses`\n                       ON `glpi_ipaddresses`.`items_id`=`glpi_networknames`.`id`\n                          AND `glpi_ipaddresses`.`itemtype`='NetworkName'\n                  WHERE `glpi_networkequipments`.`is_deleted`='0'\n                       AND `plugin_fusioninventory_configsecurities_id`!='0'";
     if ($pfIPRange->fields['entities_id'] != '-1') {
         $entities = "(" . $pfIPRange->fields['entities_id'];
         foreach (getAncestorsOf("glpi_entities", $pfIPRange->fields['entities_id']) as $parent) {
             $entities .= ",{$parent}";
         }
         $entities .= ")";
         $query .= " AND `glpi_networkequipments`.`entities_id` IN " . $entities . " ";
     }
     $query .= " AND inet_aton(`glpi_ipaddresses`.`name`)\n                      BETWEEN inet_aton('" . $pfIPRange->fields['ip_start'] . "')\n                      AND inet_aton('" . $pfIPRange->fields['ip_end'] . "') ";
     $query .= " GROUP BY `glpi_networkequipments`.`id`";
     $result = $DB->query($query);
     while ($data = $DB->fetch_array($result)) {
         if (isset($a_snmpauth[$data['plugin_fusioninventory_configsecurities_id']])) {
             $devicesList[] = array('NetworkEquipment' => $data['gID']);
         }
     }
     // Search Printer
     $query = "SELECT `glpi_printers`.`id` AS `gID`,\n                      `glpi_ipaddresses`.`name` AS `gnifaddr`,\n                      `plugin_fusioninventory_configsecurities_id`\n               FROM `glpi_printers`\n               LEFT JOIN `glpi_plugin_fusioninventory_printers`\n                       ON `printers_id`=`glpi_printers`.`id`\n               LEFT JOIN `glpi_networkports`\n                    ON `glpi_networkports`.`items_id`=`glpi_printers`.`id`\n                       AND `glpi_networkports`.`itemtype`='Printer'\n               LEFT JOIN `glpi_networknames`\n                    ON `glpi_networknames`.`items_id`=`glpi_networkports`.`id`\n                       AND `glpi_networknames`.`itemtype`='NetworkPort'\n               LEFT JOIN `glpi_ipaddresses`\n                    ON `glpi_ipaddresses`.`items_id`=`glpi_networknames`.`id`\n                       AND `glpi_ipaddresses`.`itemtype`='NetworkName'\n               WHERE `glpi_printers`.`is_deleted`=0\n                     AND `plugin_fusioninventory_configsecurities_id`!='0'";
     if ($pfIPRange->fields['entities_id'] != '-1') {
         $entities = "(" . $pfIPRange->fields['entities_id'];
         foreach (getAncestorsOf("glpi_entities", $pfIPRange->fields['entities_id']) as $parent) {
             $entities .= ",{$parent}";
         }
         $entities .= ")";
         $query .= "AND `glpi_printers`.`entities_id` IN " . $entities . " ";
     }
     $query .= " AND inet_aton(`glpi_ipaddresses`.`name`)\n                   BETWEEN inet_aton('" . $pfIPRange->fields['ip_start'] . "')\n                   AND inet_aton('" . $pfIPRange->fields['ip_end'] . "') ";
     $query .= " GROUP BY `glpi_printers`.`id`";
     $result = $DB->query($query);
     while ($data = $DB->fetch_array($result)) {
         if (isset($a_snmpauth[$data['plugin_fusioninventory_configsecurities_id']])) {
             $devicesList[] = array('Printer' => $data['gID']);
         }
     }
     return $devicesList;
 }
 /** Get data to display on GANTT for a project task
  *
  * @param $ID ID of the project task
  */
 static function getDataToDisplayOnGantt($ID)
 {
     global $DB;
     $todisplay = array();
     $task = new self();
     //       echo $ID.'<br>';
     if ($task->getFromDB($ID)) {
         $subtasks = array();
         foreach ($DB->request('glpi_projecttasks', array('projecttasks_id' => $ID, 'ORDER' => array('plan_start_date', 'real_start_date'))) as $data) {
             $subtasks += static::getDataToDisplayOnGantt($data['id']);
         }
         $real_begin = NULL;
         $real_end = NULL;
         // Use real if set
         if (!is_null($task->fields['real_start_date'])) {
             $real_begin = $task->fields['real_start_date'];
         }
         // Determine begin / end date of current task if not set (min/max sub projects / tasks)
         if (is_null($real_begin)) {
             if (!is_null($task->fields['plan_start_date'])) {
                 $real_begin = $task->fields['plan_start_date'];
             } else {
                 foreach ($subtasks as $subtask) {
                     if (is_null($real_begin) || !is_null($subtask['from']) && $real_begin > $subtask['from']) {
                         $real_begin = $subtask['from'];
                     }
                 }
             }
         }
         // Use real if set
         if (!is_null($task->fields['real_end_date'])) {
             $real_end = $task->fields['real_end_date'];
         }
         if (is_null($real_end)) {
             if (!is_null($task->fields['plan_end_date'])) {
                 $real_end = $task->fields['plan_end_date'];
             } else {
                 foreach ($subtasks as $subtask) {
                     if (is_null($real_end) || !is_null($subtask['to']) && $real_end < $subtask['to']) {
                         $real_end = $subtask['to'];
                     }
                 }
             }
         }
         $parents = 0;
         if ($task->fields['projecttasks_id'] > 0) {
             $parents = count(getAncestorsOf("glpi_projecttasks", $ID));
         }
         if ($task->fields['is_milestone']) {
             $percent = "";
         } else {
             $percent = isset($task->fields['percent_done']) ? $task->fields['percent_done'] : 0;
         }
         // Add current task
         $todisplay[$real_begin . '#' . $real_end . '#task' . $task->getID()] = array('id' => $task->getID(), 'name' => $task->fields['name'], 'desc' => $task->fields['content'], 'link' => $task->getlink(), 'type' => 'task', 'percent' => $percent, 'from' => $real_begin, 'parents' => $parents, 'to' => $real_end, 'is_milestone' => $task->fields['is_milestone']);
         // Add ordered subtasks
         foreach ($subtasks as $key => $val) {
             $todisplay[$key] = $val;
         }
     }
     return $todisplay;
 }
Exemple #23
0
 /**
  * Print the Software / license form
  *
  * @param $ID        integer  Id of the version or the template to print
  * @param $options   array    of possible options:
  *     - target form target
  *     - softwares_id ID of the software for add process
  *
  * @return true if displayed  false if item not found or not right to display
  **/
 function showForm($ID, $options = array())
 {
     global $CFG_GLPI;
     $softwares_id = -1;
     if (isset($options['softwares_id'])) {
         $softwares_id = $options['softwares_id'];
     }
     if ($ID < 0) {
         // Create item
         $this->fields['softwares_id'] = $softwares_id;
         $this->fields['number'] = 1;
         $soft = new Software();
         if ($soft->getFromDB($softwares_id) && in_array($_SESSION['glpiactive_entity'], getAncestorsOf('glpi_entities', $soft->getEntityID()))) {
             $options['entities_id'] = $soft->getEntityID();
         }
     }
     $this->initForm($ID, $options);
     $this->showFormHeader($options);
     echo "<tr class='tab_bg_1'>";
     echo "<td>" . Software::getTypeName(1) . "</td>";
     echo "<td>";
     if ($ID > 0) {
         $softwares_id = $this->fields["softwares_id"];
     } else {
         echo "<input type='hidden' name='softwares_id' value='{$softwares_id}'>";
     }
     echo "<a href='software.form.php?id=" . $softwares_id . "'>" . Dropdown::getDropdownName("glpi_softwares", $softwares_id) . "</a>";
     echo "</td>";
     echo "<td>" . __('Type') . "</td>";
     echo "<td>";
     SoftwareLicenseType::dropdown(array('value' => $this->fields["softwarelicensetypes_id"]));
     echo "</td></tr>\n";
     echo "<tr class='tab_bg_1'>";
     echo "<td>" . __('Name') . "</td>";
     echo "<td>";
     Html::autocompletionTextField($this, "name");
     echo "</td>";
     echo "<td>" . __('Serial number') . "</td>";
     echo "<td>";
     Html::autocompletionTextField($this, "serial");
     echo "</td></tr>\n";
     echo "<tr class='tab_bg_1'>";
     echo "<td>" . __('Purchase version') . "</td>";
     echo "<td>";
     SoftwareVersion::dropdown(array('name' => "softwareversions_id_buy", 'softwares_id' => $this->fields["softwares_id"], 'value' => $this->fields["softwareversions_id_buy"]));
     echo "</td>";
     echo "<td>" . __('Inventory number') . "</td>";
     echo "<td>";
     Html::autocompletionTextField($this, "otherserial");
     echo "</td></tr>\n";
     echo "<tr class='tab_bg_1'>";
     echo "<td>" . __('Version in use') . "</td>";
     echo "<td>";
     SoftwareVersion::dropdown(array('name' => "softwareversions_id_use", 'softwares_id' => $this->fields["softwares_id"], 'value' => $this->fields["softwareversions_id_use"]));
     echo "</td>";
     echo "<td rowspan='" . ($ID > 0 ? '4' : '3') . "' class='middle'>" . __('Comments') . "</td>";
     echo "<td class='center middle' rowspan='" . ($ID > 0 ? '4' : '3') . "'>";
     echo "<textarea cols='45' rows='5' name='comment' >" . $this->fields["comment"] . "</textarea>";
     echo "</td></tr>\n";
     echo "<tr class='tab_bg_1'>";
     echo "<td>" . _x('quantity', 'Number') . "</td>";
     echo "<td>";
     Dropdown::showNumber("number", array('value' => $this->fields["number"], 'min' => 1, 'max' => 10000, 'step' => 1, 'toadd' => array(-1 => __('Unlimited'))));
     if ($ID > 0) {
         echo "&nbsp;";
         if ($this->fields['is_valid']) {
             echo "<span class='green'>" . _x('adjective', 'Valid') . '<span>';
         } else {
             echo "<span class='red'>" . _x('adjective', 'Invalid') . '<span>';
         }
     }
     echo "</td></tr>\n";
     echo "<tr class='tab_bg_1'>";
     echo "<td>" . __('Expiration') . "</td>";
     echo "<td>";
     Html::showDateField('expire', array('value' => $this->fields["expire"]));
     if ($ID && is_null($this->fields["expire"])) {
         echo "<br>" . __('Never expire') . "&nbsp;";
         Html::showToolTip(__('On search engine, use "Expiration contains NULL" to search licenses with no expiration date'));
     }
     Alert::displayLastAlert('SoftwareLicense', $ID);
     echo "</td></tr>\n";
     if ($ID > 0) {
         echo "<tr class='tab_bg_1'>";
         echo "<td>" . __('Last update') . "</td>";
         echo "<td>" . ($this->fields["date_mod"] ? Html::convDateTime($this->fields["date_mod"]) : __('Never'));
         echo "</td></tr>";
     }
     $this->showFormButtons($options);
     return true;
 }
 /**
  * Update location for a computer if needed after rule processing
  *
  * @param line_links
  * @param data
  *
  * @return nothing
  */
 static function updateLocation($line_links, $data)
 {
     //If there's a location to update
     if (isset($data['locations_id'])) {
         $computer = new Computer();
         $computer->getFromDB($line_links['computers_id']);
         $ancestors = getAncestorsOf('glpi_entities', $computer->fields['entities_id']);
         $location = new Location();
         if ($location->getFromDB($data['locations_id'])) {
             //If location is in the same entity as the computer, or if the location is
             //defined in a parent entity, but recursive
             if ($location->fields['entities_id'] == $computer->fields['entities_id'] || in_array($location->fields['entities_id'], $ancestors) && $location->fields['is_recursive']) {
                 $tmp['locations_id'] = $data['locations_id'];
                 $tmp['id'] = $line_links['computers_id'];
                 $computer->update($tmp);
             }
         }
     }
 }
 function getValueAncestor($fieldname, $entities_id, $itemtype = '', $items_id = '')
 {
     global $DB;
     if ($itemtype != '' and $items_id != '') {
         $query = "SELECT * FROM `" . $this->getTable() . "`\n            WHERE `items_id`='" . $items_id . "'\n               AND `itemtype`='" . $itemtype . "'\n            LIMIT 1";
         $result = $DB->query($query);
         if ($DB->numrows($result) == '1') {
             $data = $DB->fetch_assoc($result);
             if ($fieldname == 'jetlag') {
                 if ($data[$fieldname] != '100') {
                     return $data[$fieldname];
                 }
             } else {
                 if ($data[$fieldname] != '-1') {
                     return $data[$fieldname];
                 }
             }
         }
     }
     $query = "SELECT * FROM `" . $this->getTable() . "`\n         WHERE `items_id`='" . $entities_id . "'\n            AND `itemtype`='Entity'\n         LIMIT 1";
     $result = $DB->query($query);
     if ($DB->numrows($result) == '0') {
         $entities_ancestors = getAncestorsOf("glpi_entities", $entities_id);
         $nbentities = count($entities_ancestors);
         for ($i = 0; $i < $nbentities; $i++) {
             $entity = array_pop($entities_ancestors);
             $query = "SELECT * FROM `" . $this->getTable() . "`\n               WHERE `items_id`='" . $entity . "'\n                  AND `itemtype`='Entity'\n               LIMIT 1";
             $result = $DB->query($query);
             if ($DB->numrows($result) != '0') {
                 $data = $DB->fetch_assoc($result);
                 if ($fieldname == 'jetlag') {
                     if ($data[$fieldname] != '100') {
                         return $data[$fieldname];
                     }
                 } else {
                     if ($data[$fieldname] != '-1') {
                         return $data[$fieldname];
                     }
                 }
             }
         }
     } else {
         $data = $DB->fetch_assoc($result);
         if ($data[$fieldname] != '-1') {
             return $data[$fieldname];
         } else {
             $entities_ancestors = getAncestorsOf("glpi_entities", $entities_id);
             $nbentities = count($entities_ancestors);
             for ($i = 0; $i < $nbentities; $i++) {
                 $entity = array_pop($entities_ancestors);
                 $query = "SELECT * FROM `" . $this->getTable() . "`\n                  WHERE `items_id`='" . $entity . "'\n                     AND `itemtype`='Entity'\n                  LIMIT 1";
                 $result = $DB->query($query);
                 if ($DB->numrows($result) != '0') {
                     $data = $DB->fetch_assoc($result);
                     if ($fieldname == 'jetlag') {
                         if ($data[$fieldname] != '100') {
                             return $data[$fieldname];
                         }
                     } else {
                         if ($data[$fieldname] != '-1') {
                             return $data[$fieldname];
                         }
                     }
                 }
             }
         }
     }
 }
Exemple #26
0
 /**
  * Get value of config
  * 
  * @global object $DB
  * @param value $name field name 
  * @param integer $entities_id
  * 
  * @return value of field 
  */
 function getValueAncestor($name, $entities_id)
 {
     global $DB;
     $entities_ancestors = getAncestorsOf("glpi_entities", $entities_id);
     $nbentities = count($entities_ancestors);
     for ($i = 0; $i < $nbentities; $i++) {
         $entity = array_pop($entities_ancestors);
         $query = "SELECT * FROM `" . $this->getTable() . "`\n            WHERE `entities_id`='" . $entity . "'\n               AND `" . $name . "` IS NOT NULL\n            LIMIT 1";
         $result = $DB->query($query);
         if ($DB->numrows($result) != '0') {
             $data = $DB->fetch_assoc($result);
             return $data[$name];
         }
     }
     $this->getFromDB(1);
     return $this->getField($name);
 }
 /**
  * Print the Software / license form
  *
  * @param $ID        integer  Id of the version or the template to print
  * @param $options   array    of possible options:
  *     - target form target
  *     - softwares_id ID of the software for add process
  *
  * @return true if displayed  false if item not found or not right to display
  **/
 function showForm($ID, $options = array())
 {
     global $CFG_GLPI;
     $softwares_id = -1;
     if (isset($options['softwares_id'])) {
         $softwares_id = $options['softwares_id'];
     }
     if ($ID < 0) {
         // Create item
         $this->fields['softwares_id'] = $softwares_id;
         $this->fields['number'] = 1;
         $soft = new Software();
         if ($soft->getFromDB($softwares_id) && in_array($_SESSION['glpiactive_entity'], getAncestorsOf('glpi_entities', $soft->getEntityID()))) {
             $options['entities_id'] = $soft->getEntityID();
         }
     }
     $this->initForm($ID, $options);
     $this->showFormHeader($options);
     // Restore saved value or override with page parameter
     if (!isset($options['template_preview'])) {
         if (isset($_REQUEST)) {
             $saved = Html::cleanPostForTextArea($_REQUEST);
         }
     }
     foreach ($this->fields as $name => $value) {
         if (isset($saved[$name]) && empty($this->fields[$name])) {
             $this->fields[$name] = $saved[$name];
         }
     }
     echo "<input type='hidden' name='withtemplate' value='" . $options['withtemplate'] . "'>";
     echo "<tr class='tab_bg_1'>";
     echo "<td>" . Software::getTypeName(1) . "</td>";
     echo "<td>";
     if ($ID > 0) {
         $softwares_id = $this->fields["softwares_id"];
         echo "<input type='hidden' name='softwares_id' value='{$softwares_id}'>";
         echo "<a href='software.form.php?id=" . $softwares_id . "'>" . Dropdown::getDropdownName("glpi_softwares", $softwares_id) . "</a>";
     } else {
         Dropdown::show('Software', array('condition' => "`is_template`='0' AND `is_deleted`='0'", 'entity' => $_SESSION['glpiactive_entity'], 'entity_sons' => $_SESSION['glpiactive_entity_recursive'], 'on_change' => 'this.form.submit()', 'value' => $softwares_id));
     }
     echo "</td>";
     echo "<td colspan='2'>";
     echo "</td></tr>\n";
     echo "<tr class='tab_bg_1'>";
     echo "<td>" . sprintf(__('%1$s%2$s'), __('Name'), isset($options['withtemplate']) && $options['withtemplate'] ? "*" : "") . "</td>";
     echo "<td>";
     $objectName = autoName($this->fields["name"], "name", isset($options['withtemplate']) && $options['withtemplate'] == 2, $this->getType(), $this->fields["entities_id"]);
     Html::autocompletionTextField($this, 'name', array('value' => $objectName));
     echo "</td>";
     echo "<td>" . __('Status') . "</td>";
     echo "<td>";
     State::dropdown(array('value' => $this->fields["states_id"], 'entity' => $this->fields["entities_id"], 'condition' => "`is_visible_softwarelicense`"));
     echo "</td></tr>\n";
     echo "<tr class='tab_bg_1'>";
     echo "<td>" . __('Location') . "</td><td>";
     Location::dropdown(array('value' => $this->fields["locations_id"], 'entity' => $this->fields["entities_id"]));
     echo "</td>";
     echo "<td>" . __('Type') . "</td>";
     echo "<td>";
     SoftwareLicenseType::dropdown(array('value' => $this->fields["softwarelicensetypes_id"]));
     echo "</td></tr>\n";
     echo "<tr class='tab_bg_1'>";
     echo "<td>" . __('Technician in charge of the hardware') . "</td>";
     echo "<td>";
     User::dropdown(array('name' => 'users_id_tech', 'value' => $this->fields["users_id_tech"], 'right' => 'own_ticket', 'entity' => $this->fields["entities_id"]));
     echo "</td>";
     echo "<td>" . __('Publisher') . "</td>";
     echo "<td>";
     Manufacturer::dropdown(array('value' => $this->fields["manufacturers_id"]));
     echo "</td></tr>\n";
     echo "<tr class='tab_bg_1'>";
     echo "<td>" . __('Group in charge of the hardware') . "</td>";
     echo "<td>";
     Group::dropdown(array('name' => 'groups_id_tech', 'value' => $this->fields['groups_id_tech'], 'entity' => $this->fields['entities_id'], 'condition' => '`is_assign`'));
     echo "</td>";
     echo "<td>" . __('Serial number') . "</td>";
     echo "<td>";
     Html::autocompletionTextField($this, "serial");
     echo "</td></tr>\n";
     echo "<tr class='tab_bg_1'>";
     echo "<td >" . __('User') . "</td>";
     echo "<td >";
     User::dropdown(array('value' => $this->fields["users_id"], 'entity' => $this->fields["entities_id"], 'right' => 'all'));
     echo "</td>";
     echo "<td>" . sprintf(__('%1$s%2$s'), __('Inventory number'), isset($options['withtemplate']) && $options['withtemplate'] ? "*" : "");
     echo "</td>";
     echo "<td>";
     $objectName = autoName($this->fields["otherserial"], "otherserial", isset($options['withtemplate']) && $options['withtemplate'] == 2, $this->getType(), $this->fields["entities_id"]);
     Html::autocompletionTextField($this, 'otherserial', array('value' => $objectName));
     echo "</td></tr>\n";
     echo "<tr class='tab_bg_1'>";
     echo "<td>" . __('Group') . "</td><td>";
     Group::dropdown(array('value' => $this->fields["groups_id"], 'entity' => $this->fields["entities_id"], 'condition' => '`is_itemgroup`'));
     echo "</td>";
     echo "<td rowspan='4' class='middle'>" . __('Comments') . "</td>";
     echo "<td class='center middle' rowspan='4'>";
     echo "<textarea cols='45' rows='4' name='comment' >" . $this->fields["comment"] . "</textarea>";
     echo "</td></tr>\n";
     echo "<tr class='tab_bg_1'>";
     echo "<td>" . __('Version in use') . "</td>";
     echo "<td>";
     SoftwareVersion::dropdownForOneSoftware(array('name' => "softwareversions_id_use", 'softwares_id' => $this->fields["softwares_id"], 'value' => $this->fields["softwareversions_id_use"]));
     echo "</td></tr>";
     echo "<tr class='tab_bg_1'>";
     echo "<td>" . __('Purchase version') . "</td>";
     echo "<td>";
     SoftwareVersion::dropdownForOneSoftware(array('name' => "softwareversions_id_buy", 'softwares_id' => $this->fields["softwares_id"], 'value' => $this->fields["softwareversions_id_buy"]));
     echo "</td></tr>\n";
     echo "<tr class='tab_bg_1'>";
     echo "<td>" . _x('quantity', 'Number') . "</td>";
     echo "<td>";
     Dropdown::showNumber("number", array('value' => $this->fields["number"], 'min' => 1, 'max' => 10000, 'step' => 1, 'toadd' => array(-1 => __('Unlimited'))));
     if ($ID > 0) {
         echo "&nbsp;";
         if ($this->fields['is_valid']) {
             echo "<span class='green'>" . _x('adjective', 'Valid') . '<span>';
         } else {
             echo "<span class='red'>" . _x('adjective', 'Invalid') . '<span>';
         }
     }
     echo "</td></tr>\n";
     echo "<tr class='tab_bg_1'>";
     echo "<td>" . __('Expiration') . "</td>";
     echo "<td>";
     Html::showDateField('expire', array('value' => $this->fields["expire"]));
     if ($ID && is_null($this->fields["expire"])) {
         echo "<br>" . __('Never expire') . "&nbsp;";
         Html::showToolTip(__('On search engine, use "Expiration contains NULL" to search licenses with no expiration date'));
     }
     Alert::displayLastAlert('SoftwareLicense', $ID);
     echo "</td><td colspan='2'></td></tr>\n";
     $this->showFormButtons($options);
     return true;
 }
/**
 * Get SQL request to restrict to current entities of the user
 *
 * @param $separator : separator in the begin of the request
 * @param $table : table where apply the limit (if needed, multiple tables queries)
 * @param $field : field where apply the limit (id != entities_id)
 * @param $value : entity to restrict (if not set use $_SESSION['glpiactiveentities']). single item or array
 * @param $is_recursive : need to use recursive process to find item (field need to be named recursive)
 *
 * @return String : the WHERE clause to restrict
**/
function getEntitiesRestrictRequest($separator = "AND", $table = "", $field = "", $value = '', $is_recursive = false)
{
    $query = $separator . " ( ";
    // !='0' needed because consider as empty
    if ($value != '0' && empty($value) && isset($_SESSION['glpishowallentities']) && $_SESSION['glpishowallentities']) {
        // Not ADD "AND 1" if not needed
        if (trim($separator) == "AND") {
            return "";
        }
        return $query . " 1 ) ";
    }
    if (!empty($table)) {
        $query .= "`{$table}`.";
    }
    if (empty($field)) {
        if ($table == 'glpi_entities') {
            $field = "id";
        } else {
            $field = "entities_id";
        }
    }
    $query .= "`{$field}`";
    if (is_array($value)) {
        $query .= " IN ('" . implode("','", $value) . "') ";
    } else {
        if (strlen($value) == 0) {
            $query .= " IN (" . $_SESSION['glpiactiveentities_string'] . ") ";
        } else {
            $query .= " = '{$value}' ";
        }
    }
    if ($is_recursive) {
        $ancestors = array();
        if (is_array($value)) {
            foreach ($value as $val) {
                $ancestors = array_unique(array_merge(getAncestorsOf("glpi_entities", $val), $ancestors));
            }
            $ancestors = array_diff($ancestors, $value);
        } else {
            if (strlen($value) == 0) {
                $ancestors = $_SESSION['glpiparententities'];
            } else {
                $ancestors = getAncestorsOf("glpi_entities", $value);
            }
        }
        if (count($ancestors)) {
            if ($table == 'glpi_entities') {
                $query .= " OR `{$table}`.`{$field}` IN ('" . implode("','", $ancestors) . "')";
            } else {
                $query .= " OR (`{$table}`.`is_recursive`='1'\n                            AND `{$table}`.`{$field}` IN ('" . implode("','", $ancestors) . "'))";
            }
        }
    }
    $query .= " ) ";
    return $query;
}
 /**
  * Can I change recursive flag to false
  * check if there is "linked" object in another entity
  *
  * Overloaded from CommonDBTM
  *
  * @since version 0.85
  *
  * @return booleen
  **/
 function canUnrecurs()
 {
     global $DB;
     $ID = $this->fields['id'];
     if ($ID < 0 || !$this->fields['is_recursive']) {
         return true;
     }
     if (!parent::canUnrecurs()) {
         return false;
     }
     $entities = "(" . $this->fields['entities_id'];
     foreach (getAncestorsOf("glpi_entities", $this->fields['entities_id']) as $papa) {
         $entities .= ",{$papa}";
     }
     $entities .= ")";
     // RELATION : device -> item_device -> item
     $linktype = static::getItem_DeviceType();
     $linktable = getTableForItemType($linktype);
     $sql = "SELECT `itemtype`,\n                     GROUP_CONCAT(DISTINCT `items_id`) AS ids\n              FROM `{$linktable}`\n              WHERE `{$linktable}`.`" . $this->getForeignKeyField() . "` = '{$ID}'\n              GROUP BY `itemtype`";
     foreach ($DB->request($sql) as $data) {
         if (!empty($data["itemtype"])) {
             $itemtable = getTableForItemType($data["itemtype"]);
             if ($item = getItemForItemtype($data["itemtype"])) {
                 // For each itemtype which are entity dependant
                 if ($item->isEntityAssign()) {
                     if (countElementsInTable($itemtable, "id IN (" . $data["ids"] . ")\n                                           AND entities_id NOT IN {$entities}") > 0) {
                         return false;
                     }
                 }
             }
         }
     }
     return true;
 }
 /**
  * Can I change recursive flag to false
  * check if there is "linked" object in another entity
  *
  * May be overloaded if needed
  *
  * @return booleen
  **/
 function canUnrecurs()
 {
     global $DB, $CFG_GLPI;
     $ID = $this->fields['id'];
     if ($ID < 0 || !$this->fields['is_recursive']) {
         return true;
     }
     $entities = getAncestorsOf('glpi_entities', $this->fields['entities_id']);
     $entities[] = $this->fields['entities_id'];
     $RELATION = getDbRelations();
     if ($this instanceof CommonTreeDropdown) {
         $f = getForeignKeyFieldForTable($this->getTable());
         if (countElementsInTable($this->getTable(), [$f => $ID, 'NOT' => ['entities_id' => $entities]]) > 0) {
             return false;
         }
     }
     if (isset($RELATION[$this->getTable()])) {
         foreach ($RELATION[$this->getTable()] as $tablename => $field) {
             if ($tablename[0] != '_') {
                 $itemtype = getItemTypeForTable($tablename);
                 $item = new $itemtype();
                 if ($item->isEntityAssign()) {
                     // 1->N Relation
                     if (is_array($field)) {
                         foreach ($field as $f) {
                             if (countElementsInTable($tablename, [$f => $ID, 'NOT' => ['entities_id' => $entities]]) > 0) {
                                 return false;
                             }
                         }
                     } else {
                         if (countElementsInTable($tablename, [$field => $ID, 'NOT' => ['entities_id' => $entities]]) > 0) {
                             return false;
                         }
                     }
                 } else {
                     foreach ($RELATION as $othertable => $rel) {
                         // Search for a N->N Relation with devices
                         if ($othertable == "_virtual_device" && isset($rel[$tablename])) {
                             $devfield = $rel[$tablename][0];
                             // items_id...
                             $typefield = $rel[$tablename][1];
                             // itemtype...
                             $sql = "SELECT DISTINCT `{$typefield}` AS itemtype\n                                FROM `{$tablename}`\n                                WHERE `{$field}`='{$ID}'";
                             $res = $DB->query($sql);
                             // Search linked device of each type
                             if ($res) {
                                 while ($data = $DB->fetch_assoc($res)) {
                                     $itemtype = $data["itemtype"];
                                     $itemtable = getTableForItemType($itemtype);
                                     $item = new $itemtype();
                                     if ($item->isEntityAssign()) {
                                         if (countElementsInTable(array($tablename, $itemtable), ["{$tablename}.{$field}" => $ID, "{$tablename}.{$typefield}" => $itemtype, 'FKEY' => [$tablename => $devfield, $itemtable => 'id'], 'NOT' => [$itemtable . '.entities_id' => $entities]]) > '0') {
                                             return false;
                                         }
                                     }
                                 }
                             }
                         } else {
                             if ($othertable != $this->getTable() && isset($rel[$tablename])) {
                                 // Search for another N->N Relation
                                 $itemtype = getItemTypeForTable($othertable);
                                 $item = new $itemtype();
                                 if ($item->isEntityAssign()) {
                                     if (is_array($rel[$tablename])) {
                                         foreach ($rel[$tablename] as $otherfield) {
                                             if (countElementsInTable(array($tablename, $othertable), ["{$tablename}.{$field}" => $ID, 'FKEY' => [$tablename => $otherfield, $othertable => 'id'], 'NOT' => [$othertable . '.entities_id' => $entities]]) > '0') {
                                                 return false;
                                             }
                                         }
                                     } else {
                                         $otherfield = $rel[$tablename];
                                         if (countElementsInTable(array($tablename, $othertable), ["{$tablename}.{$field}" => $ID, 'FKEY' => [$tablename => $otherfield, $othertable => 'id'], 'NOT' => [$othertable . '.entities_id' => $entities]]) > '0') {
                                             return false;
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     // Doc links to this item
     if ($this->getType() > 0 && countElementsInTable(array('glpi_documents_items', 'glpi_documents'), ['glpi_documents_items.items_id' => $ID, 'glpi_documents_items.itemtype' => $this->getType(), 'FKEY' => ['glpi_documents_items' => 'documents_id', 'glpi_documents' => 'id'], 'NOT' => ['glpi_documents.entities_id' => $entities]]) > '0') {
         return false;
     }
     // TODO : do we need to check all relations in $RELATION["_virtual_device"] for this item
     return true;
 }