/** * @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()))); }
public static function queryAccountsList($values) { global $DB; $ID = $values["id"]; $aeskey = $values["aeskey"]; $PluginAccountsHash = new PluginAccountsHash(); $PluginAccountsHash->getFromDB($ID); $hash = $PluginAccountsHash->fields["hash"]; if ($PluginAccountsHash->isRecursive()) { $entities = getSonsOf('glpi_entities', $PluginAccountsHash->getEntityID()); } else { $entities = $PluginAccountsHash->getEntityID(); } if ($aeskey) { $query = "SELECT `glpi_plugin_accounts_accounts`.*,\n `glpi_plugin_accounts_accounttypes`.`name` AS type\n FROM `glpi_plugin_accounts_accounts`\n LEFT JOIN `glpi_plugin_accounts_accounttypes`\n ON (`glpi_plugin_accounts_accounts`.`plugin_accounts_accounttypes_id` = `glpi_plugin_accounts_accounttypes`.`id`)\n WHERE `is_deleted`= '0'"; $query .= getEntitiesRestrictRequest(" AND ", "glpi_plugin_accounts_accounts", '', $entities, $PluginAccountsHash->maybeRecursive()); $query .= " ORDER BY `type`,`name`"; foreach ($DB->request($query) as $data) { $accounts[] = $data; } $list = array(); if (!empty($accounts)) { foreach ($accounts as $account) { $ID = $account["id"]; $list[$ID]["id"] = $account["id"]; $list[$ID]["name"] = $account["name"]; if (Session::isMultiEntitiesMode()) { $list[$ID]["entities_id"] = Dropdown::getDropdownName("glpi_entities", $account["entities_id"]); } $list[$ID]["type"] = $account["type"]; $list[$ID]["login"] = $account["login"]; $list[$ID]["password"] = $account["encrypted_password"]; } } } return $list; }
/** * @param $itemtype * @param $type * @param $begin (default '') * @param $end (default '') * @param $param (default '') * @param $value (default '') * @param $value2 (default '') */ static function constructEntryValues($itemtype, $type, $begin = "", $end = "", $param = "", $value = "", $value2 = "") { global $DB; if (!($item = getItemForItemtype($itemtype))) { return; } $table = $item->getTable(); $fkfield = $item->getForeignKeyField(); if (!($userlinkclass = getItemForItemtype($item->userlinkclass))) { return; } $userlinktable = $userlinkclass->getTable(); if (!($grouplinkclass = getItemForItemtype($item->grouplinkclass))) { return; } $grouplinktable = $grouplinkclass->getTable(); if (!($supplierlinkclass = getItemForItemtype($item->supplierlinkclass))) { return; } $supplierlinktable = $supplierlinkclass->getTable(); $tasktable = getTableForItemType($item->getType() . 'Task'); $closed_status = $item->getClosedStatusArray(); $solved_status = array_merge($closed_status, $item->getSolvedStatusArray()); $query = ""; $WHERE = "WHERE NOT `{$table}`.`is_deleted` " . getEntitiesRestrictRequest("AND", $table); $LEFTJOIN = ""; $LEFTJOINUSER = "******"; $LEFTJOINGROUP = "LEFT JOIN `{$grouplinktable}`\n ON (`{$grouplinktable}`.`{$fkfield}` = `{$table}`.`id`)"; $LEFTJOINSUPPLIER = "LEFT JOIN `{$supplierlinktable}`\n ON (`{$supplierlinktable}`.`{$fkfield}` = `{$table}`.`id`)"; switch ($param) { case "technicien": $LEFTJOIN = $LEFTJOINUSER; $WHERE .= " AND (`{$userlinktable}`.`users_id` = '{$value}'\n AND `{$userlinktable}`.`type`='" . CommonITILActor::ASSIGN . "')"; break; case "technicien_followup": $WHERE .= " AND `{$tasktable}`.`users_id` = '{$value}'"; $LEFTJOIN = " LEFT JOIN `{$tasktable}`\n ON (`{$tasktable}`.`{$fkfield}` = `{$table}`.`id`)"; break; case "user": $LEFTJOIN = $LEFTJOINUSER; $WHERE .= " AND (`{$userlinktable}`.`users_id` = '{$value}'\n AND `{$userlinktable}`.`type` ='" . CommonITILActor::REQUESTER . "')"; break; case "usertitles_id": $LEFTJOIN = $LEFTJOINUSER; $LEFTJOIN .= " LEFT JOIN `glpi_users`\n ON (`glpi_users`.`id` = `{$userlinktable}`.`users_id`)"; $WHERE .= " AND (`glpi_users`.`usertitles_id` = '{$value}'\n AND `{$userlinktable}`.`type` = '" . CommonITILActor::REQUESTER . "')"; break; case "usercategories_id": $LEFTJOIN = $LEFTJOINUSER; $LEFTJOIN .= " LEFT JOIN `glpi_users`\n ON (`glpi_users`.`id` = `{$userlinktable}`.`users_id`)"; $WHERE .= " AND (`glpi_users`.`usercategories_id` = '{$value}'\n AND `{$userlinktable}`.`type` = '" . CommonITILActor::REQUESTER . "')"; break; case "itilcategories_tree": if ($value == $value2) { $categories = array($value); } else { $categories = getSonsOf("glpi_itilcategories", $value); } $condition = implode("','", $categories); $WHERE .= " AND `{$table}`.`itilcategories_id` IN ('{$condition}')"; break; case 'locations_tree': if ($value == $value2) { $categories = array($value); } else { $categories = getSonsOf('glpi_locations', $value); } $condition = implode("','", $categories); $WHERE .= " AND `{$table}`.`locations_id` IN ('{$condition}')"; break; case 'group_tree': case 'groups_tree_assign': $grptype = $param == 'group_tree' ? CommonITILActor::REQUESTER : CommonITILActor::ASSIGN; if ($value == $value2) { $groups = array($value); } else { $groups = getSonsOf("glpi_groups", $value); } $condition = implode("','", $groups); $LEFTJOIN = $LEFTJOINGROUP; $WHERE .= " AND (`{$grouplinktable}`.`groups_id` IN ('{$condition}')\n AND `{$grouplinktable}`.`type` = '{$grptype}')"; break; case "group": $LEFTJOIN = $LEFTJOINGROUP; $WHERE .= " AND (`{$grouplinktable}`.`groups_id` = '{$value}'\n AND `{$grouplinktable}`.`type` = '" . CommonITILActor::REQUESTER . "')"; break; case "groups_id_assign": $LEFTJOIN = $LEFTJOINGROUP; $WHERE .= " AND (`{$grouplinktable}`.`groups_id` = '{$value}'\n AND `{$grouplinktable}`.`type` = '" . CommonITILActor::ASSIGN . "')"; break; case "suppliers_id_assign": $LEFTJOIN = $LEFTJOINSUPPLIER; $WHERE .= " AND (`{$supplierlinktable}`.`suppliers_id` = '{$value}'\n AND `{$supplierlinktable}`.`type` = '" . CommonITILActor::ASSIGN . "')"; break; case "requesttypes_id": case "solutiontypes_id": case "urgency": case "impact": case "priority": case "users_id_recipient": case "type": case "itilcategories_id": case 'locations_id': $WHERE .= " AND `{$table}`.`{$param}` = '{$value}'"; break; case "device": $devtable = getTableForItemType('Computer_' . $value2); $fkname = getForeignKeyFieldForTable(getTableForItemType($value2)); //select computers IDs that are using this device; $LEFTJOIN = ''; $linkdetable = $table; if ($itemtype == 'Ticket') { $linkedtable = 'glpi_items_tickets'; $LEFTJOIN .= " LEFT JOIN `glpi_items_tickets`\n ON (`glpi_tickets`.`id` = `glpi_items_tickets`.`tickets_id`)"; } $LEFTJOIN .= " INNER JOIN `glpi_computers`\n ON (`glpi_computers`.`id` = `{$linkedtable}`.`items_id`\n AND `{$linkedtable}`.`itemtype` = 'Computer')\n INNER JOIN `{$devtable}`\n ON (`glpi_computers`.`id` = `{$devtable}`.`computers_id`\n AND `{$devtable}`.`{$fkname}` = '{$value}')"; $WHERE .= " AND `glpi_computers`.`is_template` <> '1' "; break; case "comp_champ": $ftable = getTableForItemType($value2); $champ = getForeignKeyFieldForTable($ftable); $LEFTJOIN = ''; $linkdetable = $table; if ($itemtype == 'Ticket') { $linkedtable = 'glpi_items_tickets'; $LEFTJOIN .= " LEFT JOIN `glpi_items_tickets`\n ON (`glpi_tickets`.`id` = `glpi_items_tickets`.`tickets_id`)"; } $LEFTJOIN .= " INNER JOIN `glpi_computers`\n ON (`glpi_computers`.`id` = `{$linkedtable}`.`items_id`\n AND `{$linkedtable}`.`itemtype` = 'Computer')"; $WHERE .= " AND `glpi_computers`.`{$champ}` = '{$value}'\n AND `glpi_computers`.`is_template` <> '1'"; break; } switch ($type) { case "inter_total": $WHERE .= " AND " . getDateRequest("`{$table}`.`date`", $begin, $end); $query = "SELECT FROM_UNIXTIME(UNIX_TIMESTAMP(`{$table}`.`date`),'%Y-%m')\n AS date_unix,\n COUNT(`{$table}`.`id`) AS total_visites\n FROM `{$table}`\n {$LEFTJOIN}\n {$WHERE}\n GROUP BY date_unix\n ORDER BY `{$table}`.`date`"; break; case "inter_solved": $WHERE .= " AND `{$table}`.`status` IN ('" . implode("','", $solved_status) . "')\n AND `{$table}`.`solvedate` IS NOT NULL\n AND " . getDateRequest("`{$table}`.`solvedate`", $begin, $end); $query = "SELECT FROM_UNIXTIME(UNIX_TIMESTAMP(`{$table}`.`solvedate`),'%Y-%m')\n AS date_unix,\n COUNT(`{$table}`.`id`) AS total_visites\n FROM `{$table}`\n {$LEFTJOIN}\n {$WHERE}\n GROUP BY date_unix\n ORDER BY `{$table}`.`solvedate`"; break; case "inter_solved_late": $WHERE .= " AND `{$table}`.`status` IN ('" . implode("','", $solved_status) . "')\n AND `{$table}`.`solvedate` IS NOT NULL\n AND `{$table}`.`due_date` IS NOT NULL\n AND " . getDateRequest("`{$table}`.`solvedate`", $begin, $end) . "\n AND `{$table}`.`solvedate` > `{$table}`.`due_date`"; $query = "SELECT FROM_UNIXTIME(UNIX_TIMESTAMP(`{$table}`.`solvedate`),'%Y-%m')\n AS date_unix,\n COUNT(`{$table}`.`id`) AS total_visites\n FROM `{$table}`\n {$LEFTJOIN}\n {$WHERE}\n GROUP BY date_unix\n ORDER BY `{$table}`.`solvedate`"; break; case "inter_closed": $WHERE .= " AND `{$table}`.`status` IN ('" . implode("','", $closed_status) . "')\n AND `{$table}`.`closedate` IS NOT NULL\n AND " . getDateRequest("`{$table}`.`closedate`", $begin, $end); $query = "SELECT FROM_UNIXTIME(UNIX_TIMESTAMP(`{$table}`.`closedate`),'%Y-%m')\n AS date_unix,\n COUNT(`{$table}`.`id`) AS total_visites\n FROM `{$table}`\n {$LEFTJOIN}\n {$WHERE}\n GROUP BY date_unix\n ORDER BY `{$table}`.`closedate`"; break; case "inter_avgsolvedtime": $WHERE .= " AND `{$table}`.`status` IN ('" . implode("','", $solved_status) . "')\n AND `{$table}`.`solvedate` IS NOT NULL\n AND " . getDateRequest("`{$table}`.`solvedate`", $begin, $end); $query = "SELECT FROM_UNIXTIME(UNIX_TIMESTAMP(`{$table}`.`solvedate`),'%Y-%m')\n AS date_unix,\n AVG(solve_delay_stat) AS total_visites\n FROM `{$table}`\n {$LEFTJOIN}\n {$WHERE}\n GROUP BY date_unix\n ORDER BY `{$table}`.`solvedate`"; break; case "inter_avgclosedtime": $WHERE .= " AND `{$table}`.`status` IN ('" . implode("','", $closed_status) . "')\n AND `{$table}`.`closedate` IS NOT NULL\n AND " . getDateRequest("`{$table}`.`closedate`", $begin, $end); $query = "SELECT FROM_UNIXTIME(UNIX_TIMESTAMP(`{$table}`.`closedate`),'%Y-%m')\n AS date_unix,\n AVG(close_delay_stat) AS total_visites\n FROM `{$table}`\n {$LEFTJOIN}\n {$WHERE}\n GROUP BY date_unix\n ORDER BY `{$table}`.`closedate`"; break; case "inter_avgactiontime": if ($param == "technicien_followup") { $actiontime_table = $tasktable; } else { $actiontime_table = $table; } $WHERE .= " AND `{$actiontime_table}`.`actiontime` > '0'\n AND " . getDateRequest("`{$table}`.`solvedate`", $begin, $end); $query = "SELECT FROM_UNIXTIME(UNIX_TIMESTAMP(`{$table}`.`solvedate`),'%Y-%m')\n AS date_unix,\n AVG(`{$actiontime_table}`.`actiontime`) AS total_visites\n FROM `{$table}`\n {$LEFTJOIN}\n {$WHERE}\n GROUP BY date_unix\n ORDER BY `{$table}`.`solvedate`"; break; case "inter_avgtakeaccount": $WHERE .= " AND `{$table}`.`status` IN ('" . implode("','", $solved_status) . "')\n AND `{$table}`.`solvedate` IS NOT NULL\n AND " . getDateRequest("`{$table}`.`solvedate`", $begin, $end); $query = "SELECT `{$table}`.`id`,\n FROM_UNIXTIME(UNIX_TIMESTAMP(`{$table}`.`solvedate`),'%Y-%m')\n AS date_unix,\n AVG(`{$table}`.`takeintoaccount_delay_stat`) AS total_visites\n FROM `{$table}`\n {$LEFTJOIN}\n {$WHERE}\n GROUP BY date_unix\n ORDER BY `{$table}`.`solvedate`"; break; case "inter_opensatisfaction": $WHERE .= " AND `{$table}`.`status` IN ('" . implode("','", $closed_status) . "')\n AND `{$table}`.`closedate` IS NOT NULL\n AND " . getDateRequest("`{$table}`.`closedate`", $begin, $end); $query = "SELECT FROM_UNIXTIME(UNIX_TIMESTAMP(`{$table}`.`closedate`),'%Y-%m')\n AS date_unix,\n COUNT(`{$table}`.`id`) AS total_visites\n FROM `{$table}`\n INNER JOIN `glpi_ticketsatisfactions`\n ON (`{$table}`.`id` = `glpi_ticketsatisfactions`.`tickets_id`)\n {$LEFTJOIN}\n {$WHERE}\n GROUP BY date_unix\n ORDER BY `{$table}`.`closedate`"; break; case "inter_answersatisfaction": $WHERE .= " AND `{$table}`.`status` IN ('" . implode("','", $closed_status) . "')\n AND `{$table}`.`closedate` IS NOT NULL\n AND `glpi_ticketsatisfactions`.`date_answered` IS NOT NULL\n AND " . getDateRequest("`{$table}`.`closedate`", $begin, $end); $query = "SELECT FROM_UNIXTIME(UNIX_TIMESTAMP(`{$table}`.`closedate`),'%Y-%m')\n AS date_unix,\n COUNT(`{$table}`.`id`) AS total_visites\n FROM `{$table}`\n INNER JOIN `glpi_ticketsatisfactions`\n ON (`{$table}`.`id` = `glpi_ticketsatisfactions`.`tickets_id`)\n {$LEFTJOIN}\n {$WHERE}\n GROUP BY date_unix\n ORDER BY `{$table}`.`closedate`"; break; case "inter_avgsatisfaction": $WHERE .= " AND `glpi_ticketsatisfactions`.`date_answered` IS NOT NULL\n AND `{$table}`.`status` IN ('" . implode("','", $closed_status) . "')\n AND `{$table}`.`closedate` IS NOT NULL\n AND " . getDateRequest("`{$table}`.`closedate`", $begin, $end); $query = "SELECT FROM_UNIXTIME(UNIX_TIMESTAMP(`{$table}`.`closedate`),'%Y-%m')\n AS date_unix,\n AVG(`glpi_ticketsatisfactions`.`satisfaction`) AS total_visites\n FROM `{$table}`\n INNER JOIN `glpi_ticketsatisfactions`\n ON (`{$table}`.`id` = `glpi_ticketsatisfactions`.`tickets_id`)\n {$LEFTJOIN}\n {$WHERE}\n GROUP BY date_unix\n ORDER BY `{$table}`.`closedate`"; break; } $entrees = array(); $count = array(); if (empty($query)) { return array(); } $result = $DB->query($query); if ($result && $DB->numrows($result) > 0) { while ($row = $DB->fetch_assoc($result)) { $date = $row['date_unix']; //$visites = round($row['total_visites']); $entrees["{$date}"] = $row['total_visites']; } } // Remplissage de $entrees pour les mois ou il n'y a rien // $min=-1; // $max=0; // if (count($entrees)==0) { // return $entrees; // } // foreach ($entrees as $key => $val) { // $time=strtotime($key."-01"); // if ($min>$time || $min<0) { // $min=$time; // } // if ($max<$time) { // $max=$time; // } // } $end_time = strtotime(date("Y-m", strtotime($end)) . "-01"); $begin_time = strtotime(date("Y-m", strtotime($begin)) . "-01"); // if ($max<$end_time) { // $max=$end_time; // } // if ($min>$begin_time) { // $min=$begin_time; // } $current = $begin_time; while ($current <= $end_time) { $curentry = date("Y-m", $current); if (!isset($entrees["{$curentry}"])) { $entrees["{$curentry}"] = 0; } $month = date("m", $current); $year = date("Y", $current); $current = mktime(0, 0, 0, intval($month) + 1, 1, intval($year)); } ksort($entrees); return $entrees; }
function generateContactsCfg($file=0, $tag='') { global $DB; $pmEntity = new PluginMonitoringEntity(); $calendar = new Calendar(); PluginMonitoringToolbox::logIfExtradebug( 'pm-shinken', "Starting generateContactsCfg ($tag) ...\n" ); $a_users_used = array(); $a_contacts = array(); // Add default contact 'monitoring' for fake hosts // $a_calendars = current($calendar->find("", "", 1)); // $cal = '24x7'; // if (isset($a_calendars['name'])) { // $cal = $a_calendars['name']; // } // $a_contacts[-1] = array( // 'contact_name' => 'monitoring', // 'alias' => 'monitoring', // 'host_notifications_enabled' => '0', // 'service_notifications_enabled' => '0', // 'service_notification_period' => $cal, // 'host_notification_period' => $cal, // 'service_notification_options' => '', // 'host_notification_options' => '', // 'service_notification_commands' => '', // 'host_notification_commands' => '', // 'email' => '', // 'pager' => '', // ); $a_entities_allowed = $pmEntity->getEntitiesByTag($tag); $a_entities_list = array(); foreach ($a_entities_allowed as $entity) { $a_entities_list = getSonsOf("glpi_entities", $entity); } // Always add root entity $a_entities_list[] = '0'; $where = ''; if (! isset($a_entities_allowed['-1'])) { $where = getEntitiesRestrictRequest("WHERE", "glpi_plugin_monitoring_contacts_items", '', $a_entities_list); } $i=0; $query = "SELECT * FROM `glpi_plugin_monitoring_contacts_items` $where"; // Toolbox::logInFile("pm-shinken", "- Contacts query: $query\n"); $result = $DB->query($query); while ($data=$DB->fetch_array($result)) { if ($data['users_id'] > 0) { if ((!isset($a_users_used[$data['users_id']]))) { $a_contacts = $this->_addContactUser($a_contacts, $data['users_id'], $i); $i++; $a_users_used[$data['users_id']] = 1; } } else if ($data['groups_id'] > 0) { $queryg = "SELECT * FROM `glpi_groups_users` WHERE `groups_id`='".$data['groups_id']."'"; $resultg = $DB->query($queryg); while ($datag=$DB->fetch_array($resultg)) { if ((!isset($a_users_used[$datag['users_id']]))) { $a_contacts = $this->_addContactUser($a_contacts, $datag['users_id'], $i); $i++; $a_users_used[$datag['users_id']] = 1; } } } } // Add user monitoring $user = new User(); $a_monit_user = current($user->find("`name`='monitoring'", '', 1)); if ((!isset($a_users_used[$a_monit_user['id']]))) { $a_contacts = $this->_addContactUser($a_contacts, $a_monit_user['id'], $i); } PluginMonitoringToolbox::logIfExtradebug( 'pm-shinken', "End generateContactsCfg\n" ); if ($file == "1") { $config = "# Generated by plugin monitoring for GLPI\n# on ".date("Y-m-d H:i:s")."\n\n"; foreach ($a_contacts as $data) { $config .= $this->writeFile("contact", $data); } return array('contacts.cfg', $config); } else { return $a_contacts; } }
/** * 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']); }
/** * Display tickets for an item * * Will also display tickets of linked items * * @param $item CommonDBTM object * * @return nothing (display a table) **/ static function showListForItem(CommonDBTM $item) { global $DB, $CFG_GLPI; if (!Session::haveRightsOr(self::$rightname, array(self::READALL, self::READMY, self::READASSIGN, CREATE))) { return false; } if ($item->isNewID($item->getID())) { return false; } $restrict = ''; $order = ''; $options['reset'] = 'reset'; switch ($item->getType()) { case 'User': $restrict = "(`glpi_tickets_users`.`users_id` = '" . $item->getID() . "' " . " AND `glpi_tickets_users`.`type` = " . CommonITILActor::REQUESTER . ")"; $order = '`glpi_tickets`.`date_mod` DESC'; $options['reset'] = 'reset'; $options['criteria'][0]['field'] = 4; // status $options['criteria'][0]['searchtype'] = 'equals'; $options['criteria'][0]['value'] = $item->getID(); $options['criteria'][0]['link'] = 'AND'; break; case 'SLT': $restrict = "`slts_tto_id` = '" . $item->getID() . "'\n OR `slts_ttr_id` = '" . $item->getID() . "'"; $order = '`glpi_tickets`.`due_date` DESC'; $options['criteria'][0]['field'] = 30; $options['criteria'][0]['searchtype'] = 'equals'; $options['criteria'][0]['value'] = $item->getID(); $options['criteria'][0]['link'] = 'AND'; break; case 'Supplier': $restrict = "(`glpi_suppliers_tickets`.`suppliers_id` = '" . $item->getID() . "' " . " AND `glpi_suppliers_tickets`.`type` = " . CommonITILActor::ASSIGN . ")"; $order = '`glpi_tickets`.`date_mod` DESC'; $options['criteria'][0]['field'] = 6; $options['criteria'][0]['searchtype'] = 'equals'; $options['criteria'][0]['value'] = $item->getID(); $options['criteria'][0]['link'] = 'AND'; break; case 'Group': // Mini search engine if ($item->haveChildren()) { $tree = Session::getSavedOption(__CLASS__, 'tree', 0); echo "<table class='tab_cadre_fixe'>"; echo "<tr class='tab_bg_1'><th>" . __('Last tickets') . "</th></tr>"; echo "<tr class='tab_bg_1'><td class='center'>"; echo __('Child groups') . " "; Dropdown::showYesNo('tree', $tree, -1, array('on_change' => 'reloadTab("start=0&tree="+this.value)')); } else { $tree = 0; } echo "</td></tr></table>"; if ($tree) { $restrict = "IN (" . implode(',', getSonsOf('glpi_groups', $item->getID())) . ")"; } else { $restrict = "='" . $item->getID() . "'"; } $restrict = "(`glpi_groups_tickets`.`groups_id` {$restrict}" . " AND `glpi_groups_tickets`.`type` = " . CommonITILActor::REQUESTER . ")"; $order = '`glpi_tickets`.`date_mod` DESC'; $options['criteria'][0]['field'] = 71; $options['criteria'][0]['searchtype'] = $tree ? 'under' : 'equals'; $options['criteria'][0]['value'] = $item->getID(); $options['criteria'][0]['link'] = 'AND'; break; default: $restrict = "(`glpi_items_tickets`.`items_id` = '" . $item->getID() . "' " . " AND `glpi_items_tickets`.`itemtype` = '" . $item->getType() . "')"; // you can only see your tickets if (!Session::haveRight(self::$rightname, self::READALL)) { $restrict .= " AND (`glpi_tickets`.`users_id_recipient` = '" . Session::getLoginUserID() . "'\n OR (`glpi_tickets_users`.`tickets_id` = '" . $item->getID() . "'\n AND `glpi_tickets_users`.`users_id`\n = '" . Session::getLoginUserID() . "'))"; } $order = '`glpi_tickets`.`date_mod` DESC'; $options['criteria'][0]['field'] = 12; $options['criteria'][0]['searchtype'] = 'equals'; $options['criteria'][0]['value'] = 'all'; $options['criteria'][0]['link'] = 'AND'; $options['metacriteria'][0]['itemtype'] = $item->getType(); $options['metacriteria'][0]['field'] = Search::getOptionNumber($item->getType(), 'id'); $options['metacriteria'][0]['searchtype'] = 'equals'; $options['metacriteria'][0]['value'] = $item->getID(); $options['metacriteria'][0]['link'] = 'AND'; break; } $query = "SELECT " . self::getCommonSelect() . "\n FROM `glpi_tickets` " . self::getCommonLeftJoin() . "\n WHERE {$restrict} " . getEntitiesRestrictRequest("AND", "glpi_tickets") . "\n ORDER BY {$order}\n LIMIT " . intval($_SESSION['glpilist_limit']); $result = $DB->query($query); $number = $DB->numrows($result); $colspan = 11; if (count($_SESSION["glpiactiveentities"]) > 1) { $colspan++; } // Ticket for the item echo "<div class='firstbloc'>"; // Link to open a new ticket if ($item->getID() && Ticket::isPossibleToAssignType($item->getType()) && self::canCreate()) { Html::showSimpleForm($CFG_GLPI["root_doc"] . "/front/ticket.form.php", '_add_fromitem', __('New ticket for this item...'), array('itemtype' => $item->getType(), 'items_id' => $item->getID())); } echo "</div><div>"; if ($number > 0) { echo "<table class='tab_cadre_fixehov'>"; if (Session::haveRight(self::$rightname, self::READALL)) { Session::initNavigateListItems('Ticket', sprintf(__('%1$s = %2$s'), $item->getTypeName(1), $item->getName())); echo "<tr class='noHover'><th colspan='{$colspan}'>"; $title = sprintf(_n('Last %d ticket', 'Last %d tickets', $number), $number); $link = "<a href='" . $CFG_GLPI["root_doc"] . "/front/ticket.php?" . Toolbox::append_params($options, '&') . "'>" . __('Show all') . "</a>"; $title = printf(__('%1$s (%2$s)'), $title, $link); echo "</th></tr>"; } else { echo "<tr><th colspan='{$colspan}'>" . __("You don't have right to see all tickets") . "</th></tr>"; } } else { echo "<table class='tab_cadre_fixe'>"; echo "<tr><th>" . __('No ticket found.') . "</th></tr>"; } if ($item->getID() && $item->getType() == 'User' && self::canCreate()) { echo "<tr><td class='tab_bg_2 center b' colspan='{$colspan}'>"; Html::showSimpleForm($CFG_GLPI["root_doc"] . "/front/ticket.form.php", '_add_fromitem', __('New ticket for this item...'), array('_users_id_requester' => $item->getID())); echo "</td></tr>"; } // Ticket list if ($number > 0) { self::commonListHeader(Search::HTML_OUTPUT); while ($data = $DB->fetch_assoc($result)) { Session::addToNavigateListItems('Ticket', $data["id"]); self::showShort($data["id"]); } self::commonListHeader(Search::HTML_OUTPUT); } echo "</table></div>"; // Tickets for linked items $linkeditems = $item->getLinkedItems(); $restrict = array(); if (count($linkeditems)) { foreach ($linkeditems as $ltype => $tab) { foreach ($tab as $lID) { $restrict[] = "(`glpi_items_tickets`.`itemtype` = '{$ltype}' AND `glpi_items_tickets`.`items_id` = '{$lID}')"; } } } if (count($restrict) && Session::haveRight(self::$rightname, self::READALL)) { $query = "SELECT " . self::getCommonSelect() . "\n FROM `glpi_tickets` " . self::getCommonLeftJoin() . "\n WHERE " . implode(' OR ', $restrict) . getEntitiesRestrictRequest(' AND ', 'glpi_tickets') . "\n ORDER BY `glpi_tickets`.`date_mod` DESC\n LIMIT " . intval($_SESSION['glpilist_limit']); $result = $DB->query($query); $number = $DB->numrows($result); echo "<div class='spaced'><table class='tab_cadre_fixe'>"; echo "<tr><th colspan='12'>"; echo _n('Ticket on linked items', 'Tickets on linked items', $number); echo "</th></tr>"; if ($number > 0) { self::commonListHeader(Search::HTML_OUTPUT); while ($data = $DB->fetch_assoc($result)) { // Session::addToNavigateListItems(TRACKING_TYPE,$data["id"]); self::showShort($data["id"]); } self::commonListHeader(Search::HTML_OUTPUT); } else { echo "<tr><th>" . __('No ticket found.') . "</th></tr>"; } echo "</table></div>"; } // Subquery for linked item }
/** * Show softwares candidates to be merged with the current * * @return nothing **/ function showMergeCandidates() { global $DB, $CFG_GLPI; $ID = $this->getField('id'); $this->check($ID, "w"); $rand = mt_rand(); echo "<div class='center'>"; $sql = "SELECT `glpi_softwares`.`id`,\n `glpi_softwares`.`name`,\n `glpi_entities`.`completename` AS entity\n FROM `glpi_softwares`\n LEFT JOIN `glpi_entities` ON (`glpi_softwares`.`entities_id` = `glpi_entities`.`id`)\n WHERE (`glpi_softwares`.`id` != '{$ID}'\n AND `glpi_softwares`.`name` = '" . addslashes($this->fields["name"]) . "'\n AND `glpi_softwares`.`is_deleted` = '0'\n AND `glpi_softwares`.`is_template` = '0' " . getEntitiesRestrictRequest('AND', 'glpi_softwares', 'entities_id', getSonsOf("glpi_entities", $this->fields["entities_id"]), false) . ")\n ORDER BY `entity`"; $req = $DB->request($sql); if ($nb = $req->numrows()) { $link = Toolbox::getItemTypeFormURL('Software'); Html::openMassiveActionsForm('mass' . __CLASS__ . $rand); $paramsma = array('num_displayed' => $nb, 'specific_actions' => array('mergesoftware' => __('Merge'))); Html::showMassiveActions(__CLASS__, $paramsma); echo "<table class='tab_cadre_fixehov'>"; echo "<tr><th width='10'>"; echo Html::checkAllAsCheckbox('mass' . __CLASS__ . $rand); echo "</th>"; echo "<th>" . __('Name') . "</th>"; echo "<th>" . __('Entity') . "</th>"; echo "<th>" . _n('Installation', 'Installations', 2) . "</th>"; echo "<th>" . _n('License', 'Licenses', 2) . "</th></tr>"; foreach ($req as $data) { echo "<tr class='tab_bg_2'>"; echo "<td>" . Html::getMassiveActionCheckBox(__CLASS__, $data["id"]) . "</td>"; echo "<td><a href='" . $link . "?id=" . $data["id"] . "'>" . $data["name"] . "</a></td>"; echo "<td>" . $data["entity"] . "</td>"; echo "<td class='right'>" . Computer_SoftwareVersion::countForSoftware($data["id"]) . "</td>"; echo "<td class='right'>" . SoftwareLicense::countForSoftware($data["id"]) . "</td></tr>\n"; } echo "</table>\n"; echo "<input type='hidden' name='id' value='{$ID}'>"; $paramsma['ontop'] = false; Html::showMassiveActions(__CLASS__, $paramsma); Html::closeForm(); } else { _e('No item found'); } echo "</div>"; }
/** * Is the login user have access to reminder based on visibility configuration * * @return boolean **/ function haveVisibilityAccess() { // No public reminder right : no visibility check if (!Session::haveRight('reminder_public', 'r')) { return false; } // Author if ($this->fields['users_id'] == Session::getLoginUserID()) { return true; } // Users if (isset($this->users[Session::getLoginUserID()])) { return true; } // Groups if (count($this->groups) && isset($_SESSION["glpigroups"]) && count($_SESSION["glpigroups"])) { foreach ($this->groups as $key => $data) { foreach ($data as $group) { if (in_array($group['groups_id'], $_SESSION["glpigroups"])) { // All the group if ($group['entities_id'] < 0) { return true; } // Restrict to entities $entities = array($group['entities_id']); if ($group['is_recursive']) { $entities = getSonsOf('glpi_entities', $group['entities_id']); } if (Session::haveAccessToOneOfEntities($entities, true)) { return true; } } } } } // Entities if (count($this->entities) && isset($_SESSION["glpiactiveentities"]) && count($_SESSION["glpiactiveentities"])) { foreach ($this->entities as $key => $data) { foreach ($data as $entity) { $entities = array($entity['entities_id']); if ($entity['is_recursive']) { $entities = getSonsOf('glpi_entities', $entity['entities_id']); } if (Session::haveAccessToOneOfEntities($entities, true)) { return true; } } } } // Profiles if (count($this->profiles) && isset($_SESSION["glpiactiveprofile"]) && isset($_SESSION["glpiactiveprofile"]['id'])) { if (isset($this->profiles[$_SESSION["glpiactiveprofile"]['id']])) { foreach ($this->profiles[$_SESSION["glpiactiveprofile"]['id']] as $profile) { // All the profile if ($profile['entities_id'] < 0) { return true; } // Restrict to entities $entities = array($profile['entities_id']); if ($profile['is_recursive']) { $entities = getSonsOf('glpi_entities', $profile['entities_id']); } if (Session::haveAccessToOneOfEntities($entities, true)) { return true; } } } } return false; }
/** * Retrieve list of member of a Group * * @since version 0.83 * * @param $group Group object * @param $members Array filled on output of member (filtered) * @param $ids Array of ids (not filtered) * @param $crit String filter (is_manager, is_userdelegate) (default '') * @param $tree Boolean true to include member of sub-group (default 0) * * @return String tab of entity for restriction **/ static function getDataForGroup(Group $group, &$members, &$ids, $crit = '', $tree = 0) { global $DB; // Entity restriction for this group, according to user allowed entities if ($group->fields['is_recursive']) { $entityrestrict = getSonsOf('glpi_entities', $group->fields['entities_id']); // active entity could be a child of object entity if ($_SESSION['glpiactive_entity'] != $group->fields['entities_id'] && in_array($_SESSION['glpiactive_entity'], $entityrestrict)) { $entityrestrict = getSonsOf('glpi_entities', $_SESSION['glpiactive_entity']); } } else { $entityrestrict = $group->fields['entities_id']; } if ($tree) { $restrict = "IN (" . implode(',', getSonsOf('glpi_groups', $group->getID())) . ")"; } else { $restrict = "='" . $group->getID() . "'"; } // All group members $query = "SELECT DISTINCT `glpi_users`.`id`,\n `glpi_groups_users`.`id` AS linkID,\n `glpi_groups_users`.`groups_id`,\n `glpi_groups_users`.`is_dynamic` AS is_dynamic,\n `glpi_groups_users`.`is_manager` AS is_manager,\n `glpi_groups_users`.`is_userdelegate` AS is_userdelegate\n FROM `glpi_groups_users`\n INNER JOIN `glpi_users`\n ON (`glpi_users`.`id` = `glpi_groups_users`.`users_id`)\n INNER JOIN `glpi_profiles_users`\n ON (`glpi_profiles_users`.`users_id`=`glpi_users`.`id`)\n WHERE `glpi_groups_users`.`groups_id` {$restrict} " . getEntitiesRestrictRequest('AND', 'glpi_profiles_users', '', $entityrestrict, 1) . "\n ORDER BY `glpi_users`.`realname`,\n `glpi_users`.`firstname`,\n `glpi_users`.`name`"; $result = $DB->query($query); if ($DB->numrows($result) > 0) { while ($data = $DB->fetch_assoc($result)) { // Add to display list, according to criterion if (empty($crit) || $data[$crit]) { $members[] = $data; } // Add to member list (member of sub-group are not member) if ($data['groups_id'] == $group->getID()) { $ids[] = $data['id']; } } } return $entityrestrict; }
/** * Make a select box for connected port * * @param $ID ID of the current port to connect * @param $options array of possible options: * - name : string / name of the select (default is networkports_id) * - comments : boolean / is the comments displayed near the dropdown (default true) * - entity : integer or array / restrict to a defined entity or array of entities * (default -1 : no restriction) * - entity_sons : boolean / if entity restrict specified auto select its sons * only available if entity is a single value not an array (default false) * * @return nothing (print out an HTML select box) **/ static function dropdownConnect($ID, $options = array()) { global $CFG_GLPI; $p['name'] = 'networkports_id'; $p['comments'] = 1; $p['entity'] = -1; $p['entity_sons'] = false; if (is_array($options) && count($options)) { foreach ($options as $key => $val) { $p[$key] = $val; } } // Manage entity_sons if (!($p['entity'] < 0) && $p['entity_sons']) { if (is_array($p['entity'])) { echo "entity_sons options is not available with entity option as array"; } else { $p['entity'] = getSonsOf('glpi_entities', $p['entity']); } } echo "<input type='hidden' name='NetworkPortConnect_networkports_id_1'value='{$ID}'>"; $rand = Dropdown::showItemTypes('NetworkPortConnect_itemtype', $CFG_GLPI["networkport_types"]); $params = array('itemtype' => '__VALUE__', 'entity_restrict' => $p['entity'], 'networkports_id' => $ID, 'comments' => $p['comments'], 'myname' => $p['name'], 'instantiation_type' => get_called_class()); Ajax::updateItemOnSelectEvent("dropdown_NetworkPortConnect_itemtype{$rand}", "show_" . $p['name'] . "{$rand}", $CFG_GLPI["root_doc"] . "/ajax/dropdownConnectNetworkPortDeviceType.php", $params); echo "<span id='show_" . $p['name'] . "{$rand}'> </span>\n"; return $rand; }
/** * Get SQL code associated with the criteria * * @see plugins/reports/inc/PluginReportsAutoCriteria::getSqlCriteriasRestriction() **/ public function getSqlCriteriasRestriction($link = 'AND') { if ($this->getParameterValue() || $this->searchzero) { if (!$this->childrens) { return $link . " " . $this->getSqlField() . "='" . $this->getParameterValue() . "' "; } if ($this->getParameterValue()) { return $link . " " . $this->getSqlField() . " IN (" . implode(',', getSonsOf($this->getTable(), $this->getParameterValue())) . ") "; } // 0 + its child means ALL } // Zero => means ALL => no criteria return ''; }
/** * Try to match a definied rule * * @param &$criterion RuleCriteria object * @param $field the field to match * @param &$criterias_results * @param &$regex_result * * @return true if the field match the rule, false if it doesn't match **/ static function match(RuleCriteria &$criterion, $field, &$criterias_results, &$regex_result) { $condition = $criterion->fields['condition']; $pattern = $criterion->fields['pattern']; $criteria = $criterion->fields['criteria']; //If pattern is wildcard, don't check the rule and return true //or if the condition is "already present in GLPI" : will be processed later if ($pattern == Rule::RULE_WILDCARD || $condition == Rule::PATTERN_FIND) { return true; } $pattern = trim($pattern); switch ($condition) { case Rule::PATTERN_EXISTS: return !empty($field); case Rule::PATTERN_DOES_NOT_EXISTS: return empty($field); case Rule::PATTERN_IS: if (is_array($field)) { // Special case (used only by UNIQUE_PROFILE, for now) // $pattern is an ID if (in_array($pattern, $field)) { $criterias_results[$criteria] = $pattern; return true; } } else { //Perform comparison with fields in lower case $field = Toolbox::strtolower($field); $pattern = Toolbox::strtolower($pattern); if ($field == $pattern) { $criterias_results[$criteria] = $pattern; return true; } } return false; case Rule::PATTERN_IS_NOT: //Perform comparison with fields in lower case $field = Toolbox::strtolower($field); $pattern = Toolbox::strtolower($pattern); if ($field != $pattern) { $criterias_results[$criteria] = $pattern; return true; } return false; case Rule::PATTERN_UNDER: $table = getTableNameForForeignKeyField($criteria); $values = getSonsOf($table, $pattern); if (isset($values[$field])) { return true; } return false; case Rule::PATTERN_NOT_UNDER: $table = getTableNameForForeignKeyField($criteria); $values = getSonsOf($table, $pattern); if (isset($values[$field])) { return false; } return true; case Rule::PATTERN_END: $value = "/" . $pattern . "\$/i"; if (preg_match($value, $field) > 0) { $criterias_results[$criteria] = $pattern; return true; } return false; case Rule::PATTERN_BEGIN: if (empty($pattern)) { return false; } $value = mb_stripos($field, $pattern, 0, 'UTF-8'); if ($value !== false && $value == 0) { $criterias_results[$criteria] = $pattern; return true; } return false; case Rule::PATTERN_CONTAIN: if (empty($pattern)) { return false; } $value = mb_stripos($field, $pattern, 0, 'UTF-8'); if ($value !== false && $value >= 0) { $criterias_results[$criteria] = $pattern; return true; } return false; case Rule::PATTERN_NOT_CONTAIN: if (empty($pattern)) { return false; } $value = mb_stripos($field, $pattern, 0, 'UTF-8'); if ($value === false) { $criterias_results[$criteria] = $pattern; return true; } return false; case Rule::REGEX_MATCH: $results = array(); // Permit use < and > $pattern = Toolbox::unclean_cross_side_scripting_deep($pattern); if (preg_match_all($pattern . "i", $field, $results) > 0) { // Drop $result[0] : complete match result array_shift($results); // And add to $regex_result array $regex_result[] = $results[1]; $criterias_results[$criteria] = $pattern; return true; } return false; case Rule::REGEX_NOT_MATCH: // Permit use < and > $pattern = Toolbox::unclean_cross_side_scripting_deep($pattern); if (preg_match($pattern . "i", $field) == 0) { $criterias_results[$criteria] = $pattern; return true; } return false; case Rule::PATTERN_FIND: case Rule::PATTERN_IS_EMPTY: // Global criteria will be evaluated later return true; } return false; }
/** * Print a select with contracts * * Print a select named $name with contracts options and selected value $value * @param $options array of possible options: * - name : string / name of the select (default is contracts_id) * - value : integer / preselected value (default 0) * - entity : integer or array / restrict to a defined entity or array of entities * (default -1 : no restriction) * - rand : (defauolt mt_rand) * - entity_sons : boolean / if entity restrict specified auto select its sons * only available if entity is a single value not an array (default false) * - used : array / Already used items ID: not to display in dropdown (default empty) * - nochecklimit : boolean / disable limit for nomber of device (for supplier, default false) * - on_change : string / value to transmit to "onChange" * - display : boolean / display or return string (deault true) * * @return Nothing (display) **/ static function dropdown($options = array()) { global $DB; //$name,$entity_restrict=-1,$alreadyused=array(),$nochecklimit=false $p['name'] = 'contracts_id'; $p['value'] = ''; $p['entity'] = ''; $p['rand'] = mt_rand(); $p['entity_sons'] = false; $p['used'] = array(); $p['nochecklimit'] = false; $p['on_change'] = ''; $p['display'] = true; if (is_array($options) && count($options)) { foreach ($options as $key => $val) { $p[$key] = $val; } } if (!($p['entity'] < 0) && $p['entity_sons']) { if (is_array($p['entity'])) { // no translation needed (only for dev) echo "entity_sons options is not available with array of entity"; } else { $p['entity'] = getSonsOf('glpi_entities', $p['entity']); } } $entrest = ""; $idrest = ""; if ($p['entity'] >= 0) { $entrest = getEntitiesRestrictRequest("AND", "glpi_contracts", "entities_id", $p['entity'], true); } if (count($p['used'])) { $idrest = " AND `glpi_contracts`.`id` NOT IN (" . implode(",", $p['used']) . ") "; } $query = "SELECT `glpi_contracts`.*\n FROM `glpi_contracts`\n LEFT JOIN `glpi_entities` ON (`glpi_contracts`.`entities_id` = `glpi_entities`.`id`)\n WHERE `glpi_contracts`.`is_deleted` = '0' {$entrest} {$idrest}\n ORDER BY `glpi_entities`.`completename`,\n `glpi_contracts`.`name` ASC,\n `glpi_contracts`.`begin_date` DESC"; $result = $DB->query($query); $values = array(0 => Dropdown::EMPTY_VALUE); $group = ''; $prev = -1; while ($data = $DB->fetch_assoc($result)) { if ($p['nochecklimit'] || $data["max_links_allowed"] == 0 || $data["max_links_allowed"] > countElementsInTable("glpi_contracts_items", "contracts_id\n = '" . $data['id'] . "'")) { if ($data["entities_id"] != $prev) { $group = Dropdown::getDropdownName("glpi_entities", $data["entities_id"]); $prev = $data["entities_id"]; } $name = $data["name"]; if ($_SESSION["glpiis_ids_visible"] || empty($data["name"])) { $name = sprintf(__('%1$s (%2$s)'), $name, $data["id"]); } $tmp = sprintf(__('%1$s - %2$s'), $name, $data["num"]); $tmp = sprintf(__('%1$s - %2$s'), $tmp, Html::convDateTime($data["begin_date"])); $values[$group][$data['id']] = $tmp; } } return Dropdown::showFromArray($p['name'], $values, array('value' => $p['value'], 'on_change' => $p['on_change'], 'display' => $p['display'])); }
function addItem($displayviews_id) { global $DB, $CFG_GLPI; $this->getEmpty(); $pmDisplayview = new PluginMonitoringDisplayview(); $pmDisplayview->getFromDB($displayviews_id); // Manage entity_sons $a_entities = array(); if (!($pmDisplayview->fields['entities_id'] < 0)) { if ($pmDisplayview->fields['is_recursive'] == '0') { $a_entities[$pmDisplayview->fields['entities_id']] = $pmDisplayview->fields['entities_id']; } else { $a_entities = getSonsOf('glpi_entities', $pmDisplayview->fields['entities_id']); } } $options = array(); $this->showFormHeader($options); echo "<tr class='tab_bg_1'>"; echo "<td>"; echo "<input type='hidden' name='plugin_monitoring_displayviews_id' value='" . $displayviews_id . "' />"; echo __('Element to display', 'monitoring') . " :</td>"; echo "<td>"; $elements = array(); $elements['NULL'] = Dropdown::EMPTY_VALUE; $elements['PluginMonitoringDisplayview'] = __('Views', 'monitoring'); $elements['PluginMonitoringServicescatalog'] = __('Business rules', 'monitoring'); // $elements['service'] = __('Resources (info)', 'monitoring'); $elements['host'] = __('Host (info)', 'monitoring'); $elements['PluginMonitoringService'] = __('Resources (graph)', 'monitoring'); $elements['PluginMonitoringComponentscatalog'] = __('Components catalog', 'monitoring'); $elements['PluginMonitoringWeathermap'] = __('Weathermap', 'monitoring'); $rand = Dropdown::showFromArray('itemtype', $elements, array('value' => $this->fields['itemtype'])); $params = array('itemtype' => '__VALUE__', 'displayviews_id' => $displayviews_id, 'myname' => "items_id", 'a_entities' => $a_entities); Ajax::updateItemOnSelectEvent("dropdown_itemtype" . $rand, "items_id", $CFG_GLPI["root_doc"] . "/plugins/monitoring/ajax/dropdownDisplayviewItemtype.php", $params); echo "<span id='items_id'></span>"; echo "<input type='hidden' name='x' value='1' />"; echo "<input type='hidden' name='y' value='1' />"; echo "</td>"; echo "<td colspan='2'></td>"; echo "</tr>"; $this->showFormButtons($options); return true; }
/** * Permet l'affichage dynamique d'une liste d�roulante imbriquee * * @static * @param array ($itemtype,$options) */ public static function dropdownReferencesByEnterprise($itemtype, $options = array()) { global $DB, $CFG_GLPI; $item = getItemForItemtype($itemtype); if ($itemtype && !($item = getItemForItemtype($itemtype))) { return false; } $table = $item->getTable(); $params['comments'] = true; $params['condition'] = ''; $params['entity'] = -1; $params['name'] = "reference"; $params['value'] = 0; $params['entity_sons'] = false; $params['rand'] = mt_rand(); $params['used'] = array(); $params['table'] = $table; $params['emptylabel'] = Dropdown::EMPTY_VALUE; //specific $params['action'] = ""; $params['itemtype'] = ""; $params['span'] = ""; $params['orders_id'] = 0; $params['suppliers_id'] = 0; if (is_array($options) && count($options)) { foreach ($options as $key => $val) { $params[$key] = $val; } } $name = $params['emptylabel']; $comment = ""; $limit_length = $_SESSION["glpidropdown_chars_limit"]; if (strlen($params['value']) == 0 || !is_numeric($params['value'])) { $params['value'] = 0; } if ($params['value'] > 0) { $tmpname = Dropdown::getDropdownName($table, $params['value'], 1); if ($tmpname["name"] != " ") { $name = $tmpname["name"]; $comment = $tmpname["comment"]; if (Toolbox::strlen($name) > $_SESSION["glpidropdown_chars_limit"]) { if ($item instanceof CommonTreeDropdown) { $pos = strrpos($name, ">"); $limit_length = max(Toolbox::strlen($name) - $pos, $_SESSION["glpidropdown_chars_limit"]); if (Toolbox::strlen($name) > $limit_length) { $name = "…" . Toolbox::substr($name, -$limit_length); } } else { $limit_length = Toolbox::strlen($name); } } else { $limit_length = $_SESSION["glpidropdown_chars_limit"]; } } } // Manage entity_sons if (!($params['entity'] < 0) && $params['entity_sons']) { if (is_array($params['entity'])) { echo "entity_sons options is not available with array of entity"; } else { $params['entity'] = getSonsOf('glpi_entities', $params['entity']); } } $use_ajax = false; if ($CFG_GLPI["use_ajax_autocompletion"]) { $nb = 0; $query = "SELECT COUNT(*) AS cpt\n FROM `{$table}` as t\n LEFT JOIN `glpi_plugin_order_references_suppliers` as s\n ON (`t`.`id` = `s`.`plugin_order_references_id`)\n WHERE `s`.`suppliers_id` = '{$params['suppliers_id']}'\n AND `t`.`itemtype` = '{$params['itemtype']}'"; if ($item->isEntityAssign()) { if (!($params['entity'] < 0)) { $query .= getEntitiesRestrictRequest("AND", 't', '', $params['entity'], true); } else { $query .= getEntitiesRestrictRequest("AND", 't', '', '', true); } } $result = $DB->query($query); if ($DB->numrows($result) == 1) { $nb = $DB->result($result, 0, "cpt"); } $nb -= count($params['used']); if ($nb > $CFG_GLPI["ajax_limit_count"]) { $use_ajax = true; } } $param = array('searchText' => '__VALUE__', 'value' => $params['value'], 'itemtype' => $params['itemtype'], 'myname' => $params['name'], 'limit' => $limit_length, 'comment' => $params['comments'], 'rand' => $params['rand'], 'entity_restrict' => $params['entity'], 'used' => $params['used'], 'condition' => $params['condition'], 'table' => $params['table'], 'action' => $params['action'], 'span' => $params['span'], 'orders_id' => $params['orders_id'], 'suppliers_id' => $params['suppliers_id']); $default = "<select name='" . $params['name'] . "' id='dropdown_" . $params['name'] . $params['rand'] . "'>"; $default .= "<option value='" . $params['value'] . "'>{$name}</option></select>"; Ajax::Dropdown($use_ajax, "/plugins/order/ajax/dropdownValue.php", $param, $default, $params['rand']); // Display comment if ($params['comments']) { $options_tooltip = array('contentid' => "comment_" . $param['myname'] . $params['rand']); if ($params['value'] && $item->getFromDB($params['value'])) { $options_tooltip['link'] = $item->getLinkURL(); $options_tooltip['linktarget'] = '_blank'; } Html::showToolTip($comment, $options_tooltip); if ($itemtype::canCreate() && !isset($_GET['popup'])) { echo "<img alt='' title=\"" . __("Add") . "\" src='" . $CFG_GLPI["root_doc"] . "\n /pics/add_dropdown.png' style='cursor:pointer; margin-left:2px;'\n onClick=\"var w = window . open('" . $item->getFormURL() . "?popup=1&rand=" . $params['rand'] . "&itemtype=" . $params['itemtype'] . "&entities_id=" . $params['entity'] . "', " . "'glpipopup', 'height=400,width=1000, top=100, left=100,\n scrollbars=yes' );w.focus();\">"; } } return $params['rand']; }
static function pdfForItem(PluginPdfSimplePDF $pdf, CommonDBTM $item, $tree = false) { global $DB, $CFG_GLPI; $ID = $item->getField('id'); $type = $item->getType(); if (!Session::haveRight("show_all_ticket", "1")) { return; } switch ($item->getType()) { case 'User': $restrict = "(`glpi_tickets_users`.`users_id` = '" . $item->getID() . "'\n AND `glpi_tickets_users`.`type` = " . CommonITILActor::REQUESTER . ")"; $order = '`glpi_tickets`.`date_mod` DESC'; break; case 'SLA': $restrict = "(`slas_id` = '" . $item->getID() . "')"; $order = '`glpi_tickets`.`due_date` DESC'; break; case 'Supplier': $restrict = "(`glpi_suppliers_tickets`.`suppliers_id` = '" . $item->getID() . "'\n AND `glpi_suppliers_tickets`.`type` = " . CommonITILActor::ASSIGN . ")"; $order = '`glpi_tickets`.`date_mod` DESC'; break; case 'Group': if ($tree) { $restrict = "IN (" . implode(',', getSonsOf('glpi_groups', $item->getID())) . ")"; } else { $restrict = "='" . $item->getID() . "'"; } $restrict = "(`glpi_groups_tickets`.`groups_id` {$restrict}\n AND `glpi_groups_tickets`.`type` = " . CommonITILActor::REQUESTER . ")"; $order = '`glpi_tickets`.`date_mod` DESC'; break; default: $restrict = "(`items_id` = '" . $item->getID() . "' AND `itemtype` = '{$type}')"; $order = '`glpi_tickets`.`date_mod` DESC'; } $query = "SELECT " . Ticket::getCommonSelect() . "\n FROM glpi_tickets " . Ticket::getCommonLeftJoin() . "\n WHERE {$restrict} " . getEntitiesRestrictRequest("AND", "glpi_tickets") . "\n ORDER BY {$order}\n LIMIT " . intval($_SESSION['glpilist_limit']); $result = $DB->query($query); $number = $DB->numrows($result); $pdf->setColumnsSize(100); if (!$number) { $pdf->displayTitle('<b>' . __('Last tickets') . '</b>'); } else { $pdf->displayTitle("<b>" . sprintf(__('Last %d ticket') . "</b>", $number)); $job = new Ticket(); while ($data = $DB->fetch_assoc($result)) { if (!$job->getFromDB($data["id"])) { continue; } $pdf->setColumnsAlign('center'); $col = '<b><i>ID ' . $job->fields["id"] . '</i></b>, ' . sprintf(__('%1$s: %2$s'), __('Status'), Ticket::getStatus($job->fields["status"])); if (count($_SESSION["glpiactiveentities"]) > 1) { if ($job->fields['entities_id'] == 0) { $col = sprintf(__('%1$s (%2$s)'), $col, __('Root entity')); } else { $col = sprintf(__('%1$s (%2$s)'), $col, Dropdown::getDropdownName("glpi_entities", $job->fields['entities_id'])); } } $pdf->displayLine($col); $pdf->setColumnsAlign('left'); $col = '<b><i>' . sprintf(__('Opened on %s') . '</i></b>', Html::convDateTime($job->fields['date'])); if ($job->fields['begin_waiting_date']) { $col = sprintf(__('%1$s, %2$s'), $col, '<b><i>' . sprintf(__('Put on hold on %s') . '</i></b>', Html::convDateTime($job->fields['begin_waiting_date']))); } if (in_array($job->fields["status"], $job->getSolvedStatusArray()) || in_array($job->fields["status"], $job->getClosedStatusArray())) { $col = sprintf(__('%1$s, %2$s'), $col, '<b><i>' . sprintf(__('Solved on %s') . '</i></b>', Html::convDateTime($job->fields['solvedate']))); } if (in_array($job->fields["status"], $job->getClosedStatusArray())) { $col = sprintf(__('%1$s, %2$s'), $col, '<b><i>' . sprintf(__('Closed on %s') . '</i></b>', Html::convDateTime($job->fields['closedate']))); } if ($job->fields['due_date']) { $col = sprintf(__('%1$s, %2$s'), $col, '<b><i>' . sprintf(__('%1$s: %2$s') . '</i></b>', __('Due date'), Html::convDateTime($job->fields['due_date']))); } $pdf->displayLine($col); $col = '<b><i>' . sprintf(__('%1$s: %2$s'), __('Priority') . '</i></b>', Ticket::getPriorityName($job->fields["priority"])); if ($job->fields["itilcategories_id"]) { $col = sprintf(__('%1$s - %2$s'), $col, '<b><i>' . sprintf(__('%1$s: %2$s') . '</i></b>', __('Category'), Dropdown::getDropdownName('glpi_itilcategories', $job->fields["itilcategories_id"]))); } $pdf->displayLine($col); $col = ''; $users = $job->getUsers(CommonITILActor::REQUESTER); if (count($users)) { foreach ($users as $d) { if (empty($col)) { $col = getUserName($d['users_id']); } else { $col = sprintf(__('%1$s, %2$s'), $col, getUserName($d['users_id'])); } } } $grps = $job->getGroups(CommonITILActor::REQUESTER); if (count($grps)) { if (empty($col)) { $col = sprintf(__('%1$s %2$s'), $col, _n('Group', 'Groups', 2) . ' </i></b>'); } else { $col = sprintf(__('%1$s - %2$s'), $col, _n('Group', 'Groups', 2) . ' </i></b>'); } $first = true; foreach ($grps as $d) { if ($first) { $col = sprintf(__('%1$s %2$s'), $col, Dropdown::getDropdownName("glpi_groups", $d['groups_id'])); } else { $col = sprintf(__('%1$s, %2$s'), $col, Dropdown::getDropdownName("glpi_groups", $d['groups_id'])); } $first = false; } } if ($col) { $texte = '<b><i>' . sprintf(__('%1$s: %2$s'), __('Requester') . '</i></b>', ''); $pdf->displayText($texte, $col, 1); } $col = ''; $users = $job->getUsers(CommonITILActor::ASSIGN); if (count($users)) { foreach ($users as $d) { if (empty($col)) { $col = getUserName($d['users_id']); } else { $col = sprintf(__('%1$s, %2$s'), $col, getUserName($d['users_id'])); } } } $grps = $job->getGroups(CommonITILActor::ASSIGN); if (count($grps)) { if (empty($col)) { $col = sprintf(__('%1$s %2$s'), $col, _n('Group', 'Groups', 2) . ' </i></b>'); } else { $col = sprintf(__('%1$s - %2$s'), $col, _n('Group', 'Groups', 2) . ' </i></b>'); } $first = true; foreach ($grps as $d) { if ($first) { $col = sprintf(__('%1$s %2$s'), $col, Dropdown::getDropdownName("glpi_groups", $d['groups_id'])); } else { $col = sprintf(__('%1$s, %2$s'), $col, Dropdown::getDropdownName("glpi_groups", $d['groups_id'])); } $first = false; } } if ($col) { $texte = '<b><i>' . sprintf(__('%1$s: %2$s') . '</i></b>', 'Assigned to', ''); $pdf->displayText($texte, $col, 1); } $texte = '<b><i>' . sprintf(__('%1$s: %2$s') . '</i></b>', 'Title', ''); $pdf->displayText($texte, $job->fields["name"], 1); } } $pdf->displaySpace(); }
$table = getTableForItemType('PluginFormcreatorFormprofiles'); $query = "SELECT *\n FROM {$table}\n WHERE plugin_formcreator_profiles_id = {$_SESSION['glpiactiveprofile']['id']}\n AND plugin_formcreator_forms_id = {$form->fields['id']}"; $result = $DB->query($query); if ($DB->numrows($result) == 0) { Html::displayRightError(); exit; } } if ($form->fields['access_rights'] == PluginFormcreatorForm::ACCESS_PUBLIC && !isset($_SESSION['glpiID'])) { // If user is not authenticated, create temporary user if (!isset($_SESSION['glpiname'])) { $_SESSION['formcreator_forms_id'] = $form->fields['id']; $_SESSION['glpiname'] = 'formcreator_temp_user'; $_SESSION['valid_id'] = session_id(); $_SESSION['glpiactiveentities'] = $form->fields['entities_id']; $subentities = getSonsOf('glpi_entities', $form->fields['entities_id']); $_SESSION['glpiactiveentities_string'] = !empty($subentities) ? "'" . implode("', '", $subentities) . "'" : "'" . $form->fields['entities_id'] . "'"; } } if (isset($_SESSION['glpiactiveprofile']['interface']) && $_SESSION['glpiactiveprofile']['interface'] == 'helpdesk') { Html::helpHeader(__('Form list', 'formcreator'), $_SERVER['PHP_SELF']); $form->displayUserForm($form); Html::helpFooter(); } elseif (!empty($_SESSION['glpiactiveprofile'])) { Html::header(__('Form Creator', 'formcreator'), $_SERVER['PHP_SELF'], 'helpdesk', 'PluginFormcreatorFormlist'); $form->displayUserForm($form); Html::footer(); } else { Html::nullHeader(__('Form Creator', 'formcreator'), $_SERVER['PHP_SELF']); Html::displayMessageAfterRedirect(); $form->displayUserForm($form);
/** * List doubles * * @param $unicity an instance of FieldUnicity class **/ static function showDoubles(FieldUnicity $unicity) { global $DB; $fields = array(); $where_fields = array(); if (!($item = getItemForItemtype($unicity->fields['itemtype']))) { return; } foreach (explode(',', $unicity->fields['fields']) as $field) { $fields[] = $field; $where_fields[] = $field; } if (!empty($fields)) { $colspan = count($fields) + 1; echo "<table class='tab_cadre_fixe'>"; echo "<tr class='tab_bg_2'><th colspan='" . $colspan . "'>" . __('Duplicates') . "</th></tr>"; $entities = array($unicity->fields['entities_id']); if ($unicity->fields['is_recursive']) { $entities = getSonsOf('glpi_entities', $unicity->fields['entities_id']); } $fields_string = implode(',', $fields); if ($item->maybeTemplate()) { $where_template = " AND `" . $item->getTable() . "`.`is_template` = '0'"; } else { $where_template = ""; } $where_fields_string = ""; foreach ($where_fields as $where_field) { if (getTableNameForForeignKeyField($where_field)) { $where_fields_string .= " AND `{$where_field}` IS NOT NULL AND `{$where_field}` <> '0'"; } else { $where_fields_string .= " AND `{$where_field}` IS NOT NULL AND `{$where_field}` <> ''"; } } $query = "SELECT {$fields_string},\n COUNT(*) AS cpt\n FROM `" . $item->getTable() . "`\n WHERE `" . $item->getTable() . "`.`entities_id` IN (" . implode(',', $entities) . ")\n {$where_template}\n {$where_fields_string}\n GROUP BY {$fields_string}\n ORDER BY cpt DESC"; $results = array(); foreach ($DB->request($query) as $data) { if ($data['cpt'] > 1) { $results[] = $data; } } if (empty($results)) { echo "<tr class='tab_bg_2'>"; echo "<td class='center' colspan='{$colspan}'>" . __('No item to display') . "</td></tr>"; } else { echo "<tr class='tab_bg_2'>"; foreach ($fields as $field) { $searchOption = $item->getSearchOptionByField('field', $field); echo "<th>" . $searchOption["name"] . "</th>"; } echo "<th>" . _x('quantity', 'Number') . "</th></tr>"; foreach ($results as $result) { echo "<tr class='tab_bg_2'>"; foreach ($fields as $field) { $table = getTableNameForForeignKeyField($field); if ($table != '') { echo "<td>" . Dropdown::getDropdownName($table, $result[$field]) . "</td>"; } else { echo "<td>" . $result[$field] . "</td>"; } } echo "<td class='numeric'>" . $result['cpt'] . "</td></tr>"; } } } else { echo "<tr class='tab_bg_2'>"; echo "<td class='center' colspan='{$colspan}'>" . __('No item to display') . "</td></tr>"; } echo "</table>"; }
function getRuleListQuery($options = array()) { $p['active'] = true; $p['start'] = 0; $p['limit'] = 0; $p['inherited'] = true; $p['childrens'] = false; foreach ($options as $key => $value) { $p[$key] = $value; } if ($p['active']) { $sql_active = " `is_active` = '1'"; } else { $sql_active = "1"; } $sql = "SELECT `glpi_rules`.*\n FROM `glpi_rules`"; //Select all the rules of a different type if ($this->isRuleRecursive()) { $sql .= " LEFT JOIN `glpi_entities` ON (`glpi_entities`.`id`=`glpi_rules`.`entities_id`)\n WHERE {$sql_active}\n AND `sub_type` = '" . $this->getRuleClassName() . "' "; if (!$p['childrens']) { $sql .= getEntitiesRestrictRequest(" AND", "glpi_rules", "entities_id", $this->entity, $p['inherited']); } else { $sons = getSonsOf('glpi_entities', $this->entity); $sql .= " AND `glpi_rules`.`entities_id` IN (" . implode(',', $sons) . ")"; } $sql .= " ORDER BY `glpi_entities`.`level` ASC,\n `" . $this->orderby . "` ASC"; } else { $sql .= "WHERE {$sql_active}\n AND `sub_type` = '" . $this->getRuleClassName() . "'\n ORDER BY `" . $this->orderby . "` ASC"; } if ($p['limit']) { $sql .= " LIMIT " . intval($p['start']) . "," . intval($p['limit']); } return $sql; }
/** * Change active entity to the $ID one. Update glpiactiveentities session variable. * Reload groups related to this entity. * * @param $ID : ID of the new active entity ("all"=>load all possible entities) * @param $is_recursive : also display sub entities of the active entity ? * * @return Nothing **/ function changeActiveEntities($ID = "all", $is_recursive = false) { global $LANG; $newentities = array(); $newroots = array(); if (isset($_SESSION['glpiactiveprofile'])) { if ($ID == "all") { $ancestors = array(); foreach ($_SESSION['glpiactiveprofile']['entities'] as $key => $val) { $ancestors = array_unique(array_merge(getAncestorsOf("glpi_entities", $val['id']), $ancestors)); $newroots[$val['id']] = $val['is_recursive']; $newentities[$val['id']] = $val['id']; if ($val['is_recursive']) { $entities = getSonsOf("glpi_entities", $val['id']); if (count($entities)) { foreach ($entities as $key2 => $val2) { $newentities[$key2] = $key2; } } } } } else { /// Check entity validity $ancestors = getAncestorsOf("glpi_entities", $ID); $ok = false; foreach ($_SESSION['glpiactiveprofile']['entities'] as $key => $val) { if ($val['id'] == $ID || in_array($val['id'], $ancestors)) { // Not recursive or recursive and root entity is recursive if (!$is_recursive || $val['is_recursive']) { $ok = true; } } } if (!$ok) { return false; } $newroots[$ID] = $is_recursive; $newentities[$ID] = $ID; if ($is_recursive) { $entities = getSonsOf("glpi_entities", $ID); if (count($entities)) { foreach ($entities as $key2 => $val2) { $newentities[$key2] = $key2; } } } } } if (count($newentities) > 0) { $_SESSION['glpiactiveentities'] = $newentities; $_SESSION['glpiactiveentities_string'] = "'" . implode("', '", $newentities) . "'"; $active = reset($newentities); $_SESSION['glpiparententities'] = $ancestors; $_SESSION['glpiparententities_string'] = implode("', '", $ancestors); if (!empty($_SESSION['glpiparententities_string'])) { $_SESSION['glpiparententities_string'] = "'" . $_SESSION['glpiparententities_string'] . "'"; } // Active entity loading $_SESSION["glpiactive_entity"] = $active; $_SESSION["glpiactive_entity_name"] = Dropdown::getDropdownName("glpi_entities", $active); $_SESSION["glpiactive_entity_shortname"] = getTreeLeafValueName("glpi_entities", $active); if ($is_recursive) { $_SESSION["glpiactive_entity_name"] .= " (" . $LANG['entity'][7] . ")"; $_SESSION["glpiactive_entity_shortname"] .= " (" . $LANG['entity'][7] . ")"; } if ($ID == "all") { $_SESSION["glpiactive_entity_name"] .= " (" . $LANG['buttons'][40] . ")"; $_SESSION["glpiactive_entity_shortname"] .= " (" . $LANG['buttons'][40] . ")"; } if (countElementsInTable('glpi_entities') < count($_SESSION['glpiactiveentities'])) { $_SESSION['glpishowallentities'] = 1; } else { $_SESSION['glpishowallentities'] = 0; } // Clean session variable to search system if (isset($_SESSION['glpisearch']) && count($_SESSION['glpisearch'])) { foreach ($_SESSION['glpisearch'] as $itemtype => $tab) { if (isset($tab['start']) && $tab['start'] > 0) { $_SESSION['glpisearch'][$itemtype]['start'] = 0; } } } loadGroups(); doHook("change_entity"); return true; } return false; }
static function dropdownService($ID, $options = array()) { global $CFG_GLPI; $p = array(); $p['name'] = 'networkports_id'; $p['comments'] = 1; $p['entity'] = -1; $p['entity_sons'] = false; if (is_array($options) && count($options)) { foreach ($options as $key => $val) { $p[$key] = $val; } } // Manage entity_sons if (!($p['entity'] < 0) && $p['entity_sons']) { if (is_array($p['entity'])) { echo "entity_sons options is not available with array of entity"; } else { $p['entity'] = getSonsOf('glpi_entities', $p['entity']); } } $rand = mt_rand(); echo "<select name='itemtype[{$ID}]' id='itemtype{$rand}'>"; echo "<option value='0'>" . DROPDOWN_EMPTY_VALUE . "</option>"; // $a_types =array(); echo "<option value='Computer'>" . Computer::getTypeName() . "</option>"; echo "<option value='NetworkEquipment'>" . NetworkEquipment::getTypeName() . "</option>"; echo "</select>"; $params = array('itemtype' => '__VALUE__', 'entity_restrict' => $p['entity'], 'current' => $ID, 'comments' => $p['comments'], 'myname' => $p['name'], 'rand' => $rand); ajaxUpdateItemOnSelectEvent("itemtype{$rand}", "show_" . $p['name'] . "{$rand}", $CFG_GLPI["root_doc"] . "/plugins/monitoring/ajax/dropdownServiceHostType.php", $params); echo "<span id='show_" . $p['name'] . "{$rand}'><input type='hidden' name='services_id[]' value='0'/></span>\n"; return $rand; }
/** * Print a select with contracts * * Print a select named $name with contracts options and selected value $value * @param $options array of possible options: * - name : string / name of the select (default is contracts_id) * - value : integer / preselected value (default 0) * - entity : integer or array / restrict to a defined entity or array of entities * (default -1 : no restriction) * - entity_sons : boolean / if entity restrict specified auto select its sons * only available if entity is a single value not an array (default false) * - used : array / Already used items ID: not to display in dropdown (default empty) * - nochecklimit : boolean / disable limit for nomber of device (for supplier, default false) * * @return Nothing (display) **/ static function dropdown($options = array()) { global $DB; //$name,$entity_restrict=-1,$alreadyused=array(),$nochecklimit=false $p['name'] = 'contracts_id'; $p['value'] = ''; $p['entity'] = ''; $p['entity_sons'] = false; $p['used'] = array(); $p['nochecklimit'] = false; $p['on_change'] = ''; if (is_array($options) && count($options)) { foreach ($options as $key => $val) { $p[$key] = $val; } } if (!($p['entity'] < 0) && $p['entity_sons']) { if (is_array($p['entity'])) { // no translation needed (only for dev) echo "entity_sons options is not available with array of entity"; } else { $p['entity'] = getSonsOf('glpi_entities', $p['entity']); } } $entrest = ""; $idrest = ""; if ($p['entity'] >= 0) { $entrest = getEntitiesRestrictRequest("AND", "glpi_contracts", "entities_id", $p['entity'], true); } if (count($p['used'])) { $idrest = " AND `glpi_contracts`.`id` NOT IN('" . implode("','", $p['used']) . "') "; } $query = "SELECT `glpi_contracts`.*\n FROM `glpi_contracts`\n LEFT JOIN `glpi_entities` ON (`glpi_contracts`.`entities_id` = `glpi_entities`.`id`)\n WHERE `glpi_contracts`.`is_deleted` = '0' {$entrest} {$idrest}\n ORDER BY `glpi_entities`.`completename`,\n `glpi_contracts`.`name` ASC,\n `glpi_contracts`.`begin_date` DESC"; $result = $DB->query($query); echo "<select name='" . $p['name'] . "'"; if (!empty($p["on_change"])) { echo " onChange='" . $p["on_change"] . "'"; } echo '>'; if ($p['value'] > 0) { $output = Dropdown::getDropdownName('glpi_contracts', $p['value']); if ($_SESSION["glpiis_ids_visible"]) { $output = sprintf(__('%1$s (%2$s)'), $output, $p['value']); } echo "<option selected value='" . $p['value'] . "'>" . $output . "</option>"; } else { echo "<option value='-1'>" . Dropdown::EMPTY_VALUE . "</option>"; } $prev = -1; while ($data = $DB->fetch_assoc($result)) { if ($p['nochecklimit'] || $data["max_links_allowed"] == 0 || $data["max_links_allowed"] > countElementsInTable("glpi_contracts_items", "contracts_id\n = '" . $data['id'] . "'")) { if ($data["entities_id"] != $prev) { if ($prev >= 0) { echo "</optgroup>"; } $prev = $data["entities_id"]; echo "<optgroup label=\"" . Dropdown::getDropdownName("glpi_entities", $prev) . "\">"; } $name = $data["name"]; if ($_SESSION["glpiis_ids_visible"] || empty($data["name"])) { $name = sprintf(__('%1$s (%2$s)'), $name, $data["id"]); } echo "<option value='" . $data["id"] . "'>"; $tmp = sprintf(__('%1$s - %2$s'), $name, $data["num"]); $tmp = sprintf(__('%1$s - %2$s'), $tmp, Html::convDateTime($data["begin_date"])); echo Toolbox::substr($tmp, 0, $_SESSION["glpidropdown_chars_limit"]); echo "</option>"; } } if ($prev >= 0) { echo "</optgroup>"; } echo "</select>"; }
/** * Generic Function to add where to a request * * @param $link link string * @param $nott is it a negative search ? * @param $itemtype item type * @param $ID ID of the item to search * @param $searchtype searchtype used (equals or contains) * @param $val item num in the request * @param $meta is a meta search (meta=2 in search.class.php) (default 0) * * @return select string **/ static function addWhere($link, $nott, $itemtype, $ID, $searchtype, $val, $meta = 0) { $searchopt =& self::getOptions($itemtype); $table = $searchopt[$ID]["table"]; $field = $searchopt[$ID]["field"]; $inittable = $table; $addtable = ''; if ($table != 'asset_types' && $table != getTableForItemType($itemtype) && $searchopt[$ID]["linkfield"] != getForeignKeyFieldForTable($table)) { $addtable = "_" . $searchopt[$ID]["linkfield"]; $table .= $addtable; } if (isset($searchopt[$ID]['joinparams'])) { $complexjoin = self::computeComplexJoinID($searchopt[$ID]['joinparams']); if (!empty($complexjoin)) { $table .= "_" . $complexjoin; } } if ($meta && getTableForItemType($itemtype) != $table) { $table .= "_" . $itemtype; } // Hack to allow search by ID on every sub-table if (preg_match('/^\\$\\$\\$\\$([0-9]+)$/', $val, $regs)) { return $link . " (`{$table}`.`id` " . ($nott ? "<>" : "=") . $regs[1] . " " . ($regs[1] == 0 ? " OR `{$table}`.`id` IS NULL" : '') . ") "; } // Preparse value if (isset($searchopt[$ID]["datatype"])) { switch ($searchopt[$ID]["datatype"]) { case "datetime": case "date": case "date_delay": $force_day = true; if ($searchopt[$ID]["datatype"] == 'datetime') { $force_day = false; } if (strstr($val, 'BEGIN') || strstr($val, 'LAST')) { $force_day = true; } $val = Html::computeGenericDateTimeSearch($val, $force_day); break; } } switch ($searchtype) { case "contains": $SEARCH = self::makeTextSearch($val, $nott); break; case "equals": if ($nott) { $SEARCH = " <> '{$val}'"; } else { $SEARCH = " = '{$val}'"; } break; case "notequals": if ($nott) { $SEARCH = " = '{$val}'"; } else { $SEARCH = " <> '{$val}'"; } break; case "under": if ($nott) { $SEARCH = " NOT IN ('" . implode("','", getSonsOf($inittable, $val)) . "')"; } else { $SEARCH = " IN ('" . implode("','", getSonsOf($inittable, $val)) . "')"; } break; case "notunder": if ($nott) { $SEARCH = " IN ('" . implode("','", getSonsOf($inittable, $val)) . "')"; } else { $SEARCH = " NOT IN ('" . implode("','", getSonsOf($inittable, $val)) . "')"; } break; } // Plugin can override core definition for its type if ($plug = isPluginItemType($itemtype)) { $function = 'plugin_' . $plug['plugin'] . '_addWhere'; if (function_exists($function)) { $out = $function($link, $nott, $itemtype, $ID, $val, $searchtype); if (!empty($out)) { return $out; } } } switch ($inittable . "." . $field) { // // case "glpi_users_validation.name" : case "glpi_users.name": if ($itemtype == 'User') { // glpi_users case / not link table if (in_array($searchtype, array('equals', 'notequals'))) { return " {$link} `{$table}`.`id`" . $SEARCH; } return self::makeTextCriteria("`{$table}`.`{$field}`", $val, $nott, $link); } if ($_SESSION["glpinames_format"] == User::FIRSTNAME_BEFORE) { $name1 = 'firstname'; $name2 = 'realname'; } else { $name1 = 'realname'; $name2 = 'firstname'; } if (in_array($searchtype, array('equals', 'notequals'))) { return " {$link} (`{$table}`.`id`" . $SEARCH . ($val == 0 ? " OR `{$table}`.`id` IS NULL" : '') . ') '; } $toadd = ''; $tmplink = 'OR'; if ($nott) { $tmplink = 'AND'; } if ($itemtype == 'Ticket' || $itemtype == 'Problem') { if (isset($searchopt[$ID]["joinparams"]["beforejoin"]["table"]) && isset($searchopt[$ID]["joinparams"]["beforejoin"]["joinparams"]) && ($searchopt[$ID]["joinparams"]["beforejoin"]["table"] == 'glpi_tickets_users' || $searchopt[$ID]["joinparams"]["beforejoin"]["table"] == 'glpi_problems_users' || $searchopt[$ID]["joinparams"]["beforejoin"]["table"] == 'glpi_changes_users')) { $bj = $searchopt[$ID]["joinparams"]["beforejoin"]; $linktable = $bj['table'] . '_' . self::computeComplexJoinID($bj['joinparams']); //$toadd = "`$linktable`.`alternative_email` $SEARCH $tmplink "; $toadd = self::makeTextCriteria("`{$linktable}`.`alternative_email`", $val, $nott, $tmplink); } } $toadd2 = ''; if ($nott && $val != 'NULL' && $val != 'null') { $toadd2 = " OR `{$table}`.`{$field}` IS NULL"; } return $link . " (((`{$table}`.`{$name1}` {$SEARCH}\n {$tmplink} `{$table}`.`{$name2}` {$SEARCH}\n {$tmplink} `{$table}`.`{$field}` {$SEARCH}\n {$tmplink} CONCAT(`{$table}`.`{$name1}`, ' ', `{$table}`.`{$name2}`) {$SEARCH} )\n {$toadd2}) {$toadd})"; case "glpi_groups.completename": if ($val == 'mygroups') { switch ($searchtype) { case 'equals': return " {$link} (`{$table}`.`id` IN ('" . implode("','", $_SESSION['glpigroups']) . "')) "; case 'notequals': return " {$link} (`{$table}`.`id` NOT IN ('" . implode("','", $_SESSION['glpigroups']) . "')) "; case 'under': $groups = $_SESSION['glpigroups']; foreach ($_SESSION['glpigroups'] as $g) { $groups += getSonsOf($inittable, $g); } $groups = array_unique($groups); return " {$link} (`{$table}`.`id` IN ('" . implode("','", $groups) . "')) "; case 'notunder': $groups = $_SESSION['glpigroups']; foreach ($_SESSION['glpigroups'] as $g) { $groups += getSonsOf($inittable, $g); } $groups = array_unique($groups); return " {$link} (`{$table}`.`id` NOT IN ('" . implode("','", $groups) . "')) "; } } break; case "glpi_auth_tables.name": $user_searchopt = self::getOptions('User'); $tmplink = 'OR'; if ($nott) { $tmplink = 'AND'; } return $link . " (`glpi_authmails" . $addtable . "_" . self::computeComplexJoinID($user_searchopt[31]['joinparams']) . "`.`name`\n {$SEARCH}\n {$tmplink} `glpi_authldaps" . $addtable . "_" . self::computeComplexJoinID($user_searchopt[30]['joinparams']) . "`.`name`\n {$SEARCH} ) "; case "glpi_ipaddresses.name": $search = array("/\\</", "/\\>/"); $replace = array("<", ">"); $val = preg_replace($search, $replace, $val); if (preg_match("/^\\s*([<>])([=]*)[[:space:]]*([0-9\\.]+)/", $val, $regs)) { if ($nott) { if ($regs[1] == '<') { $regs[1] = '>'; } else { $regs[1] = '<'; } } $regs[1] .= $regs[2]; return $link . " (INET_ATON(`{$table}`.`{$field}`) " . $regs[1] . " INET_ATON('" . $regs[3] . "')) "; } break; case "glpi_tickets.status": case "glpi_problems.status": case "glpi_changes.status": if ($val == 'all') { return ""; } $tocheck = array(); if ($item = getItemForItemtype($itemtype)) { switch ($val) { case 'process': $tocheck = $item->getProcessStatusArray(); break; case 'notclosed': $tocheck = $item->getAllStatusArray(); foreach ($item->getClosedStatusArray() as $status) { if (isset($tocheck[$status])) { unset($tocheck[$status]); } } $tocheck = array_keys($tocheck); break; case 'old': $tocheck = array_merge($item->getSolvedStatusArray(), $item->getClosedStatusArray()); break; case 'notold': $tocheck = $item->getAllStatusArray(); foreach ($item->getSolvedStatusArray() as $status) { if (isset($tocheck[$status])) { unset($tocheck[$status]); } } foreach ($item->getClosedStatusArray() as $status) { if (isset($tocheck[$status])) { unset($tocheck[$status]); } } $tocheck = array_keys($tocheck); break; } } if (count($tocheck) == 0) { $statuses = $item->getAllStatusArray(); if (isset($statuses[$val])) { $tocheck = array($val); } } if (count($tocheck)) { if ($nott) { return $link . " `{$table}`.`{$field}` NOT IN ('" . implode("','", $tocheck) . "')"; } return $link . " `{$table}`.`{$field}` IN ('" . implode("','", $tocheck) . "')"; } break; case "glpi_tickets_tickets.tickets_id_1": $tmplink = 'OR'; $compare = '='; if ($nott) { $tmplink = 'AND'; $compare = '<>'; } $toadd2 = ''; if ($nott && $val != 'NULL' && $val != 'null') { $toadd2 = " OR `{$table}`.`{$field}` IS NULL"; } return $link . " (((`{$table}`.`tickets_id_1` {$compare} '{$val}'\n {$tmplink} `{$table}`.`tickets_id_2` {$compare} '{$val}')\n AND `glpi_tickets`.`id` <> '{$val}')\n {$toadd2})"; case "glpi_tickets.priority": case "glpi_tickets.impact": case "glpi_tickets.urgency": case "glpi_problems.priority": case "glpi_problems.impact": case "glpi_problems.urgency": case "glpi_changes.priority": case "glpi_changes.impact": case "glpi_changes.urgency": case "glpi_projects.priority": if (is_numeric($val)) { if ($val > 0) { return $link . " `{$table}`.`{$field}` = '{$val}'"; } if ($val < 0) { return $link . " `{$table}`.`{$field}` >= '" . abs($val) . "'"; } // Show all return $link . " `{$table}`.`{$field}` >= '0' "; } return ""; case "glpi_tickets.global_validation": case "glpi_ticketvalidations.status": if ($val == 'all') { return ""; } $tocheck = array(); switch ($val) { case 'can': $tocheck = CommonITILValidation::getCanValidationStatusArray(); break; case 'all': $tocheck = CommonITILValidation::getAllValidationStatusArray(); break; } if (count($tocheck) == 0) { $tocheck = array($val); } if (count($tocheck)) { if ($nott) { return $link . " `{$table}`.`{$field}` NOT IN ('" . implode("','", $tocheck) . "')"; } return $link . " `{$table}`.`{$field}` IN ('" . implode("','", $tocheck) . "')"; } break; } //// Default cases // Link with plugin tables if (preg_match("/^glpi_plugin_([a-z0-9]+)/", $inittable, $matches)) { if (count($matches) == 2) { $plug = $matches[1]; $function = 'plugin_' . $plug . '_addWhere'; if (function_exists($function)) { $out = $function($link, $nott, $itemtype, $ID, $val, $searchtype); if (!empty($out)) { return $out; } } } } $tocompute = "`{$table}`.`{$field}`"; $tocomputetrans = "`" . $table . "_" . $field . "_trans`.`value`"; if (isset($searchopt[$ID]["computation"])) { $tocompute = $searchopt[$ID]["computation"]; $tocompute = str_replace("TABLE", "`{$table}`", $tocompute); } // Preformat items if (isset($searchopt[$ID]["datatype"])) { switch ($searchopt[$ID]["datatype"]) { case "itemtypename": if (in_array($searchtype, array('equals', 'notequals'))) { return " {$link} (`{$table}`.`{$field}`" . $SEARCH . ') '; } break; case "itemlink": if (in_array($searchtype, array('equals', 'notequals', 'under', 'notunder'))) { return " {$link} (`{$table}`.`id`" . $SEARCH . ') '; } break; case "datetime": case "date": case "date_delay": if ($searchopt[$ID]["datatype"] == 'datetime') { // Specific search for datetime if (in_array($searchtype, array('equals', 'notequals'))) { $val = preg_replace("/:00\$/", '', $val); $val = '^' . $val; if ($searchtype == 'notequals') { $nott = !$nott; } return self::makeTextCriteria("`{$table}`.`{$field}`", $val, $nott, $link); } } if ($searchtype == 'lessthan') { $val = '<' . $val; } if ($searchtype == 'morethan') { $val = '>' . $val; } if ($searchtype) { $date_computation = $tocompute; } $search_unit = ' MONTH '; if (isset($searchopt[$ID]['searchunit'])) { $search_unit = $searchopt[$ID]['searchunit']; } if ($searchopt[$ID]["datatype"] == "date_delay") { $delay_unit = ' MONTH '; if (isset($searchopt[$ID]['delayunit'])) { $delay_unit = $searchopt[$ID]['delayunit']; } $add_minus = ''; if (isset($searchopt[$ID]["datafields"][3])) { $add_minus = "-`{$table}`.`" . $searchopt[$ID]["datafields"][3] . "`"; } $date_computation = "ADDDATE(`{$table}`." . $searchopt[$ID]["datafields"][1] . ",\n INTERVAL (`{$table}`." . $searchopt[$ID]["datafields"][2] . "\n {$add_minus})\n {$delay_unit})"; } if (in_array($searchtype, array('equals', 'notequals'))) { return " {$link} ({$date_computation} " . $SEARCH . ') '; } $search = array("/\\</", "/\\>/"); $replace = array("<", ">"); $val = preg_replace($search, $replace, $val); if (preg_match("/^\\s*([<>=]+)(.*)/", $val, $regs)) { if (is_numeric($regs[2])) { return $link . " {$date_computation} " . $regs[1] . "\n ADDDATE(NOW(), INTERVAL " . $regs[2] . " {$search_unit}) "; } // ELSE Reformat date if needed $regs[2] = preg_replace('@(\\d{1,2})(-|/)(\\d{1,2})(-|/)(\\d{4})@', '\\5-\\3-\\1', $regs[2]); if (preg_match('/[0-9]{2,4}-[0-9]{1,2}-[0-9]{1,2}/', $regs[2])) { return $link . " {$date_computation} " . $regs[1] . " '" . $regs[2] . "'"; } return ""; } // ELSE standard search // Date format modification if needed $val = preg_replace('@(\\d{1,2})(-|/)(\\d{1,2})(-|/)(\\d{4})@', '\\5-\\3-\\1', $val); return self::makeTextCriteria($date_computation, $val, $nott, $link); case "right": if ($searchtype == 'notequals') { $nott = !$nott; } return $link . ($nott ? ' NOT' : '') . " ({$tocompute} & '{$val}') "; case "bool": if (!is_numeric($val)) { if (strcasecmp($val, __('No')) == 0) { $val = 0; } else { if (strcasecmp($val, __('Yes')) == 0) { $val = 1; } } } if ($searchtype == 'notequals') { $nott = !$nott; } // No break here : use number comparaison case // No break here : use number comparaison case case "count": case "number": case "decimal": case "timestamp": $search = array("/\\</", "/\\>/"); $replace = array("<", ">"); $val = preg_replace($search, $replace, $val); if (preg_match("/([<>])([=]*)[[:space:]]*([0-9]+)/", $val, $regs)) { if ($nott) { if ($regs[1] == '<') { $regs[1] = '>'; } else { $regs[1] = '<'; } } $regs[1] .= $regs[2]; return $link . " ({$tocompute} " . $regs[1] . " " . $regs[3] . ") "; } if (is_numeric($val)) { if (isset($searchopt[$ID]["width"])) { $ADD = ""; if ($nott && $val != 'NULL' && $val != 'null') { $ADD = " OR {$tocompute} IS NULL"; } if ($nott) { return $link . " ({$tocompute} < " . (intval($val) - $searchopt[$ID]["width"]) . "\n OR {$tocompute} > " . (intval($val) + $searchopt[$ID]["width"]) . "\n {$ADD}) "; } return $link . " (({$tocompute} >= " . (intval($val) - $searchopt[$ID]["width"]) . "\n AND {$tocompute} <= " . (intval($val) + $searchopt[$ID]["width"]) . ")\n {$ADD}) "; } if (!$nott) { return " {$link} ({$tocompute} = " . intval($val) . ") "; } return " {$link} ({$tocompute} <> " . intval($val) . ") "; } break; } } // Default case if (in_array($searchtype, array('equals', 'notequals', 'under', 'notunder'))) { if ((!isset($searchopt[$ID]['searchequalsonfield']) || !$searchopt[$ID]['searchequalsonfield']) && ($table != getTableForItemType($itemtype) || $itemtype == 'AllAssets')) { $out = " {$link} (`{$table}`.`id`" . $SEARCH; } else { $out = " {$link} (`{$table}`.`{$field}`" . $SEARCH; } if ($searchtype == 'notequals') { $nott = !$nott; } // Add NULL if $val = 0 and not negative search // Or negative search on real value if (!$nott && $val == 0 || $nott && $val != 0) { $out .= " OR `{$table}`.`id` IS NULL"; } $out .= ')'; return $out; } $transitemtype = getItemTypeForTable($inittable); if (Session::haveTranslations($transitemtype, $field)) { return " {$link} (" . self::makeTextCriteria($tocompute, $val, $nott, '') . "\n OR " . self::makeTextCriteria($tocomputetrans, $val, $nott, '') . ")"; } return self::makeTextCriteria($tocompute, $val, $nott, $link); }
/** * @since version 0.85 * * @see CommonDBTM::processMassiveActionsForOneItemtype() **/ static function processMassiveActionsForOneItemtype(MassiveAction $ma, CommonDBTM $item, array $ids) { switch ($ma->getAction()) { case 'duplicate': // For calendar duplicate in another entity if (method_exists($item, 'duplicate')) { $input = $ma->getInput(); $options = array(); if ($item->isEntityAssign()) { $options = array('entities_id' => $input['entities_id']); } foreach ($ids as $id) { if ($item->getFromDB($id)) { if (!$item->isEntityAssign() || $input['entities_id'] != $item->getEntityID()) { if ($item->can(-1, CREATE, $options)) { if ($item->duplicate($options)) { $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)); } } else { $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_KO); $ma->addMessage($item->getErrorMessage(ERROR_COMPAT)); } } else { $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_KO); $ma->addMessage($item->getErrorMessage(ERROR_NOT_FOUND)); } } } else { $ma->itemDone($item->getType(), $ids, MassiveAction::ACTION_KO); } return; case 'addholiday': // add an holiday with massive action $input = $ma->getInput(); if ($input['holidays_id'] > 0) { $holiday = new Holiday(); $calendar_holiday = new Calendar_Holiday(); $holiday->getFromDB($input['holidays_id']); $entities = array($holiday->getEntityID() => $holiday->getEntityID()); if ($holiday->isRecursive()) { $entities = getSonsOf("glpi_entities", $holiday->getEntityID()); } foreach ($ids as $id) { $entities_id = CommonDBTM::getItemEntity('Calendar', $id); if (isset($entities[$entities_id])) { $input = array('calendars_id' => $id, 'holidays_id' => $input['holidays_id']); if ($calendar_holiday->add($input)) { $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_KO); $ma->addMessage($item->getErrorMessage(ERROR_ON_ACTION)); } } } else { $ma->itemDone($item->getType(), $ids, MassiveAction::ACTION_KO); } return; } parent::processMassiveActionsForOneItemtype($ma, $item, $ids); }
/** * Display changes for an item * * Will also display changes of linked items * * @param $item CommonDBTM object * * @return nothing (display a table) **/ static function showListForItem(CommonDBTM $item) { global $DB, $CFG_GLPI; if (!Session::haveRight(self::$rightname, self::READALL)) { return false; } if ($item->isNewID($item->getID())) { return false; } $restrict = ''; $order = ''; $options['reset'] = 'reset'; switch ($item->getType()) { case 'User': $restrict = "(`glpi_changes_users`.`users_id` = '" . $item->getID() . "')"; $order = '`glpi_changes`.`date_mod` DESC'; $options['criteria'][0]['field'] = 4; // status $options['criteria'][0]['searchtype'] = 'equals'; $options['criteria'][0]['value'] = $item->getID(); $options['criteria'][0]['link'] = 'OR'; $options['criteria'][1]['field'] = 66; // status $options['criteria'][1]['searchtype'] = 'equals'; $options['criteria'][1]['value'] = $item->getID(); $options['criteria'][1]['link'] = 'OR'; $options['criteria'][5]['field'] = 5; // status $options['criteria'][5]['searchtype'] = 'equals'; $options['criteria'][5]['value'] = $item->getID(); $options['criteria'][5]['link'] = 'OR'; break; case 'Supplier': $restrict = "(`glpi_changes_suppliers`.`suppliers_id` = '" . $item->getID() . "')"; $order = '`glpi_changes`.`date_mod` DESC'; $options['criteria'][0]['field'] = 6; $options['criteria'][0]['searchtype'] = 'equals'; $options['criteria'][0]['value'] = $item->getID(); $options['criteria'][0]['link'] = 'AND'; break; case 'Group': // Mini search engine if ($item->haveChildren()) { $tree = Session::getSavedOption(__CLASS__, 'tree', 0); echo "<table class='tab_cadre_fixe'>"; echo "<tr class='tab_bg_1'><th>" . __('Last changes') . "</th></tr>"; echo "<tr class='tab_bg_1'><td class='center'>"; _e('Child groups'); Dropdown::showYesNo('tree', $tree, -1, array('on_change' => 'reloadTab("start=0&tree="+this.value)')); } else { $tree = 0; } echo "</td></tr></table>"; if ($tree) { $restrict = "IN (" . implode(',', getSonsOf('glpi_groups', $item->getID())) . ")"; } else { $restrict = "='" . $item->getID() . "'"; } $restrict = "(`glpi_changes_groups`.`groups_id` {$restrict}\n AND `glpi_changes_groups`.`type` = " . CommonITILActor::REQUESTER . ")"; $order = '`glpi_changes`.`date_mod` DESC'; $options['criteria'][0]['field'] = 71; $options['criteria'][0]['searchtype'] = $tree ? 'under' : 'equals'; $options['criteria'][0]['value'] = $item->getID(); $options['criteria'][0]['link'] = 'AND'; break; default: $restrict = "(`items_id` = '" . $item->getID() . "'\n AND `itemtype` = '" . $item->getType() . "')"; $order = '`glpi_changes`.`date_mod` DESC'; break; } $query = "SELECT " . self::getCommonSelect() . "\n FROM `glpi_changes`\n LEFT JOIN `glpi_changes_items`\n ON (`glpi_changes`.`id` = `glpi_changes_items`.`changes_id`) " . self::getCommonLeftJoin() . "\n WHERE {$restrict} " . getEntitiesRestrictRequest("AND", "glpi_changes") . "\n ORDER BY {$order}\n LIMIT " . intval($_SESSION['glpilist_limit']); $result = $DB->query($query); $number = $DB->numrows($result); // Ticket for the item echo "<div class='firstbloc'><table class='tab_cadre_fixe'>"; $colspan = 11; if (count($_SESSION["glpiactiveentities"]) > 1) { $colspan++; } if ($number > 0) { Session::initNavigateListItems('Change', sprintf(__('%1$s = %2$s'), $item->getTypeName(1), $item->getName())); echo "<tr><th colspan='{$colspan}'>"; //TRANS : %d is the number of problems echo sprintf(_n('Last %d change', 'Last %d changes', $number), $number); // echo "<span class='small_space'><a href='".$CFG_GLPI["root_doc"]."/front/ticket.php?". // Toolbox::append_params($options,'&')."'>".__('Show all')."</a></span>"; echo "</th></tr>"; } else { echo "<tr><th>" . __('No change found.') . "</th></tr>"; } // Ticket list if ($number > 0) { self::commonListHeader(Search::HTML_OUTPUT); while ($data = $DB->fetch_assoc($result)) { Session::addToNavigateListItems('Problem', $data["id"]); self::showShort($data["id"]); } self::commonListHeader(Search::HTML_OUTPUT); } echo "</table></div>"; // Tickets for linked items $linkeditems = $item->getLinkedItems(); $restrict = array(); if (count($linkeditems)) { foreach ($linkeditems as $ltype => $tab) { foreach ($tab as $lID) { $restrict[] = "(`itemtype` = '{$ltype}' AND `items_id` = '{$lID}')"; } } } if (count($restrict)) { $query = "SELECT " . self::getCommonSelect() . "\n FROM `glpi_changes`\n LEFT JOIN `glpi_changes_items`\n ON (`glpi_changes`.`id` = `glpi_changes_items`.`changes_id`) " . self::getCommonLeftJoin() . "\n WHERE " . implode(' OR ', $restrict) . getEntitiesRestrictRequest(' AND ', 'glpi_changes') . "\n ORDER BY `glpi_changes`.`date_mod` DESC\n LIMIT " . intval($_SESSION['glpilist_limit']); $result = $DB->query($query); $number = $DB->numrows($result); echo "<div class='spaced'><table class='tab_cadre_fixe'>"; echo "<tr><th colspan='{$colspan}'>"; _e('Changes on linked items'); echo "</th></tr>"; if ($number > 0) { self::commonListHeader(Search::HTML_OUTPUT); while ($data = $DB->fetch_assoc($result)) { // Session::addToNavigateListItems(TRACKING_TYPE,$data["id"]); self::showShort($data["id"]); } self::commonListHeader(Search::HTML_OUTPUT); } else { echo "<tr><th>" . __('No change found.') . "</th></tr>"; } echo "</table></div>"; } // Subquery for linked item }
/** * get list of Computers in a group * * @since version 0.83 * * @param $types Array of types * @param $field String field name * @param $tree Boolean include child groups * @param $user Boolean include members (users) * @param $start Integer (first row to retrieve) * @param $res Array result filled on ouput * * @return integer total of items **/ function getDataItems(array $types, $field, $tree, $user, $start, array &$res) { global $DB; // include item of child groups ? if ($tree) { $grprestrict = "IN (" . implode(',', getSonsOf('glpi_groups', $this->getID())) . ")"; } else { $grprestrict = "='" . $this->getID() . "'"; } // include items of members if ($user) { $ufield = str_replace('groups', 'users', $field); $grprestrict = "(`{$field}` {$grprestrict}\n OR (`{$field}`=0\n AND `{$ufield}` IN (SELECT `users_id`\n FROM `glpi_groups_users`\n WHERE `groups_id` {$grprestrict})))"; } else { $grprestrict = "`{$field}` {$grprestrict}"; } // Count the total of item $nb = array(); $tot = 0; foreach ($types as $itemtype) { $nb[$itemtype] = 0; if (!($item = getItemForItemtype($itemtype))) { continue; } if (!$item->canView()) { continue; } if (!$item->isField($field)) { continue; } $restrict[$itemtype] = $grprestrict; if ($item->isEntityAssign()) { $restrict[$itemtype] .= getEntitiesRestrictRequest(" AND ", $item->getTable(), '', '', $item->maybeRecursive()); } if ($item->maybeTemplate()) { $restrict[$itemtype] .= " AND NOT `is_template`"; } if ($item->maybeDeleted()) { $restrict[$itemtype] .= " AND NOT `is_deleted`"; } $tot += $nb[$itemtype] = countElementsInTable($item->getTable(), $restrict[$itemtype]); } $max = $_SESSION['glpilist_limit']; if ($start >= $tot) { $start = 0; } $res = array(); foreach ($types as $itemtype) { if (!($item = getItemForItemtype($itemtype))) { continue; } if ($start >= $nb[$itemtype]) { // No need to read $start -= $nb[$itemtype]; } else { $query = "SELECT `id`\n FROM `" . $item->getTable() . "`\n WHERE " . $restrict[$itemtype] . "\n ORDER BY `name`\n LIMIT {$start},{$max}"; foreach ($DB->request($query) as $data) { $res[] = array('itemtype' => $itemtype, 'items_id' => $data['id']); $max--; } // For next type $start = 0; } if (!$max) { break; } } return $tot; }
/** * Make a select box with all glpi users where select key = name * * @param $options array of possible options: * - name : string / name of the select (default is users_id) * - value * - right : string / limit user who have specific right : * id -> only current user (default case); * interface -> central ; * all -> all users ; * specific right like show_all_ticket, create_ticket.... (is array passed one of all passed right is needed) * - comments : boolean / is the comments displayed near the dropdown (default true) * - entity : integer or array / restrict to a defined entity or array of entities * (default -1 : no restriction) * - entity_sons : boolean / if entity restrict specified auto select its sons * only available if entity is a single value not an array(default false) * - all : Nobody or All display for none selected * all=0 (default) -> Nobody * all=1 -> All * all=-1-> nothing * - rand : integer / already computed rand value * - toupdate : array / Update a specific item on select change on dropdown * (need value_fieldname, to_update, url * (see Ajax::updateItemOnSelectEvent for information) * and may have moreparams) * - used : array / Already used items ID: not to display in dropdown (default empty) * - ldap_import * - on_change : string / value to transmit to "onChange" * - display : boolean / display or get string (default true) * * @return rand value if displayed / string if not **/ static function dropdown($options = array()) { global $DB, $CFG_GLPI; // Default values $p['name'] = 'users_id'; $p['value'] = ''; $p['right'] = 'id'; $p['all'] = 0; $p['on_change'] = ''; $p['comments'] = 1; $p['entity'] = -1; $p['entity_sons'] = false; $p['used'] = array(); $p['ldap_import'] = false; $p['toupdate'] = ''; $p['rand'] = mt_rand(); $p['display'] = true; if (is_array($options) && count($options)) { foreach ($options as $key => $val) { $p[$key] = $val; } } $output = ''; if (!($p['entity'] < 0) && $p['entity_sons']) { if (is_array($p['entity'])) { $output .= "entity_sons options is not available with array of entity"; } else { $p['entity'] = getSonsOf('glpi_entities', $p['entity']); } } // Make a select box with all glpi users $use_ajax = false; if ($CFG_GLPI["use_ajax"]) { $res = self::getSqlSearchResult(true, $p['right'], $p['entity'], $p['value'], $p['used']); $nb = $res ? $DB->result($res, 0, "CPT") : 0; if ($nb > $CFG_GLPI["ajax_limit_count"]) { $use_ajax = true; } } $user = getUserName($p['value'], 2); $default_display = "<select id='dropdown_" . $p['name'] . $p['rand'] . "' name='" . $p['name'] . "'>"; $default_display .= "<option value='" . $p['value'] . "'>"; $default_display .= Toolbox::substr($user["name"], 0, $_SESSION["glpidropdown_chars_limit"]); $default_display .= "</option></select>"; $view_users = Session::haveRight("user", "r"); $params = array('searchText' => '__VALUE__', 'value' => $p['value'], 'myname' => $p['name'], 'all' => $p['all'], 'right' => $p['right'], 'comment' => $p['comments'], 'rand' => $p['rand'], 'on_change' => $p['on_change'], 'entity_restrict' => $p['entity'], 'used' => $p['used'], 'update_item' => $p['toupdate']); if ($view_users) { $params['update_link'] = $view_users; } $default = ""; if (!empty($p['value']) && $p['value'] > 0) { $default = $default_display; } else { $default = "<select name='" . $p['name'] . "' id='dropdown_" . $p['name'] . $p['rand'] . "'>"; if ($p['all']) { $default .= "<option value='0'>--" . __('All') . "--</option></select>"; } else { $default .= "<option value='0'>" . Dropdown::EMPTY_VALUE . "</option></select>\n"; } } $output .= Ajax::dropdown($use_ajax, "/ajax/dropdownUsers.php", $params, $default, $p['rand'], false); // Display comment if ($p['comments']) { if (!$view_users) { $user["link"] = ''; } else { if (empty($user["link"])) { $user["link"] = $CFG_GLPI['root_doc'] . "/front/user.php"; } } $output .= Html::showToolTip($user["comment"], array('contentid' => "comment_" . $p['name'] . $p['rand'], 'display' => false, 'link' => $user["link"], 'linkid' => "comment_link_" . $p["name"] . $p['rand'])); } if (Session::haveRight('import_externalauth_users', 'w') && $p['ldap_import'] && Entity::isEntityDirectoryConfigured($_SESSION['glpiactive_entity'])) { $output .= "<img alt='' title=\"" . __s('Import a user') . "\" src='" . $CFG_GLPI["root_doc"] . "/pics/add_dropdown.png' style='cursor:pointer; margin-left:2px;'\n onClick=\"var w = window.open('" . $CFG_GLPI['root_doc'] . "/front/popup.php?popup=add_ldapuser&rand=" . $p['rand'] . "&entity=" . $_SESSION['glpiactive_entity'] . "' ,'glpipopup', 'height=400, " . "width=1000, top=100, left=100, scrollbars=yes' );w.focus();\">"; } if ($p['display']) { echo $output; return $p['rand']; } return $output; }
/** * retrieve the entities associated to a user * * @param $users_id Integer ID of the user * @param $child Boolean when true, include child entity when recursive right * (false by default) * * @since version 0.85 * * @return Array of entity ID **/ static function getEntitiesForUser($users_id, $child = false) { global $DB; $query = "SELECT `entities_id`, `is_recursive`\n FROM `glpi_profiles_users`\n WHERE `users_id` = '{$users_id}'"; $entities = array(); foreach ($DB->request($query) as $data) { if ($child && $data['is_recursive']) { foreach (getSonsOf('glpi_entities', $data['entities_id']) as $id) { $entities[$id] = $id; } } else { $entities[$data['entities_id']] = $data['entities_id']; } } return $entities; }
/** * Print the HTML array for Items linked to a problem * * @param $problem Problem object * * @return Nothing (display) **/ static function showForProblem(Problem $problem) { global $DB, $CFG_GLPI; $instID = $problem->fields['id']; if (!$problem->can($instID, READ)) { return false; } $canedit = $problem->canEdit($instID); $rand = mt_rand(); $query = "SELECT DISTINCT `itemtype`\n FROM `glpi_items_problems`\n WHERE `glpi_items_problems`.`problems_id` = '{$instID}'\n ORDER BY `itemtype`"; $result = $DB->query($query); $number = $DB->numrows($result); if ($canedit) { echo "<div class='firstbloc'>"; echo "<form name='problemitem_form{$rand}' id='problemitem_form{$rand}' method='post'\n action='" . Toolbox::getItemTypeFormURL(__CLASS__) . "'>"; echo "<table class='tab_cadre_fixe'>"; echo "<tr class='tab_bg_2'><th colspan='2'>" . __('Add an item') . "</th></tr>"; echo "<tr class='tab_bg_1'><td>"; $types = array(); foreach ($problem->getAllTypesForHelpdesk() as $key => $val) { $types[] = $key; } Dropdown::showSelectItemFromItemtypes(array('itemtypes' => $types, 'entity_restrict' => $problem->fields['is_recursive'] ? getSonsOf('glpi_entities', $problem->fields['entities_id']) : $problem->fields['entities_id'])); echo "</td><td class='center' width='30%'>"; echo "<input type='submit' name='add' value=\"" . _sx('button', 'Add') . "\" class='submit'>"; echo "<input type='hidden' name='problems_id' value='{$instID}'>"; echo "</td></tr>"; echo "</table>"; Html::closeForm(); echo "</div>"; } echo "<div class='spaced'>"; if ($canedit && $number) { Html::openMassiveActionsForm('mass' . __CLASS__ . $rand); $massiveactionparams = array('container' => 'mass' . __CLASS__ . $rand); Html::showMassiveActions($massiveactionparams); } echo "<table class='tab_cadre_fixehov'>"; $header_begin = "<tr>"; $header_top = ''; $header_bottom = ''; $header_end = ''; if ($canedit && $number) { $header_top .= "<th width='10'>" . Html::getCheckAllAsCheckbox('mass' . __CLASS__ . $rand); $header_top .= "</th>"; $header_bottom .= "<th width='10'>" . Html::getCheckAllAsCheckbox('mass' . __CLASS__ . $rand); $header_bottom .= "</th>"; } $header_end .= "<th>" . __('Type') . "</th>"; $header_end .= "<th>" . __('Entity') . "</th>"; $header_end .= "<th>" . __('Name') . "</th>"; $header_end .= "<th>" . __('Serial number') . "</th>"; $header_end .= "<th>" . __('Inventory number') . "</th></tr>"; echo $header_begin . $header_top . $header_end; $totalnb = 0; for ($i = 0; $i < $number; $i++) { $itemtype = $DB->result($result, $i, "itemtype"); if (!($item = getItemForItemtype($itemtype))) { continue; } if ($item->canView()) { $itemtable = getTableForItemType($itemtype); $query = "SELECT `{$itemtable}`.*,\n `glpi_items_problems`.`id` AS IDD,\n `glpi_entities`.`id` AS entity\n FROM `glpi_items_problems`,\n `{$itemtable}`"; if ($itemtype != 'Entity') { $query .= " LEFT JOIN `glpi_entities`\n ON (`{$itemtable}`.`entities_id`=`glpi_entities`.`id`) "; } $query .= " WHERE `{$itemtable}`.`id` = `glpi_items_problems`.`items_id`\n AND `glpi_items_problems`.`itemtype` = '{$itemtype}'\n AND `glpi_items_problems`.`problems_id` = '{$instID}'"; if ($item->maybeTemplate()) { $query .= " AND `{$itemtable}`.`is_template` = '0'"; } $query .= getEntitiesRestrictRequest(" AND", $itemtable, '', '', $item->maybeRecursive()) . "\n ORDER BY `glpi_entities`.`completename`, `{$itemtable}`.`name`"; $result_linked = $DB->query($query); $nb = $DB->numrows($result_linked); for ($prem = true; $data = $DB->fetch_assoc($result_linked); $prem = false) { $name = $data["name"]; if ($_SESSION["glpiis_ids_visible"] || empty($data["name"])) { $name = sprintf(__('%1$s (%2$s)'), $name, $data["id"]); } $link = $itemtype::getFormURLWithID($data['id']); $namelink = "<a href=\"" . $link . "\">" . $name . "</a>"; echo "<tr class='tab_bg_1'>"; if ($canedit) { echo "<td width='10'>"; Html::showMassiveActionCheckBox(__CLASS__, $data["IDD"]); echo "</td>"; } if ($prem) { $typename = $item->getTypeName($nb); echo "<td class='center top' rowspan='{$nb}'>" . ($nb > 1 ? sprintf(__('%1$s: %2$s'), $typename, $nb) : $typename) . "</td>"; } echo "<td class='center'>"; echo Dropdown::getDropdownName("glpi_entities", $data['entity']) . "</td>"; echo "<td class='center" . (isset($data['is_deleted']) && $data['is_deleted'] ? " tab_bg_2_2'" : "'"); echo ">" . $namelink . "</td>"; echo "<td class='center'>" . (isset($data["serial"]) ? "" . $data["serial"] . "" : "-") . "</td>"; echo "<td class='center'>" . (isset($data["otherserial"]) ? "" . $data["otherserial"] . "" : "-") . "</td>"; echo "</tr>"; } $totalnb += $nb; } } if ($number) { echo $header_begin . $header_bottom . $header_end; } echo "</table>"; if ($canedit && $number) { $massiveactionparams['ontop'] = false; Html::showMassiveActions($massiveactionparams); Html::closeForm(); } echo "</div>"; }
/** * Make a select box with all glpi users where select key = name * * @param $options array of possible options: * - name : string / name of the select (default is users_id) * - value * - right : string / limit user who have specific right : * id -> only current user (default case); * interface -> central ; * all -> all users ; * specific right like Ticket::READALL, CREATE.... (is array passed one of all passed right is needed) * - comments : boolean / is the comments displayed near the dropdown (default true) * - entity : integer or array / restrict to a defined entity or array of entities * (default -1 : no restriction) * - entity_sons : boolean / if entity restrict specified auto select its sons * only available if entity is a single value not an array(default false) * - all : Nobody or All display for none selected * all=0 (default) -> Nobody * all=1 -> All * all=-1-> nothing * - rand : integer / already computed rand value * - toupdate : array / Update a specific item on select change on dropdown * (need value_fieldname, to_update, url * (see Ajax::updateItemOnSelectEvent for information) * and may have moreparams) * - used : array / Already used items ID: not to display in dropdown (default empty) * - ldap_import * - on_change : string / value to transmit to "onChange" * - display : boolean / display or get string (default true) * - width : specific width needed (default 80%) * - specific_tags : array of HTML5 tags to add the the field * - url : url of the ajax php code which should return the json data to show in * the dropdown (default /ajax/getDropdownUsers.php) * * @return rand value if displayed / string if not **/ static function dropdown($options = array()) { global $DB, $CFG_GLPI; // Default values $p['name'] = 'users_id'; $p['value'] = ''; $p['right'] = 'id'; $p['all'] = 0; $p['on_change'] = ''; $p['comments'] = 1; $p['width'] = '80%'; $p['entity'] = -1; $p['entity_sons'] = false; $p['used'] = array(); $p['ldap_import'] = false; $p['toupdate'] = ''; $p['rand'] = mt_rand(); $p['display'] = true; $p['_user_index'] = 0; $p['specific_tags'] = array(); $p['url'] = $CFG_GLPI['root_doc'] . "/ajax/getDropdownUsers.php"; if (is_array($options) && count($options)) { foreach ($options as $key => $val) { $p[$key] = $val; } } // check default value (in case of multiple observers) if (is_array($p['value'])) { $p['value'] = $p['value'][$p['_user_index']]; } // Check default value for dropdown : need to be a numeric if (strlen($p['value']) == 0 || !is_numeric($p['value'])) { $p['value'] = 0; } $output = ''; if (!($p['entity'] < 0) && $p['entity_sons']) { if (is_array($p['entity'])) { $output .= "entity_sons options is not available with array of entity"; } else { $p['entity'] = getSonsOf('glpi_entities', $p['entity']); } } // Make a select box with all glpi users $user = getUserName($p['value'], 2); $view_users = self::canView(); if (!empty($p['value']) && $p['value'] > 0) { $default = $user["name"]; } else { if ($p['all']) { $default = __('All'); } else { $default = Dropdown::EMPTY_VALUE; } } $field_id = Html::cleanId("dropdown_" . $p['name'] . $p['rand']); $param = array('value' => $p['value'], 'valuename' => $default, 'width' => $p['width'], 'all' => $p['all'], 'right' => $p['right'], 'on_change' => $p['on_change'], 'used' => $p['used'], 'entity_restrict' => $p['entity'], 'specific_tags' => $p['specific_tags']); $output = Html::jsAjaxDropdown($p['name'], $field_id, $p['url'], $param); // Display comment if ($p['comments']) { $comment_id = Html::cleanId("comment_" . $p['name'] . $p['rand']); $link_id = Html::cleanId("comment_link_" . $p["name"] . $p['rand']); if (!$view_users) { $user["link"] = ''; } else { if (empty($user["link"])) { $user["link"] = $CFG_GLPI['root_doc'] . "/front/user.php"; } } $output .= " " . Html::showToolTip($user["comment"], array('contentid' => $comment_id, 'display' => false, 'link' => $user["link"], 'linkid' => $link_id)); $paramscomment = array('value' => '__VALUE__', 'table' => "glpi_users"); if ($view_users) { $paramscomment['withlink'] = $link_id; } $output .= Ajax::updateItemOnSelectEvent($field_id, $comment_id, $CFG_GLPI["root_doc"] . "/ajax/comments.php", $paramscomment, false); } $output .= Ajax::commonDropdownUpdateItem($p, false); if (Session::haveRight('user', self::IMPORTEXTAUTHUSERS) && $p['ldap_import'] && Entity::isEntityDirectoryConfigured($_SESSION['glpiactive_entity'])) { $output .= "<img alt='' title=\"" . __s('Import a user') . "\" src='" . $CFG_GLPI["root_doc"] . "/pics/add_dropdown.png' style='cursor:pointer; margin-left:2px;'\n onClick=\"" . Html::jsGetElementbyID('userimport' . $p['rand']) . ".dialog('open');\">"; $output .= Ajax::createIframeModalWindow('userimport' . $p['rand'], $CFG_GLPI["root_doc"] . "/front/ldap.import.php?entity=" . $_SESSION['glpiactive_entity'], array('title' => __('Import a user'), 'display' => false)); } if ($p['display']) { echo $output; return $p['rand']; } return $output; }