Example #1
0
 static function getHistory($tickets_id, $full_history = false)
 {
     global $CFG_GLPI;
     $filter_groups_id = array();
     if ($_SESSION['plugins']['escalade']['config']['use_filter_assign_group']) {
         $groups_groups = new PluginEscaladeGroup_Group();
         $filter_groups_id = $groups_groups->getGroups($tickets_id);
         $use_filter_assign_group = true;
     } else {
         $use_filter_assign_group = false;
     }
     $plugin_dir = $full_history ? ".." : "../plugins/escalade";
     //get all line for this ticket
     $group = new Group();
     $history = new self();
     $found = $history->find("tickets_id = {$tickets_id}", "date_mod DESC");
     $nb_histories = count($found);
     //remove first line (current assign)
     $first_group = array_shift($found);
     if ($full_history) {
         //show 1st group
         echo "<div class='escalade_active'>";
         echo "&nbsp;<img src='" . $CFG_GLPI['root_doc'] . "/pics/group.png' />&nbsp;";
         if ($group->getFromDB($first_group['groups_id'])) {
             echo $group->getLink(true);
         }
         echo "</div>";
     }
     echo "<div class='escalade'>";
     //parse all lines
     $i = 0;
     foreach ($found as $key => $hline) {
         echo "<div class='escalade_history'>";
         if (!$use_filter_assign_group || isset($filter_groups_id[$hline['groups_id']])) {
             //up link and image
             echo "<a href='{$plugin_dir}/front/climb_group.php?tickets_id=" . $tickets_id . "&groups_id=" . $hline['groups_id'];
             if ($full_history) {
                 echo "&full_history=true";
             }
             echo "' title='" . __("Reassign the ticket to group", "escalade") . "' class='up_a'></a>";
         } else {
             echo "&nbsp;&nbsp;&nbsp;";
         }
         //group link
         echo "&nbsp;<img src='" . $CFG_GLPI['root_doc'] . "/pics/group.png' />&nbsp;";
         if ($group->getFromDB($hline['groups_id'])) {
             echo self::showGroupLink($group, $full_history);
         }
         echo "</div>";
         $i++;
         if ($i == self::HISTORY_LIMIT && !$full_history) {
             break;
         }
     }
     //In case there are more than 10 group changes, a popup can display historical
     if ($nb_histories - 1 > self::HISTORY_LIMIT && !$full_history) {
         echo "<a href='#' onclick='var w=window.open(\"" . $plugin_dir . "/front/popup_histories.php?tickets_id=" . $tickets_id . "\" ,\"\", \"height=500, width=250, top=100, left=100, scrollbars=yes\" ); " . "w.focus();' title='" . __("View full history", "escalade") . "'>...</a>";
     }
     echo "</div>";
 }
Example #2
0
function plugin_init_escalation()
{
    global $PLUGIN_HOOKS, $CFG_GLPI;
    $PLUGIN_HOOKS['change_profile']['escalation'] = array('PluginEscalationProfile', 'changeprofile');
    $PLUGIN_HOOKS['csrf_compliant']['escalation'] = true;
    // After escalation, if user can't see the ticket (dan't see all ticket right), it redirect to ticket list
    if (isset($_SERVER['HTTP_REFERER']) and strstr($_SERVER['HTTP_REFERER'], "escalation/front/group_group.form.php")) {
        if (isset($_GET['id'])) {
            $ticket = new Ticket();
            $ticket->getFromDB($_GET['id']);
            if (!$ticket->canViewItem()) {
                // Can't see ticket, go in ticket list
                $ticket->redirectToList();
            }
        }
    }
    if (isset($_SESSION["glpiID"])) {
        $plugin = new Plugin();
        if ($plugin->isActivated('escalation')) {
            Plugin::registerClass('PluginEscalationProfile', array('addtabon' => array('Profile')));
            Plugin::registerClass('PluginEscalationTicketCopy', array('addtabon' => array('Ticket')));
            Plugin::registerClass('PluginEscalationConfig', array('addtabon' => array('Entity')));
            Plugin::registerClass('PluginEscalationGroup_Group', array('addtabon' => array('Ticket', 'Group')));
            $PLUGIN_HOOKS['menu_entry']['escalation'] = false;
            PluginEscalationGroup_Group::convertNewTicket();
            // limit group
            $peConfig = new PluginEscalationConfig();
            if ($peConfig->getValue('limitgroup', $_SESSION['glpidefault_entity']) == '1') {
                if (strpos($_SERVER['PHP_SELF'], "ticket.form.php") && !isset($_GET['id'])) {
                    $group = new Group();
                    $a_groups = array();
                    $a_groups[0] = Dropdown::EMPTY_VALUE;
                    foreach ($_SESSION['glpigroups'] as $groups_id) {
                        $group->getFromDB($groups_id);
                        $a_groups[$groups_id] = $group->getName();
                    }
                    $_SESSION['plugin_escalation_requestergroups'] = $a_groups;
                    register_shutdown_function('plugin_escalation_on_exit');
                    ob_start();
                }
            }
            // end limit group
        }
        $PLUGIN_HOOKS['pre_item_add']['escalation'] = array('Ticket' => array('PluginEscalationGroup_Group', 'selectGroupOnAdd'));
        $PLUGIN_HOOKS['item_add']['escalation'] = array('Ticket' => array('PluginEscalationTicketCopy', 'finishAdd'));
        //         $PLUGIN_HOOKS['pre_item_update']['escalation'] = array('Ticket' => array('PluginEscalationGroup_Group', 'notMultiple'));
    }
}
Example #3
0
 static function pdfForGroup(PluginPdfSimplePDF $pdf, Group $group, $tree)
 {
     global $DB, $CFG_GLPI;
     $used = array();
     $ids = array();
     // Retrieve member list
     $entityrestrict = Group_User::getDataForGroup($group, $used, $ids, '', $tree);
     $title = "<b>" . sprintf(__('%1$s (%2$s)'), _n('User', 'Users', 2) . "</b>", __('D=Dynamic'));
     $number = count($used);
     if ($number > $_SESSION['glpilist_limit']) {
         $title = sprintf(__('%1$s (%2$s)'), $title, $_SESSION['glpilist_limit'] . "/" . $number);
     } else {
         $title = sprintf(__('%1$s (%2$s)'), $title, $number);
     }
     $pdf->setColumnsSize(100);
     $pdf->displayTitle($title);
     if ($number) {
         $user = new User();
         $group = new Group();
         if ($tree) {
             $pdf->setColumnsSize(35, 45, 10, 10);
             $pdf->displayTitle(User::getTypeName(1), Group::getTypeName(1), __('Manager'), __('Delegatee'));
         } else {
             $pdf->setColumnsSize(60, 20, 20);
             $pdf->displayTitle(User::getTypeName(1), __('Manager'), __('Delegatee'));
         }
         for ($i = 0; $i < $number && $i < $_SESSION['glpilist_limit']; $i++) {
             $data = $used[$i];
             $name = Html::clean(getUserName($data["id"]));
             if ($data["is_dynamic"]) {
                 $name = sprintf(__('%1$s (%2$s)'), $name, '<b>' . __('D') . '</b>');
             }
             if ($tree) {
                 $group->getFromDB($data["groups_id"]);
                 $pdf->displayLine($name, $group->getName(), Dropdown::getYesNo($data['is_manager']), Dropdown::getYesNo($data['is_userdelegate']));
             } else {
                 $pdf->displayLine($name, Dropdown::getYesNo($data['is_manager']), Dropdown::getYesNo($data['is_userdelegate']));
             }
         }
     } else {
         $pdf->setColumnsAlign('center');
         $pdf->displayLine(__('No item found'));
     }
     $pdf->displaySpace();
 }
 function showContacts($itemtype, $items_id)
 {
     global $DB, $LANG, $CFG_GLPI;
     $this->addContact($itemtype, $items_id);
     $group = new Group();
     $user = new User();
     $rand = mt_rand();
     echo "<form method='post' name='contact_item_form{$rand}' id='contact_item_form{$rand}' action=\"" . $CFG_GLPI["root_doc"] . "/plugins/monitoring/front/contact_item.form.php\">";
     echo "<table class='tab_cadre_fixe'>";
     echo "<tr>";
     echo "<th>";
     echo $LANG['plugin_monitoring']['contact'][20];
     echo "</th>";
     echo "</tr>";
     echo "</table>";
     echo "<table class='tab_cadre_fixe'>";
     echo "<tr>";
     echo "<th width='10'>&nbsp;</th>";
     echo "<th>" . $LANG['common'][35] . " - " . $LANG['common'][16] . "</th>";
     echo "<th colspan='3'></th>";
     echo "</tr>";
     $used = array();
     // Display groups first
     $query = "SELECT * FROM `" . $this->getTable() . "`\n         WHERE `items_id`='" . $items_id . "'\n            AND `itemtype`='" . $itemtype . "'\n            AND `groups_id` > 0";
     $result = $DB->query($query);
     while ($data = $DB->fetch_array($result)) {
         $group->getFromDB($data['groups_id']);
         echo "<tr>";
         echo "<td>";
         echo "<input type='checkbox' name='item[" . $data["id"] . "]' value='1'>";
         echo "</td>";
         echo "<td class='center'>";
         echo $group->getLink(1);
         echo "</td>";
         echo "<td colspan='3'>";
         echo "</td>";
         echo "</tr>";
     }
     echo "<tr>";
     echo "<th width='10'>&nbsp;</th>";
     echo "<th>" . $LANG['common'][34] . " - " . $LANG['common'][16] . "</th>";
     echo "<th>" . $LANG['entity'][0] . "</th>";
     echo "<th>" . $LANG['setup'][14] . "</th>";
     echo "<th>" . $LANG['help'][35] . "</th>";
     echo "</tr>";
     $entity = new Entity();
     $used = array();
     // Display Users
     $query = "SELECT * FROM `" . $this->getTable() . "`\n         WHERE `items_id`='" . $items_id . "'\n            AND `itemtype`='" . $itemtype . "'\n            AND `users_id` > 0";
     $result = $DB->query($query);
     while ($data = $DB->fetch_array($result)) {
         $user->getFromDB($data['users_id']);
         echo "<tr>";
         echo "<td>";
         echo "<input type='checkbox' name='item[" . $data["id"] . "]' value='1'>";
         echo "</td>";
         echo "<td class='center'>";
         echo $user->getLink(1);
         echo "</td>";
         $entity->getFromDB($data['entities_id']);
         echo "<td class='center'>";
         echo $entity->getName() . " <strong>(R)</strong>";
         echo "</td>";
         echo "<td class='center'>";
         echo $user->fields['email'];
         echo "</td>";
         echo "<td class='center'>";
         echo $user->fields['phone'];
         echo "</td>";
         echo "</tr>";
     }
     openArrowMassive("contact_item_form{$rand}", true);
     closeArrowMassive('deleteitem', $LANG['buttons'][6]);
     echo "</table>";
 }
Example #5
0
 function generateServicesCfg($file = 0, $tag = '')
 {
     global $DB;
     $pMonitoringCommand = new PluginMonitoringCommand();
     $pmEventhandler = new PluginMonitoringEventhandler();
     $pMonitoringCheck = new PluginMonitoringCheck();
     $pmComponent = new PluginMonitoringComponent();
     $pmEntity = new PluginMonitoringEntity();
     $pmContact_Item = new PluginMonitoringContact_Item();
     $pmService = new PluginMonitoringService();
     $pmComponentscatalog = new PluginMonitoringComponentscatalog();
     $calendar = new Calendar();
     $user = new User();
     $pmLog = new PluginMonitoringLog();
     $profile_User = new Profile_User();
     if (isset($_SERVER['HTTP_USER_AGENT']) and strstr($_SERVER['HTTP_USER_AGENT'], 'xmlrpclib.py')) {
         if (!isset($_SESSION['glpi_currenttime'])) {
             $_SESSION['glpi_currenttime'] = date("Y-m-d H:i:s");
         }
         $input = array();
         $input['user_name'] = "Shinken";
         $input['action'] = "restart";
         $input['date_mod'] = date("Y-m-d H:i:s");
         $pmLog->add($input);
     }
     $hostnamebp = '';
     $a_services = array();
     $i = 0;
     // * Prepare contacts
     $a_contacts_entities = array();
     $a_list_contact = $pmContact_Item->find("`itemtype`='PluginMonitoringComponentscatalog'\n         AND `users_id`>0");
     foreach ($a_list_contact as $data) {
         $contactentities = getSonsOf('glpi_entities', $data['entities_id']);
         if (isset($a_contacts_entities[$data['items_id']][$data['users_id']])) {
             $contactentities = array_merge($contactentities, $a_contacts_entities[$data['items_id']][$data['users_id']]);
         }
         $a_contacts_entities[$data['items_id']][$data['users_id']] = $contactentities;
     }
     // Groups
     $group = new Group();
     $a_list_contact = $pmContact_Item->find("`itemtype`='PluginMonitoringComponentscatalog'\n         AND `groups_id`>0");
     foreach ($a_list_contact as $data) {
         $group->getFromDB($data['groups_id']);
         if ($group->fields['is_recursive'] == 1) {
             $contactentities = getSonsOf('glpi_entities', $group->fields['entities_id']);
         } else {
             $contactentities = array($group->fields['entities_id'] => $group->fields['entities_id']);
         }
         $queryg = "SELECT * FROM `glpi_groups_users`\n            WHERE `groups_id`='" . $data['groups_id'] . "'";
         $resultg = $DB->query($queryg);
         while ($datag = $DB->fetch_array($resultg)) {
             if (isset($a_contacts_entities[$data['items_id']][$datag['users_id']])) {
                 $contactentities = array_merge($contactentities, $a_contacts_entities[$data['items_id']][$datag['users_id']]);
             }
             $a_contacts_entities[$data['items_id']][$datag['users_id']] = $contactentities;
         }
     }
     $a_entities_allowed = $pmEntity->getEntitiesByTag($tag);
     $query = "SELECT * FROM `glpi_plugin_monitoring_services`";
     $result = $DB->query($query);
     while ($data = $DB->fetch_array($result)) {
         $notadd = 0;
         $notadddescription = '';
         $a_component = current($pmComponent->find("`id`='" . $data['plugin_monitoring_components_id'] . "'", "", 1));
         $a_hostname = array();
         $queryh = "SELECT * FROM `glpi_plugin_monitoring_componentscatalogs_hosts` \n            WHERE `id` = '" . $data['plugin_monitoring_componentscatalogs_hosts_id'] . "'\n            LIMIT 1";
         $resulth = $DB->query($queryh);
         $hostname = '';
         $plugin_monitoring_componentscatalogs_id = 0;
         while ($datah = $DB->fetch_array($resulth)) {
             $itemtype = $datah['itemtype'];
             $item = new $itemtype();
             if ($item->getFromDB($datah['items_id'])) {
                 if (isset($a_entities_allowed['-1']) or isset($a_entities_allowed[$item->fields['entities_id']])) {
                     $a_hostname[] = $itemtype . "-" . $datah['items_id'] . "-" . preg_replace("/[^A-Za-z0-9]/", "", $item->fields['name']);
                     $hostname = $item->fields['name'];
                     $plugin_monitoring_componentscatalogs_id = $datah['plugin_monitoring_componentscalalog_id'];
                 }
             }
         }
         if (count($a_hostname) > 0) {
             if (isset($_SESSION['plugin_monitoring']['servicetemplates'][$a_component['id']])) {
                 $a_services[$i]['use'] = $_SESSION['plugin_monitoring']['servicetemplates'][$a_component['id']];
             }
             $a_services[$i]['host_name'] = implode(",", array_unique($a_hostname));
             $hostnamebp = $a_services[$i]['host_name'];
             // For business rules
             $a_services[$i]['service_description'] = preg_replace("/[^A-Za-z0-9]/", "", $a_component['name']) . "-" . $data['id'];
             $pMonitoringCommand->getFromDB($a_component['plugin_monitoring_commands_id']);
             // Manage arguments
             $array = array();
             preg_match_all("/\\\$(ARG\\d+)\\\$/", $pMonitoringCommand->fields['command_line'], $array);
             sort($array[0]);
             $a_arguments = importArrayFromDB($a_component['arguments']);
             $a_argumentscustom = importArrayFromDB($data['arguments']);
             foreach ($a_argumentscustom as $key => $value) {
                 $a_arguments[$key] = $value;
             }
             $args = '';
             foreach ($array[0] as $arg) {
                 if ($arg != '$PLUGINSDIR$' and $arg != '$HOSTADDRESS$' and $arg != '$MYSQLUSER$' and $arg != '$MYSQLPASSWORD$') {
                     $arg = str_replace('$', '', $arg);
                     if (!isset($a_arguments[$arg])) {
                         $args .= '!';
                     } else {
                         if (strstr($a_arguments[$arg], "[[HOSTNAME]]")) {
                             $a_arguments[$arg] = str_replace("[[HOSTNAME]]", $hostname, $a_arguments[$arg]);
                         } elseif (strstr($a_arguments[$arg], "[[NETWORKPORTDESCR]]")) {
                             if (class_exists("PluginFusioninventoryNetworkPort")) {
                                 $pfNetworkPort = new PluginFusioninventoryNetworkPort();
                                 $pfNetworkPort->loadNetworkport($data['networkports_id']);
                                 $descr = $pfNetworkPort->getValue("ifdescr");
                                 $a_arguments[$arg] = str_replace("[[NETWORKPORTDESCR]]", $descr, $a_arguments[$arg]);
                             }
                         } elseif (strstr($a_arguments[$arg], "[[NETWORKPORTNUM]]")) {
                             $networkPort = new NetworkPort();
                             $networkPort->getFromDB($data['networkports_id']);
                             $logicalnum = $pfNetworkPort->fields['logical_number'];
                             $a_arguments[$arg] = str_replace("[[NETWORKPORTNUM]]", $logicalnum, $a_arguments[$arg]);
                         } elseif (strstr($a_arguments[$arg], "[[NETWORKPORTNAME]]")) {
                             $networkPort = new NetworkPort();
                             $networkPort->getFromDB($data['networkports_id']);
                             $portname = $pfNetworkPort->fields['name'];
                             $a_arguments[$arg] = str_replace("[[NETWORKPORTNAME]]", $portname, $a_arguments[$arg]);
                         } else {
                             if (strstr($a_arguments[$arg], "[")) {
                                 $a_arguments[$arg] = PluginMonitoringService::convertArgument($data['id'], $a_arguments[$arg]);
                             }
                         }
                         if ($a_arguments == '') {
                             $notadd = 1;
                             if ($notadddescription != '') {
                                 $notadddescription .= ", ";
                             }
                             $notadddescription .= "Argument " . $a_arguments[$arg] . " Not have value";
                         }
                         $args .= '!' . $a_arguments[$arg];
                         if ($a_arguments[$arg] == '' and $a_component['alias_command'] != '') {
                             $args .= $a_component['alias_command'];
                         }
                     }
                 }
             }
             // End manage arguments
             if ($a_component['remotesystem'] == 'nrpe') {
                 if ($a_component['alias_command'] != '') {
                     $alias_command = $a_component['alias_command'];
                     if (strstr($alias_command, '[[IP]]')) {
                         $split = explode('-', current($a_hostname));
                         $ip = PluginMonitoringHostaddress::getIp($split[1], $split[0], '');
                         $alias_command = str_replace("[[IP]]", $ip, $alias_command);
                     }
                     $a_services[$i]['check_command'] = "check_nrpe!" . $alias_command;
                 } else {
                     $a_services[$i]['check_command'] = "check_nrpe!" . $pMonitoringCommand->fields['command_name'];
                 }
             } else {
                 $a_services[$i]['check_command'] = $pMonitoringCommand->fields['command_name'] . $args;
             }
             // * Manage event handler
             if ($a_component['plugin_monitoring_eventhandlers_id'] > 0) {
                 if ($pmEventhandler->getFromDB($a_component['plugin_monitoring_eventhandlers_id'])) {
                     $a_services[$i]['event_handler'] = $pmEventhandler->fields['command_name'];
                 }
             }
             // * Contacts
             $a_contacts = array();
             $a_list_contact = $pmContact_Item->find("`itemtype`='PluginMonitoringComponentscatalog'\n                  AND `items_id`='" . $plugin_monitoring_componentscatalogs_id . "'");
             foreach ($a_list_contact as $data_contact) {
                 if ($data_contact['users_id'] > 0) {
                     if (isset($a_contacts_entities[$plugin_monitoring_componentscatalogs_id][$data_contact['users_id']])) {
                         if (in_array($data['entities_id'], $a_contacts_entities[$plugin_monitoring_componentscatalogs_id][$data_contact['users_id']])) {
                             $user->getFromDB($data_contact['users_id']);
                             $a_contacts[] = $user->fields['name'];
                         }
                     }
                 } else {
                     if ($data_contact['groups_id'] > 0) {
                         $queryg = "SELECT * FROM `glpi_groups_users`\n                        WHERE `groups_id`='" . $data_contact['groups_id'] . "'";
                         $resultg = $DB->query($queryg);
                         while ($datag = $DB->fetch_array($resultg)) {
                             if (in_array($data['entities_id'], $a_contacts_entities[$plugin_monitoring_componentscatalogs_id][$datag['users_id']])) {
                                 $user->getFromDB($datag['users_id']);
                                 $a_contacts[] = $user->fields['name'];
                             }
                         }
                     }
                 }
             }
             $a_contacts_unique = array_unique($a_contacts);
             $a_services[$i]['contacts'] = implode(',', $a_contacts_unique);
             // ** If shinken not use templates or template not defined :
             if (!isset($_SESSION['plugin_monitoring']['servicetemplates'][$a_component['id']])) {
                 $pMonitoringCheck->getFromDB($a_component['plugin_monitoring_checks_id']);
                 $a_services[$i]['check_interval'] = $pMonitoringCheck->fields['check_interval'];
                 $a_services[$i]['retry_interval'] = $pMonitoringCheck->fields['retry_interval'];
                 $a_services[$i]['max_check_attempts'] = $pMonitoringCheck->fields['max_check_attempts'];
                 if ($calendar->getFromDB($a_component['calendars_id'])) {
                     $a_services[$i]['check_period'] = $calendar->fields['name'];
                 }
                 $a_services[$i]['notification_interval'] = '30';
                 if ($calendar->getFromDB($a_component['calendars_id'])) {
                     $a_services[$i]['notification_period'] = $calendar->fields['name'];
                 } else {
                     $a_services[$i]['notification_period'] = "24x7";
                 }
                 $a_services[$i]['notification_options'] = 'w,c,r';
                 $a_services[$i]['active_checks_enabled'] = '1';
                 $a_services[$i]['process_perf_data'] = '1';
                 $a_services[$i]['active_checks_enabled'] = '1';
                 $a_services[$i]['passive_checks_enabled'] = '1';
                 $a_services[$i]['parallelize_check'] = '1';
                 $a_services[$i]['obsess_over_service'] = '1';
                 $a_services[$i]['check_freshness'] = '1';
                 $a_services[$i]['freshness_threshold'] = '1';
                 $a_services[$i]['notifications_enabled'] = '1';
                 if (isset($a_services[$i]['event_handler'])) {
                     $a_services[$i]['event_handler_enabled'] = '1';
                 } else {
                     $a_services[$i]['event_handler_enabled'] = '0';
                     $a_services[$i]['event_handler_enabled'] = '';
                 }
                 $a_services[$i]['flap_detection_enabled'] = '1';
                 $a_services[$i]['failure_prediction_enabled'] = '1';
                 $a_services[$i]['retain_status_information'] = '1';
                 $a_services[$i]['retain_nonstatus_information'] = '1';
                 $a_services[$i]['is_volatile'] = '0';
                 $a_services[$i]['_httpstink'] = 'NO';
             }
             $pmComponentscatalog->getFromDB($plugin_monitoring_componentscatalogs_id);
             if ($pmComponentscatalog->fields['notification_interval'] != '30') {
                 $a_services[$i]['notification_interval'] = $pmComponentscatalog->fields['notification_interval'];
             }
             if ($notadd == '1') {
                 unset($a_services[$i]);
                 $input = array();
                 $input['id'] = $data['id'];
                 $input['event'] = $notadddescription;
                 $input['state'] = "CRITICAL";
                 $input['state_type'] = "HARD";
                 $pmService->update($input);
             } else {
                 $i++;
             }
         }
     }
     //      // Business rules....
     $pmService = new PluginMonitoringService();
     $pmServicescatalog = new PluginMonitoringServicescatalog();
     $pMonitoringBusinessrulegroup = new PluginMonitoringBusinessrulegroup();
     $pmBusinessrule = new PluginMonitoringBusinessrule();
     $pmComponentscatalog_Host = new PluginMonitoringComponentscatalog_Host();
     $a_listBA = $pmServicescatalog->find();
     foreach ($a_listBA as $dataBA) {
         if (isset($a_entities_allowed['-1']) or isset($a_entities_allowed[$dataBA['entities_id']])) {
             $a_grouplist = $pMonitoringBusinessrulegroup->find("`plugin_monitoring_servicescatalogs_id`='" . $dataBA['id'] . "'");
             $a_group = array();
             foreach ($a_grouplist as $gdata) {
                 $a_listBR = $pmBusinessrule->find("`plugin_monitoring_businessrulegroups_id`='" . $gdata['id'] . "'");
                 foreach ($a_listBR as $dataBR) {
                     if ($pmService->getFromDB($dataBR['plugin_monitoring_services_id'])) {
                         $pmComponentscatalog_Host->getFromDB($pmService->fields['plugin_monitoring_componentscatalogs_hosts_id']);
                         $itemtype = $pmComponentscatalog_Host->fields['itemtype'];
                         $item = new $itemtype();
                         if ($item->getFromDB($pmComponentscatalog_Host->fields['items_id'])) {
                             $hostname = $itemtype . "-" . $pmComponentscatalog_Host->fields['items_id'] . "-" . preg_replace("/[^A-Za-z0-9]/", "", $item->fields['name']);
                             if ($gdata['operator'] == 'and' or $gdata['operator'] == 'or' or strstr($gdata['operator'], ' of:')) {
                                 $operator = '|';
                                 if ($gdata['operator'] == 'and') {
                                     $operator = '&';
                                 }
                                 if (!isset($a_group[$gdata['id']])) {
                                     $a_group[$gdata['id']] = '';
                                     if (strstr($gdata['operator'], ' of:')) {
                                         $a_group[$gdata['id']] = $gdata['operator'];
                                     }
                                     $a_group[$gdata['id']] .= $hostname . "," . preg_replace("/[^A-Za-z0-9]/", "", $pmService->fields['name']) . "-" . $pmService->fields['id'];
                                 } else {
                                     $a_group[$gdata['id']] .= $operator . $hostname . "," . preg_replace("/[^A-Za-z0-9]/", "", $pmService->fields['name']) . "-" . $pmService->fields['id'];
                                 }
                             } else {
                                 $a_group[$gdata['id']] = $gdata['operator'] . " " . $hostname . "," . preg_replace("/[^A-Za-z0-9]/", "", $item->getName()) . "-" . $item->fields['id'];
                             }
                         }
                     }
                 }
             }
             if (count($a_group) > 0) {
                 $pMonitoringCheck->getFromDB($dataBA['plugin_monitoring_checks_id']);
                 $a_services[$i]['check_interval'] = $pMonitoringCheck->fields['check_interval'];
                 $a_services[$i]['retry_interval'] = $pMonitoringCheck->fields['retry_interval'];
                 $a_services[$i]['max_check_attempts'] = $pMonitoringCheck->fields['max_check_attempts'];
                 if ($calendar->getFromDB($dataBA['calendars_id'])) {
                     $a_services[$i]['check_period'] = $calendar->fields['name'];
                 }
                 $a_services[$i]['host_name'] = $hostnamebp;
                 $a_services[$i]['service_description'] = preg_replace("/[^A-Za-z0-9]/", "", $dataBA['name']) . "-" . $dataBA['id'] . "-businessrules";
                 $command = "bp_rule!";
                 foreach ($a_group as $key => $value) {
                     if (!strstr($value, "&") and !strstr($value, "|")) {
                         $a_group[$key] = trim($value);
                     } else {
                         $a_group[$key] = "(" . trim($value) . ")";
                     }
                 }
                 $a_services[$i]['check_command'] = $command . implode("&", $a_group);
                 $a_services[$i]['notification_interval'] = '30';
                 if ($calendar->getFromDB($dataBA['calendars_id'])) {
                     $a_services[$i]['notification_period'] = $calendar->fields['name'];
                 } else {
                     $a_services[$i]['notification_period'] = "24x7";
                 }
                 $a_services[$i]['notification_options'] = 'w,c,r';
                 $a_services[$i]['active_checks_enabled'] = '1';
                 $a_services[$i]['process_perf_data'] = '1';
                 $a_services[$i]['active_checks_enabled'] = '1';
                 $a_services[$i]['passive_checks_enabled'] = '1';
                 $a_services[$i]['parallelize_check'] = '1';
                 $a_services[$i]['obsess_over_service'] = '1';
                 $a_services[$i]['check_freshness'] = '1';
                 $a_services[$i]['freshness_threshold'] = '1';
                 $a_services[$i]['notifications_enabled'] = '1';
                 $a_services[$i]['event_handler_enabled'] = '0';
                 //$a_services[$i]['event_handler'] = 'super_event_kill_everyone!DIE';
                 $a_services[$i]['flap_detection_enabled'] = '1';
                 $a_services[$i]['failure_prediction_enabled'] = '1';
                 $a_services[$i]['retain_status_information'] = '1';
                 $a_services[$i]['retain_nonstatus_information'] = '1';
                 $a_services[$i]['is_volatile'] = '0';
                 $a_services[$i]['_httpstink'] = 'NO';
                 $a_services[$i]['contacts'] = '';
                 $i++;
             }
         }
     }
     if ($file == "1") {
         $config = "# Generated by plugin monitoring for GLPI\n# on " . date("Y-m-d H:i:s") . "\n\n";
         foreach ($a_services as $data) {
             $config .= $this->constructFile("service", $data);
         }
         return array('services.cfg', $config);
     } else {
         return $a_services;
     }
 }
 /**
  * show groups asociated
  *
  * @param $type      integer : user type
  * @param $canedit   boolean : can edit ?
  * @param $options   array    options for default values ($options of showForm)
  *
  * @return nothing display
  **/
 function showGroupsAssociated($type, $canedit, array $options = array())
 {
     global $CFG_GLPI;
     $groupicon = self::getActorIcon('group', $type);
     $group = new Group();
     $linkclass = new $this->grouplinkclass();
     $itemtype = $this->getType();
     $typename = self::getActorFieldNameType($type);
     $candelete = true;
     $mandatory = '';
     // For ticket templates : mandatories
     if ($itemtype == 'Ticket' && isset($options['_tickettemplate'])) {
         $mandatory = $options['_tickettemplate']->getMandatoryMark("_groups_id_" . $typename);
         if ($options['_tickettemplate']->isMandatoryField("_groups_id_" . $typename) && isset($this->groups[$type]) && count($this->groups[$type]) == 1) {
             $candelete = false;
         }
     }
     if (isset($this->groups[$type]) && count($this->groups[$type])) {
         foreach ($this->groups[$type] as $d) {
             $k = $d['groups_id'];
             echo "{$mandatory}{$groupicon}&nbsp;";
             if ($group->getFromDB($k)) {
                 echo $group->getLink(array('comments' => true));
             }
             if ($canedit && $candelete) {
                 echo "&nbsp;";
                 Html::showSimpleForm($linkclass->getFormURL(), 'delete', _x('button', 'Delete permanently'), array('id' => $d['id']), $CFG_GLPI["root_doc"] . "/pics/delete.png");
             }
             echo '<br>';
         }
     }
 }
Example #7
0
 /**
  * Show items for the group
  *
  * @param $tech   boolean  false search groups_id, true, search groups_id_tech
  **/
 function showItems($tech)
 {
     global $DB, $CFG_GLPI;
     $rand = mt_rand();
     $ID = $this->fields['id'];
     if ($tech) {
         $types = $CFG_GLPI['linkgroup_tech_types'];
         $field = 'groups_id_tech';
         $title = __('Managed items');
     } else {
         $types = $CFG_GLPI['linkgroup_types'];
         $field = 'groups_id';
         $title = __('Used items');
     }
     $tree = Session::getSavedOption(__CLASS__, 'tree', 0);
     $user = Session::getSavedOption(__CLASS__, 'user', 0);
     $type = Session::getSavedOption(__CLASS__, 'onlytype', '');
     if (!in_array($type, $types)) {
         $type = '';
     }
     echo "<div class='spaced'>";
     // Mini Search engine
     echo "<table class='tab_cadre_fixe'>";
     echo "<tr class='tab_bg_1'><th colspan='3'>{$title}</tr>";
     echo "<tr class='tab_bg_1'><td class='center'>";
     echo __('Type') . "&nbsp;";
     Dropdown::showItemType($types, array('value' => $type, 'name' => 'onlytype', 'plural' => true, 'on_change' => 'reloadTab("start=0&onlytype="+this.value)', 'checkright' => true));
     if ($this->haveChildren()) {
         echo "</td><td class='center'>" . __('Child groups') . "&nbsp;";
         Dropdown::showYesNo('tree', $tree, -1, array('on_change' => 'reloadTab("start=0&tree="+this.value)'));
     } else {
         $tree = 0;
     }
     if ($this->getField('is_usergroup')) {
         echo "</td><td class='center'>" . User::getTypeName(Session::getPluralNumber()) . "&nbsp;";
         Dropdown::showYesNo('user', $user, -1, array('on_change' => 'reloadTab("start=0&user="******"</td></tr></table>";
     $datas = array();
     if ($type) {
         $types = array($type);
     }
     $start = isset($_GET['start']) ? intval($_GET['start']) : 0;
     $nb = $this->getDataItems($types, $field, $tree, $user, $start, $datas);
     $nbcan = 0;
     if ($nb) {
         Html::printAjaxPager('', $start, $nb);
         Html::openMassiveActionsForm('mass' . __CLASS__ . $rand);
         echo Html::hidden('field', array('value' => $field, 'data-glpicore-ma-tags' => 'common'));
         $massiveactionparams = array('num_displayed' => $nb, 'check_itemtype' => 'Group', 'check_items_id' => $ID, 'container' => 'mass' . __CLASS__ . $rand, 'extraparams' => array('is_tech' => $tech, 'massive_action_fields' => array('field')), 'specific_actions' => array(__CLASS__ . MassiveAction::CLASS_ACTION_SEPARATOR . 'changegroup' => __('Move')));
         Html::showMassiveActions($massiveactionparams);
         echo "<table class='tab_cadre_fixehov'>";
         $header_begin = "<tr><th width='10'>";
         $header_top = Html::getCheckAllAsCheckbox('mass' . __CLASS__ . $rand);
         $header_bottom = Html::getCheckAllAsCheckbox('mass' . __CLASS__ . $rand);
         $header_end = '</th>';
         $header_end .= "<th>" . __('Type') . "</th><th>" . __('Name') . "</th><th>" . __('Entity') . "</th>";
         if ($tree || $user) {
             $header_end .= "<th>" . sprintf(__('%1$s / %2$s'), self::getTypeName(1), User::getTypeName(1)) . "</th>";
         }
         $header_end .= "</tr>";
         echo $header_begin . $header_top . $header_end;
         $tuser = new User();
         $group = new Group();
         foreach ($datas as $data) {
             if (!($item = getItemForItemtype($data['itemtype']))) {
                 continue;
             }
             echo "<tr class='tab_bg_1'><td>";
             if ($item->canEdit($data['items_id'])) {
                 Html::showMassiveActionCheckBox($data['itemtype'], $data['items_id']);
             }
             echo "</td><td>" . $item->getTypeName(1);
             echo "</td><td>" . $item->getLink(array('comments' => true));
             echo "</td><td>" . Dropdown::getDropdownName("glpi_entities", $item->getEntityID());
             if ($tree || $user) {
                 echo "</td><td>";
                 if ($grp = $item->getField($field)) {
                     if ($group->getFromDB($grp)) {
                         echo $group->getLink(array('comments' => true));
                     }
                 } else {
                     if ($usr = $item->getField(str_replace('groups', 'users', $field))) {
                         if ($tuser->getFromDB($usr)) {
                             echo $tuser->getLink(array('comments' => true));
                         }
                     }
                 }
             }
             echo "</td></tr>";
         }
         echo $header_begin . $header_bottom . $header_end;
         echo "</table>";
     } else {
         echo "<p class='center b'>" . __('No item found') . "</p>";
     }
     if ($nb) {
         $massiveactionparams['ontop'] = false;
         Html::showMassiveActions($massiveactionparams);
     }
     Html::closeForm();
     if ($nb) {
         Html::printAjaxPager('', $start, $nb);
     }
     echo "</div>";
 }
Example #8
0
 function getGroups($ticket_id, $removeAlreadyAssigned = true)
 {
     $groups = $user_groups = $ticket_groups = array();
     // get groups for user connected
     $tmp_user_groups = Group_User::getUserGroups($_SESSION['glpiID']);
     foreach ($tmp_user_groups as $current_group) {
         $user_groups[$current_group['id']] = $current_group['id'];
         $groups[$current_group['id']] = $current_group['id'];
     }
     // get groups already assigned in the ticket
     if ($ticket_id > 0) {
         $ticket = new Ticket();
         $ticket->getFromDB($ticket_id);
         foreach ($ticket->getGroups(CommonITILActor::ASSIGN) as $current_group) {
             $ticket_groups[$current_group['groups_id']] = $current_group['groups_id'];
         }
     }
     // To do an escalation, the user must be in a group currently assigned to the ticket
     // or no group is assigned to the ticket
     // TODO : matching with "view all tickets (yes/no) option in profile user"
     if (!empty($ticket_groups) && count(array_intersect($ticket_groups, $user_groups)) == 0) {
         return array();
     }
     //get all group which we can climb
     if (count($groups) > 0) {
         $group_group = $this->find("groups_id_source IN (" . implode(", ", $groups) . ")");
         foreach ($group_group as $current_group) {
             $groups[$current_group['groups_id_destination']] = $current_group['groups_id_destination'];
         }
     }
     //remove already assigned groups
     if (!empty($ticket_groups) && $removeAlreadyAssigned) {
         $groups = array_diff_assoc($groups, $ticket_groups);
     }
     //add name to returned groups and remove non assignable groups
     $group_obj = new Group();
     foreach ($groups as $groups_id => &$groupname) {
         $group_obj->getFromDB($groups_id);
         //check if we can assign this group
         if ($group_obj->fields['is_assign'] == 0) {
             unset($groups[$groups_id]);
             continue;
         }
         //add name
         $groupname = $group_obj->fields['name'];
     }
     //sort by group name (and keep associative index)
     asort($groups);
     return $groups;
 }
Example #9
0
 static function pdfItems(PluginPdfSimplePDF $pdf, Group $group, $tech, $tree, $user)
 {
     global $CFG_GLPI;
     if ($tech) {
         $types = $CFG_GLPI['linkgroup_tech_types'];
         $field = 'groups_id_tech';
         $title = __('Managed items');
     } else {
         $types = $CFG_GLPI['linkgroup_types'];
         $field = 'groups_id';
         $title = __('Used items');
     }
     $datas = array();
     $max = $group->getDataItems($types, $field, $tree, $user, 0, $datas);
     $nb = count($datas);
     if ($nb < $max) {
         $title = sprintf(__('%1$s (%2$s)'), $title, $nb / $max);
     } else {
         $title = sprintf(__('%1$s (%2$s)'), $title, $nb);
     }
     $pdf->setColumnsSize(100);
     $pdf->displayTitle($title);
     if ($nb) {
         if ($tree || $user) {
             $pdf->setColumnsSize(16, 20, 34, 30);
             $pdf->displayTitle(__('Type'), __('Name'), __('Entity'), Group::getTypeName(1) . " / " . User::getTypeName(1));
         } else {
             $pdf->setColumnsSize(20, 25, 55);
             $pdf->displayTitle(__('Type'), __('Name'), __('Entity'));
         }
     } else {
         $pdf->displayLine(__('No item found'));
     }
     $tmpgrp = new Group();
     $tmpusr = new User();
     foreach ($datas as $data) {
         if (!($item = getItemForItemtype($data['itemtype']))) {
             continue;
         }
         $item->getFromDB($data['items_id']);
         $col4 = '';
         if ($tree || $user) {
             if ($grp = $item->getField($field)) {
                 if ($tmpgrp->getFromDB($grp)) {
                     $col4 = $tmpgrp->getNameID();
                 }
             } else {
                 if ($usr = $item->getField(str_replace('groups', 'users', $field))) {
                     $col4 = Html::clean(getUserName($usr));
                 }
             }
         }
         $pdf->displayLine($item->getTypeName(1), $item->getName(), Html::clean(Dropdown::getDropdownName("glpi_entities", $item->getEntityID())), $col4);
     }
     $pdf->displaySpace();
 }
   function showContacts($itemtype, $items_id) {
      global $DB,$CFG_GLPI;

      $this->addContact($itemtype, $items_id);

      $group = new Group();
      $user  = new User();

      $rand = mt_rand();

      echo "<form method='post' name='contact_item_form$rand' id='contact_item_form$rand' action=\"".
                $CFG_GLPI["root_doc"]."/plugins/monitoring/front/contact_item.form.php\">";

      echo "<table class='tab_cadre_fixe'>";

      echo "<tr>";
      echo "<th>";
      echo __('Contacts', 'monitoring');
      echo "</th>";
      echo "</tr>";

      echo "</table>";

      echo "<table class='tab_cadre_fixe'>";

      echo "<tr>";
      echo "<th width='10'>&nbsp;</th>";
      echo "<th>".__('Group')." - ".__('Name')."</th>";
      echo "<th colspan='3'></th>";
      echo "</tr>";

      $used = array();
      // Display groups first
      $query = "SELECT * FROM `".$this->getTable()."`
         WHERE `items_id`='".$items_id."'
            AND `itemtype`='".$itemtype."'
            AND `groups_id` > 0";
      $result = $DB->query($query);
      while ($data=$DB->fetch_array($result)) {
         $group->getFromDB($data['groups_id']);

         echo "<tr>";
         echo "<td>";
         echo "<input type='checkbox' name='item[".$data["id"]."]' value='1'>";
         echo "</td>";
         echo "<td class='center'>";
         echo $group->getLink(1);
         echo "</td>";
         echo "<td colspan='3'>";

         echo "</td>";

         echo "</tr>";
      }

      echo "<tr>";
      echo "<th width='10'>&nbsp;</th>";
      echo "<th>".__('User')." - ".__('Name')."</th>";
      echo "<th>".__('Entity')."</th>";
      echo "<th>".__('Email address')."</th>";
      echo "<th>".__('Phone')."</th>";
      echo "</tr>";

      $entity = new Entity();
      $used = array();
      // Display Users
      $query = "SELECT * FROM `".$this->getTable()."`
         WHERE `items_id`='".$items_id."'
            AND `itemtype`='".$itemtype."'
            AND `users_id` > 0";
      $result = $DB->query($query);
      while ($data=$DB->fetch_array($result)) {
         $user->getFromDB($data['users_id']);

         echo "<tr>";
         echo "<td>";
         echo "<input type='checkbox' name='item[".$data["id"]."]' value='1'>";
         echo "</td>";
         echo "<td class='center'>";
         echo $user->getLink(1);
         echo "</td>";
         $entity->getFromDB($data['entities_id']);
         echo "<td class='center'>";
         echo $entity->getName()." <strong>(R)</strong>";
         echo "</td>";
         echo "<td class='center'>";
         $a_emails = UserEmail::getAllForUser($data['users_id']);
         $first = 0;
         foreach ($a_emails as $email) {
            if ($first == 0) {
               echo $email;
            }
            $first++;
         }
         echo "</td>";
         echo "<td class='center'>";
         echo $user->fields['phone'];
         echo "</td>";

         echo "</tr>";
      }

      Html::openArrowMassives("contact_item_form$rand", true);
      Html::closeArrowMassives(array('deleteitem' => _sx('button', 'Delete permanently')));
      Html::closeForm();
      echo "</table>";

   }
Example #11
0
function plugin_timelineticket_giveItem($type, $ID, $data, $num)
{
    global $CFG_GLPI, $DB;
    $searchopt =& Search::getOptions($type);
    $table = $searchopt[$ID]["table"];
    $field = $searchopt[$ID]["field"];
    switch ($table . '.' . $field) {
        case "glpi_plugin_timelineticket_grouplevels.groups":
            if (empty($data["ITEM_{$num}"])) {
                $out = __('None');
            } else {
                $out = "";
                $groups = json_decode($data["ITEM_{$num}"], true);
                if (!empty($groups)) {
                    foreach ($groups as $key => $val) {
                        $out .= Dropdown::getDropdownName("glpi_groups", $val) . "<br>";
                    }
                }
            }
            return $out;
            break;
        case "glpi_plugin_timelineticket_assigngroups.groups_id":
            $ptAssignGroup = new PluginTimelineticketAssignGroup();
            $group = new Group();
            $ticket = new Ticket();
            $out = "";
            $a_out = array();
            $a_groupname = array();
            if (!isset($data["ITEM_{$num}"]) or !strstr($data["ITEM_{$num}"], '$$')) {
                return "";
            }
            $splitg = explode("\$\$\$\$", $data["ITEM_{$num}"]);
            foreach ($splitg as $datag) {
                $split = explode("\$\$", $datag);
                $group->getFromDB($split[0]);
                $ptAssignGroup->getFromDB($split[1]);
                $time = $ptAssignGroup->fields['delay'];
                if ($ptAssignGroup->fields['delay'] === NULL) {
                    $ticket->getFromDB($data["ITEM_0"]);
                    $calendar = new Calendar();
                    $calendars_id = Entity::getUsedConfig('calendars_id', $ticket->fields['entities_id']);
                    $datedebut = $ptAssignGroup->fields['date'];
                    $enddate = $_SESSION["glpi_currenttime"];
                    if ($ticket->fields['status'] == Ticket::CLOSED) {
                        $enddate = $ticket->fields['closedate'];
                    }
                    if ($calendars_id > 0 && $calendar->getFromDB($calendars_id)) {
                        $time = $calendar->getActiveTimeBetween($datedebut, $enddate);
                    } else {
                        // cas 24/24 - 7/7
                        $time = strtotime($enddate) - strtotime($datedebut);
                    }
                } else {
                    if ($ptAssignGroup->fields['delay'] == 0) {
                        $time = 0;
                    }
                }
                $a_groupname[$group->fields['id']] = $group->getLink();
                if (isset($a_out[$group->fields['id']])) {
                    $a_out[$group->fields['id']] += $time;
                } else {
                    $a_out[$group->fields['id']] = $time;
                }
            }
            $a_out_comp = array();
            foreach ($a_out as $groups_id => $time) {
                $a_out_comp[] = $a_groupname[$groups_id] . " : " . Html::timestampToString($time, TRUE, FALSE);
            }
            $out = implode("<hr/>", $a_out_comp);
            return $out;
            break;
    }
    return "";
}
Example #12
0
 /**
  *  remove old groups to a ticket when a new group assigned
  *  called by "pre_item_add" hook on Group_Ticket object
  * @param CommonDBTM $item the ticket object
  */
 static function addHistoryOnAddGroup(CommonDBTM $item)
 {
     global $DB;
     if ($_SESSION['plugins']['escalade']['config']['remove_group'] == false) {
         return true;
     }
     //if group sent is not an assign group, return
     if ($item->input['type'] != CommonITILActor::ASSIGN) {
         return;
     }
     $tickets_id = $item->input['tickets_id'];
     $groups_id = $item->input['groups_id'];
     //if group already assigned, return
     $group_ticket = new Group_Ticket();
     $condition = "tickets_id = {$tickets_id} AND groups_id = {$groups_id} AND type = 2";
     if ($group_ticket->find($condition)) {
         unset($_SESSION['plugin_escalade']['keep_users']);
         return;
     }
     $item->fields['status'] = CommonITILObject::ASSIGNED;
     //add line in history table
     $history = new PluginEscaladeHistory();
     $history->add(array('tickets_id' => $tickets_id, 'groups_id' => $groups_id));
     //remove old user(s) (pass if user added by new ticket form)
     $backtrace = debug_backtrace();
     $first_trace = array_pop($backtrace);
     if (strpos($first_trace['file'], 'ticket.form.php') === false || $first_trace['function'] != "add" || !$first_trace['object'] instanceof Ticket) {
         self::removeAssignUsers($tickets_id);
     }
     //add a task to inform the escalation (pass if solution)
     if (isset($_SESSION['plugin_escalade']['solution'])) {
         unset($_SESSION['plugin_escalade']['solution']);
         return $item;
     }
     if ($_SESSION['plugins']['escalade']['config']['task_history']) {
         $group = new Group();
         $group->getFromDB($groups_id);
         $task = new TicketTask();
         $task->add(array('tickets_id' => $tickets_id, 'is_private' => true, 'state' => 0, 'content' => __("escalated to the group", "escalade") . " " . $group->getName()));
     }
     //check if event is not triggered by behaviors plugin
     //to prevent user remove when "add technician group" option is active
     if (strpos($first_trace['file'], 'ticket.form.php') !== false && $first_trace['function'] == "add" && $first_trace['object'] instanceof Ticket) {
         return;
     }
     if ($_SESSION['plugins']['escalade']['config']['ticket_last_status'] != -1) {
         $ticket = new Ticket();
         $ticket->update(array('id' => $tickets_id, 'status' => $_SESSION['plugins']['escalade']['config']['ticket_last_status']));
     }
     return $item;
 }
 static function showGrupos(CommonDBTM $item, $withtemplate = '')
 {
     global $DB, $CFG_GLPI;
     $objeto = $item->getType();
     $appli = new $objeto();
     $ID = $item->fields['id'];
     $appli->getFromDB($item->fields['id']);
     //$canedit = $appli->can($appli->fields['id'],'w');
     $canedit = $appli->canCreate();
     //$canedit = Session::haveRight('update_ticket', 1);
     $rand = mt_rand();
     $groups = self::getFormGroups($ID);
     $used = array();
     if (!empty($groups)) {
         foreach ($groups as $data) {
             $used[$data["id"]] = $data["id"];
         }
     }
     echo "<div class='center'>";
     echo "<form name='form_grupo' id='form_grupo' method='post' action='../front/formgroup.form.php'>";
     echo "<table class='tab_cadre_fixe'>";
     echo "<th colspan=2>" . __('Grupos', 'Grupos') . "</th>";
     echo "<tr>";
     echo "<th>" . __('Grupo', 'Grupo') . "&nbsp;:" . "</th>";
     echo "<td>";
     if ($canedit) {
         Group::dropdown(array('name' => 'groups_id', 'entity' => $_SESSION['glpiactive_entity'], 'condition' => '`is_assign`'));
     }
     echo "</td>";
     //-----------------------------
     echo "</tr>";
     echo "<tr class='tab_bg_1'>";
     echo "<td colspan='2' align = 'center'>";
     echo "<input type='submit' name='agregarGrupo' value='Agregar' class='submit'>";
     echo "</td></tr>";
     echo "</table>";
     echo "<input type='hidden' name='itemtype' value='Group'>";
     echo "<input type='hidden' name='peticion_id' value='" . $item->fields['id'] . "'>";
     //echo "</form>";
     Html::closeForm();
     echo "</div>";
     // Listado de Grupos
     echo "<div class='spaced'>";
     /*
           if ($canedit && count($used)) {
              $rand = mt_rand();
              Html::openMassiveActionsForm('mass'.__CLASS__.$rand);
              echo "<input type='hidden' name='plugin_formcreator_forms_id' value='".$item->fields['id']."'>";
              $massiveactionparams = array('num_displayed' => count($used),
                                'container'     => 'mass'.__CLASS__.$rand);
              Html::showMassiveActions($massiveactionparams);
           }*/
     if ($canedit && $withtemplate < 2) {
         Html::openMassiveActionsForm('mass' . __CLASS__ . $rand);
         $massiveactionparams = array('num_displayed' => count($used));
         Html::showMassiveActions($massiveactionparams);
     }
     echo "<table class='tab_cadre_fixehov'>";
     $header_begin = "<tr>";
     $header_top = '';
     $header_bottom = '';
     $header_end = '';
     if ($canedit && count($used)) {
         $header_begin .= "<th width='10'>";
         $header_top .= Html::getCheckAllAsCheckbox('mass' . __CLASS__ . $rand);
         $header_bottom .= Html::getCheckAllAsCheckbox('mass' . __CLASS__ . $rand);
         $header_end .= "</th>";
     }
     $header_end .= "<th>" . Group::getTypeName(1) . "</th>";
     echo $header_begin . $header_top . $header_end;
     $group = new Group();
     if (!empty($groups)) {
         Session::initNavigateListItems('PluginFormcreatorForm', sprintf(__('%1$s = %2$s'), $item::getTypeName(1), $item->getName()));
         foreach ($groups as $data) {
             if (!$group->getFromDB($data["id"])) {
                 continue;
             }
             Session::addToNavigateListItems('PluginFormcreatorForm', $data["id"]);
             echo "<tr class='tab_bg_1'>";
             if ($canedit && count($used)) {
                 echo "<td width='10'>";
                 // echo __CLASS__;
                 Html::showMassiveActionCheckBox('PluginFormcreatorForm_Item', $data["linkID"]);
                 echo "</td>";
             }
             $link = $data["completename"];
             if ($_SESSION["glpiis_ids_visible"]) {
                 $link = sprintf(__('%1$s (%2$s)'), $link, $data["id"]);
             }
             $href = "<a href='" . $CFG_GLPI["root_doc"] . "/front/group.form.php?id=" . $data["id"] . "'>" . $link . "</a>";
             echo "<td>" . $group->getLink() . "</td>";
             echo "</tr>";
         }
         echo $header_begin . $header_bottom . $header_end;
     } else {
         echo "<tr class='tab_bg_1'>";
         echo "<td colspan='5' class='center'>" . __('None') . "</td></tr>";
     }
     echo "</table>";
     if ($canedit && count($used)) {
         $massiveactionparams['ontop'] = false;
         Html::showMassiveActions($massiveactionparams);
         Html::closeForm();
     }
     echo "</div>";
 }
 function prepareRun($taskjobs_id)
 {
     global $DB;
     $task = new PluginFusioninventoryTask();
     $job = new PluginFusioninventoryTaskjob();
     $joblog = new PluginFusioninventoryTaskjoblog();
     $jobstate = new PluginFusioninventoryTaskjobstate();
     $agent = new PluginFusioninventoryAgent();
     $uniqid = uniqid();
     $job->getFromDB($taskjobs_id);
     $task->getFromDB($job->fields['plugin_fusioninventory_tasks_id']);
     $communication = $task->fields['communication'];
     $actions = importArrayFromDB($job->fields['action']);
     $definitions = importArrayFromDB($job->fields['definition']);
     $taskvalid = 0;
     $computers = array();
     foreach ($actions as $action) {
         $itemtype = key($action);
         $items_id = current($action);
         switch ($itemtype) {
             case 'Computer':
                 $computers[] = $items_id;
                 break;
             case 'Group':
                 $computer_object = new Computer();
                 //find computers by user associated with this group
                 $group_users = new Group_User();
                 $group = new Group();
                 $group->getFromDB($items_id);
                 $members = array();
                 $computers_a_1 = array();
                 $computers_a_2 = array();
                 //array_keys($group_users->find("groups_id = '$items_id'"));
                 $members = $group_users->getGroupUsers($items_id);
                 foreach ($members as $member) {
                     $computers = $computer_object->find("users_id = '{$member['id']}'");
                     foreach ($computers as $computer) {
                         $computers_a_1[] = $computer['id'];
                     }
                 }
                 //find computers directly associated with this group
                 $computers = $computer_object->find("groups_id = '{$items_id}'");
                 foreach ($computers as $computer) {
                     $computers_a_2[] = $computer['id'];
                 }
                 //merge two previous array and deduplicate entries
                 $computers = array_unique(array_merge($computers_a_1, $computers_a_2));
                 break;
             case 'PluginFusioninventoryDeployGroup':
                 $group = new PluginFusioninventoryDeployGroup();
                 $group->getFromDB($items_id);
                 switch ($group->getField('type')) {
                     case 'STATIC':
                         $query = "SELECT items_id\n                     FROM glpi_plugin_fusioninventory_deploygroups_staticdatas\n                     WHERE groups_id = '{$items_id}'\n                     AND itemtype = 'Computer'";
                         $res = $DB->query($query);
                         while ($row = $DB->fetch_assoc($res)) {
                             $computers[] = $row['items_id'];
                         }
                         break;
                     case 'DYNAMIC':
                         $query = "SELECT fields_array\n                     FROM glpi_plugin_fusioninventory_deploygroups_dynamicdatas\n                     WHERE groups_id = '{$items_id}'\n                     LIMIT 1";
                         $res = $DB->query($query);
                         $row = $DB->fetch_assoc($res);
                         if (isset($_GET)) {
                             $get_tmp = $_GET;
                         }
                         if (isset($_SESSION["glpisearchcount"]['Computer'])) {
                             unset($_SESSION["glpisearchcount"]['Computer']);
                         }
                         if (isset($_SESSION["glpisearchcount2"]['Computer'])) {
                             unset($_SESSION["glpisearchcount2"]['Computer']);
                         }
                         $_GET = importArrayFromDB($row['fields_array']);
                         $_GET["glpisearchcount"] = count($_GET['field']);
                         if (isset($_GET['field2'])) {
                             $_GET["glpisearchcount2"] = count($_GET['field2']);
                         }
                         $pfSearch = new PluginFusioninventorySearch();
                         Search::manageGetValues('Computer');
                         $glpilist_limit = $_SESSION['glpilist_limit'];
                         $_SESSION['glpilist_limit'] = 999999999;
                         $result = $pfSearch->constructSQL('Computer', $_GET);
                         $_SESSION['glpilist_limit'] = $glpilist_limit;
                         while ($data = $DB->fetch_array($result)) {
                             $computers[] = $data['id'];
                         }
                         if (count($get_tmp) > 0) {
                             $_GET = $get_tmp;
                         }
                         break;
                 }
                 break;
         }
     }
     $c_input = array();
     $c_input['plugin_fusioninventory_taskjobs_id'] = $taskjobs_id;
     $c_input['state'] = 0;
     $c_input['plugin_fusioninventory_agents_id'] = 0;
     $c_input['execution_id'] = $task->fields['execution_id'];
     $pfCollect = new PluginFusioninventoryCollect();
     foreach ($computers as $computer_id) {
         //get agent if for this computer
         $agents_id = $agent->getAgentWithComputerid($computer_id);
         if ($agents_id === FALSE) {
             $jobstates_id = $jobstate->add($c_input);
             $jobstate->changeStatusFinish($jobstates_id, 0, '', 1, "No agent found for [[Computer::" . $computer_id . "]]", 0, 0);
         } else {
             foreach ($definitions as $definition) {
                 $pfCollect->getFromDB($definition['PluginFusioninventoryCollect']);
                 switch ($pfCollect->fields['type']) {
                     case 'registry':
                         // get all registry
                         $pfCollect_Registry = new PluginFusioninventoryCollect_Registry();
                         $a_registries = $pfCollect_Registry->find("`plugin_fusioninventory_collects_id`='" . $pfCollect->fields['id'] . "'");
                         foreach ($a_registries as $data_r) {
                             $uniqid = uniqid();
                             $c_input['state'] = 0;
                             $c_input['itemtype'] = 'PluginFusioninventoryCollect_Registry';
                             $c_input['items_id'] = $data_r['id'];
                             $c_input['date'] = date("Y-m-d H:i:s");
                             $c_input['uniqid'] = $uniqid;
                             $c_input['plugin_fusioninventory_agents_id'] = $agents_id;
                             # Push the agent, in the stack of agent to awake
                             if ($communication == "push") {
                                 $_SESSION['glpi_plugin_fusioninventory']['agents'][$agents_id] = 1;
                             }
                             $jobstates_id = $jobstate->add($c_input);
                             //Add log of taskjob
                             $c_input['plugin_fusioninventory_taskjobstates_id'] = $jobstates_id;
                             $c_input['state'] = PluginFusioninventoryTaskjoblog::TASK_PREPARED;
                             $taskvalid++;
                             $joblog->add($c_input);
                         }
                         break;
                     case 'wmi':
                         // get all wmi
                         $pfCollect_Wmi = new PluginFusioninventoryCollect_Wmi();
                         $a_wmies = $pfCollect_Wmi->find("`plugin_fusioninventory_collects_id`='" . $pfCollect->fields['id'] . "'");
                         foreach ($a_wmies as $data_r) {
                             $uniqid = uniqid();
                             $c_input['state'] = 0;
                             $c_input['itemtype'] = 'PluginFusioninventoryCollect_Wmi';
                             $c_input['items_id'] = $data_r['id'];
                             $c_input['date'] = date("Y-m-d H:i:s");
                             $c_input['uniqid'] = $uniqid;
                             $c_input['plugin_fusioninventory_agents_id'] = $agents_id;
                             # Push the agent, in the stack of agent to awake
                             if ($communication == "push") {
                                 $_SESSION['glpi_plugin_fusioninventory']['agents'][$agents_id] = 1;
                             }
                             $jobstates_id = $jobstate->add($c_input);
                             //Add log of taskjob
                             $c_input['plugin_fusioninventory_taskjobstates_id'] = $jobstates_id;
                             $c_input['state'] = PluginFusioninventoryTaskjoblog::TASK_PREPARED;
                             $taskvalid++;
                             $joblog->add($c_input);
                         }
                         break;
                     case 'file':
                         // find files
                         $pfCollect_File = new PluginFusioninventoryCollect_File();
                         $a_files = $pfCollect_File->find("`plugin_fusioninventory_collects_id`='" . $pfCollect->fields['id'] . "'");
                         foreach ($a_files as $data_r) {
                             $uniqid = uniqid();
                             $c_input['state'] = 0;
                             $c_input['itemtype'] = 'PluginFusioninventoryCollect_File';
                             $c_input['items_id'] = $data_r['id'];
                             $c_input['date'] = date("Y-m-d H:i:s");
                             $c_input['uniqid'] = $uniqid;
                             $c_input['plugin_fusioninventory_agents_id'] = $agents_id;
                             # Push the agent, in the stack of agent to awake
                             if ($communication == "push") {
                                 $_SESSION['glpi_plugin_fusioninventory']['agents'][$agents_id] = 1;
                             }
                             $jobstates_id = $jobstate->add($c_input);
                             //Add log of taskjob
                             $c_input['plugin_fusioninventory_taskjobstates_id'] = $jobstates_id;
                             $c_input['state'] = PluginFusioninventoryTaskjoblog::TASK_PREPARED;
                             $taskvalid++;
                             $joblog->add($c_input);
                         }
                         break;
                 }
             }
         }
     }
     if ($taskvalid > 0) {
         $job->fields['status'] = 1;
         $job->update($job->fields);
     } else {
         $job->reinitializeTaskjobs($job->fields['plugin_fusioninventory_tasks_id']);
     }
 }
Example #15
0
 /**
  * show groups asociated
  *
  * @param $type      integer : user type
  * @param $canedit   boolean : can edit ?
  *
  * @return nothing display
  **/
 function showGroupsAssociated($type, $canedit)
 {
     global $CFG_GLPI;
     $groupicon = self::getActorIcon('group', $type);
     $group = new Group();
     if (isset($this->groups[$type]) && count($this->groups[$type])) {
         foreach ($this->groups[$type] as $d) {
             $k = $d['groups_id'];
             echo "{$groupicon}&nbsp;";
             if ($group->getFromDB($k)) {
                 echo $group->getLink(array('comments' => true));
             }
             if ($canedit) {
                 echo "&nbsp;";
                 Html::showSimpleForm($this->getFormURL(), 'delete_group', _x('button', 'Delete permanently'), array('id' => $d['id'], $this->getForeignKeyField() => $this->fields['id']), $CFG_GLPI["root_doc"] . "/pics/delete.png");
             }
             echo '<br>';
         }
     }
 }
Example #16
0
 /**
  * Display a single line of planning filter.
  * See self::showPlanningFilter function
  *
  * @param $filter_key  : identify curent line of filter
  * @param $filter_data : array of filter date, must contains :
  *   * 'show_delete' (boolean): show delete button
  *   * 'filter_color_index' (integer): index of the color to use in self::$palette_bg
  * @param $options
  *
  * @return Nothing (display function)
  */
 static function showSingleLinePlanningFilter($filter_key, $filter_data, $options = array())
 {
     global $CFG_GLPI;
     $params['show_delete'] = true;
     $params['filter_color_index'] = 0;
     if (is_array($options) && count($options)) {
         foreach ($options as $key => $val) {
             $params[$key] = $val;
         }
     }
     $actor = explode('_', $filter_key);
     $uID = 0;
     $gID = 0;
     if ($filter_data['type'] == 'user') {
         $uID = $actor[1];
         $user = new User();
         $user->getFromDB($actor[1]);
         $title = $user->getName();
     } else {
         if ($filter_data['type'] == 'group_users') {
             $group = new Group();
             $group->getFromDB($actor[1]);
             $title = $group->getName();
         } else {
             if ($filter_data['type'] == 'group') {
                 $gID = $actor[1];
                 $group = new Group();
                 $group->getFromDB($actor[1]);
                 $title = $group->getName();
             } else {
                 if ($filter_data['type'] == 'event_filter') {
                     $title = $filter_key::getTypeName();
                 }
             }
         }
     }
     echo "<li event_type='" . $filter_data['type'] . "'\n               event_name='{$filter_key}'\n               class='" . $filter_data['type'] . "'>";
     Html::showCheckbox(array('name' => 'filters[]', 'value' => $filter_key, 'title' => $title, 'checked' => $filter_data['display']));
     if ($filter_data['type'] != 'event_filter') {
         $icon_type = explode('_', $filter_data['type']);
         echo "<img class='actor_icon' src='" . $CFG_GLPI['root_doc'] . "/pics/" . $icon_type[0] . ".png'>";
     }
     echo "<label for='{$filter_key}'>{$title}</label>";
     $color = self::$palette_bg[$params['filter_color_index']];
     if (isset($filter_data['color']) && !empty($filter_data['color'])) {
         $color = $filter_data['color'];
     } else {
         $params['filter_color_index']++;
         if (!isset(self::$palette_bg[$params['filter_color_index']])) {
             $params['filter_color_index'] = 0;
             $color = self::$palette_bg[$params['filter_color_index']];
         }
     }
     if ($filter_data['type'] != 'event_filter') {
         echo "<span class='filter_option'>";
         echo "<img class='pointer' src='" . $CFG_GLPI['root_doc'] . "/pics/down.png' />";
         echo "<ul>";
         if ($params['show_delete']) {
             echo "<li class='delete_planning' value='{$filter_key}'>" . __("Delete") . "</li>";
         }
         if ($filter_data['type'] != 'group_users') {
             $url = parse_url($CFG_GLPI["url_base"]);
             $port = 80;
             if (isset($url['port'])) {
                 $port = $url['port'];
             } else {
                 if (isset($url['scheme']) && $url["scheme"] == 'https') {
                     $port = 443;
                 }
             }
             $cal_url = "/front/planning.php?genical=1&uID=" . $uID . "&gID=" . $gID . "&entities_id=" . $_SESSION["glpiactive_entity"] . "&is_recursive=" . $_SESSION["glpiactive_entity_recursive"] . "&token=" . User::getPersonalToken(Session::getLoginUserID(true));
             echo "<li><a target='_blank' href='" . $CFG_GLPI["root_doc"] . "{$cal_url}'>" . _sx("button", "Export") . " - " . __("Ical") . "</a></li>";
             echo "<li><a target='_blank' href='webcal://" . $url['host'] . ":{$port}" . (isset($url['path']) ? $url['path'] : '') . "{$cal_url}'>" . _sx("button", "Export") . " - " . __("Webcal") . "</a></li>";
         }
         echo "</ul>";
         echo "</span>";
     }
     // colors not for groups
     if ($filter_data['type'] != 'group_users') {
         echo "<span class='color_input'>";
         Html::showColorField($filter_key . "_color", array('value' => $color));
         echo "</span>";
     }
     if ($filter_data['type'] == 'group_users') {
         echo "<span class='toggle pointer' />";
     }
     if ($filter_data['type'] == 'group_users') {
         echo "<ul class='group_listofusers filters'>";
         foreach ($filter_data['users'] as $user_key => $userdata) {
             self::showSingleLinePlanningFilter($user_key, $userdata, array('show_delete' => false, 'filter_color_index' => $params['filter_color_index']));
         }
         echo "</ul>";
     }
     echo "</li>";
 }
 function prepareRun($taskjob_id, $definitions_filter = NULL)
 {
     global $DB;
     $task = new PluginFusioninventoryTask();
     $job = new PluginFusioninventoryTaskjob();
     $joblog = new PluginFusioninventoryTaskjoblog();
     $jobstate = new PluginFusioninventoryTaskjobstate();
     $agent = new PluginFusioninventoryAgent();
     $agentmodule = new PluginFusioninventoryAgentmodule();
     $job->getFromDB($taskjob_id);
     $task->getFromDB($job->fields['plugin_fusioninventory_tasks_id']);
     $communication = $task->fields['communication'];
     $actions = importArrayFromDB($job->fields['action']);
     $definitions = importArrayFromDB($job->fields['definition']);
     $taskvalid = 0;
     $computers = array();
     foreach ($actions as $action) {
         $itemtype = key($action);
         $items_id = current($action);
         switch ($itemtype) {
             case 'Computer':
                 if ($this->definitionFiltered("Computer", $definitions_filter)) {
                     break;
                 }
                 $computers[] = $items_id;
                 break;
             case 'Group':
                 if ($this->definitionFiltered("Group", $definitions_filter)) {
                     break;
                 }
                 $computer_object = new Computer();
                 //find computers by user associated with this group
                 $group_users = new Group_User();
                 $group = new Group();
                 $group->getFromDB($items_id);
                 $members = array();
                 $computers_a_1 = array();
                 $computers_a_2 = array();
                 //array_keys($group_users->find("groups_id = '$items_id'"));
                 $members = $group_users->getGroupUsers($items_id);
                 foreach ($members as $member) {
                     $computers = $computer_object->find("users_id = '{$member['id']}' " . " AND `is_deleted`='0' AND `is_template`='0'");
                     foreach ($computers as $computer) {
                         $computers_a_1[] = $computer['id'];
                     }
                 }
                 //find computers directly associated with this group
                 $computers = $computer_object->find("groups_id = '{$items_id}' " . " AND `is_deleted`='0' AND `is_template`='0'");
                 foreach ($computers as $computer) {
                     $computers_a_2[] = $computer['id'];
                 }
                 //merge two previous array and deduplicate entries
                 $computers = array_unique(array_merge($computers_a_1, $computers_a_2));
                 break;
             case 'PluginFusioninventoryDeployGroup':
                 $group = new PluginFusioninventoryDeployGroup();
                 $group->getFromDB($items_id);
                 switch ($group->getField('type')) {
                     case 'STATIC':
                         if ($this->definitionFiltered("PluginFusioninventoryDeployGroupStatic", $definitions_filter)) {
                             break;
                         }
                         $query = "SELECT items_id\n                     FROM glpi_plugin_fusioninventory_deploygroups_staticdatas\n                     WHERE groups_id = '{$items_id}'\n                     AND itemtype = 'Computer'";
                         $res = $DB->query($query);
                         while ($row = $DB->fetch_assoc($res)) {
                             $computers[] = $row['items_id'];
                         }
                         break;
                     case 'DYNAMIC':
                         if ($this->definitionFiltered("PluginFusioninventoryDeployGroupDynamic", $definitions_filter)) {
                             break;
                         }
                         //$definitions_filter is NULL = update by crontask !
                         if ($definitions_filter != NULL) {
                             $where = " AND `can_update_group`='1'";
                         } else {
                             $where = "";
                         }
                         $query = "SELECT fields_array\n                     FROM glpi_plugin_fusioninventory_deploygroups_dynamicdatas\n                     WHERE groups_id = '{$items_id}' {$where}\n                     LIMIT 1";
                         $res = $DB->query($query);
                         $row = $DB->fetch_assoc($res);
                         //No dynamic groups have been found : break
                         if ($DB->numrows($res) == 0) {
                             break;
                         }
                         if (isset($_GET)) {
                             $get_tmp = $_GET;
                         }
                         if (isset($_SESSION["glpisearchcount"]['Computer'])) {
                             unset($_SESSION["glpisearchcount"]['Computer']);
                         }
                         if (isset($_SESSION["glpisearchcount2"]['Computer'])) {
                             unset($_SESSION["glpisearchcount2"]['Computer']);
                         }
                         $_GET = importArrayFromDB($row['fields_array']);
                         $_GET["glpisearchcount"] = count($_GET['field']);
                         if (isset($_GET['field2'])) {
                             $_GET["glpisearchcount2"] = count($_GET['field2']);
                         }
                         $pfSearch = new PluginFusioninventorySearch();
                         Search::manageParams('Computer');
                         $glpilist_limit = $_SESSION['glpilist_limit'];
                         $_SESSION['glpilist_limit'] = 999999999;
                         $result = $pfSearch->constructSQL('Computer', $_GET);
                         $_SESSION['glpilist_limit'] = $glpilist_limit;
                         while ($data = $DB->fetch_array($result)) {
                             $computers[] = $data['id'];
                         }
                         if (count($get_tmp) > 0) {
                             $_GET = $get_tmp;
                         }
                         break;
                 }
                 break;
         }
     }
     //Remove duplicatas from array
     //We are using isset for faster processing than array_unique because we might have many
     //entries in this list.
     $tmp_computers = array();
     foreach ($computers as $computer) {
         if (!isset($tmp_computers[$computer])) {
             $tmp_computers[$computer] = 1;
         }
     }
     $computers = array_keys($tmp_computers);
     $c_input = array();
     $c_input['plugin_fusioninventory_taskjobs_id'] = $job->fields['id'];
     $c_input['state'] = 0;
     $c_input['plugin_fusioninventory_agents_id'] = 0;
     $c_input['execution_id'] = $task->fields['execution_id'];
     $package = new PluginFusioninventoryDeployPackage();
     foreach ($computers as $computer_id) {
         //Unique Id match taskjobstatuses for an agent(computer)
         foreach ($definitions as $definition) {
             $uniqid = uniqid();
             $package->getFromDB($definition['PluginFusioninventoryDeployPackage']);
             $c_input['state'] = 0;
             $c_input['itemtype'] = 'PluginFusioninventoryDeployPackage';
             $c_input['items_id'] = $package->fields['id'];
             $c_input['date'] = date("Y-m-d H:i:s");
             $c_input['uniqid'] = $uniqid;
             //get agent for this computer
             $agents_id = $agent->getAgentWithComputerid($computer_id);
             if ($agents_id === FALSE) {
                 $jobstates_id = $jobstate->add($c_input);
                 $jobstate->changeStatusFinish($jobstates_id, 0, '', 1, "No agent found for [[Computer::" . $computer_id . "]]", 0, 0);
             } else {
                 if ($agentmodule->isAgentCanDo('DEPLOY', $agents_id)) {
                     $c_input['plugin_fusioninventory_agents_id'] = $agents_id;
                     $jobstates_running = $jobstate->find(implode(" ", array("    `itemtype` = 'PluginFusioninventoryDeployPackage'", "AND `items_id` = " . $package->fields['id'], "AND `state` <> " . PluginFusioninventoryTaskjobstate::FINISHED, "AND `plugin_fusioninventory_agents_id` = " . $agents_id)));
                     if (count($jobstates_running) == 0) {
                         # Push the agent, in the stack of agent to awake
                         if ($communication == "push") {
                             $_SESSION['glpi_plugin_fusioninventory']['agents'][$agents_id] = 1;
                         }
                         $jobstates_id = $jobstate->add($c_input);
                         //Add log of taskjob
                         $c_input['plugin_fusioninventory_taskjobstates_id'] = $jobstates_id;
                         $c_input['state'] = PluginFusioninventoryTaskjoblog::TASK_PREPARED;
                         $taskvalid++;
                         $joblog->add($c_input);
                         unset($c_input['state']);
                         unset($c_input['plugin_fusioninventory_agents_id']);
                     }
                 }
             }
         }
     }
     if ($taskvalid > 0) {
         $job->fields['status'] = 1;
         $job->update($job->fields);
     } else {
         $job->reinitializeTaskjobs($job->fields['plugin_fusioninventory_tasks_id']);
     }
 }
 /**
  * Show users of a group
  *
  * @since version 0.83
  *
  * @param $group  Group object: the group
  **/
 static function showForGroup(Group $group)
 {
     global $DB, $CFG_GLPI;
     $ID = $group->getID();
     if (!User::canView() || !$group->can($ID, READ)) {
         return false;
     }
     // Have right to manage members
     $canedit = self::canUpdate();
     $rand = mt_rand();
     $user = new User();
     $crit = Session::getSavedOption(__CLASS__, 'criterion', '');
     $tree = Session::getSavedOption(__CLASS__, 'tree', 0);
     $used = array();
     $ids = array();
     // Retrieve member list
     $entityrestrict = self::getDataForGroup($group, $used, $ids, $crit, $tree);
     if ($canedit) {
         self::showAddUserForm($group, $ids, $entityrestrict, $crit);
     }
     // Mini Search engine
     echo "<table class='tab_cadre_fixe'>";
     echo "<tr class='tab_bg_1'><th colspan='2'>" . User::getTypeName(Session::getPluralNumber()) . "</th></tr>";
     echo "<tr class='tab_bg_1'><td class='center'>";
     echo _n('Criterion', 'Criteria', 1) . "&nbsp;";
     $crits = array('' => Dropdown::EMPTY_VALUE, 'is_manager' => __('Manager'), 'is_userdelegate' => __('Delegatee'));
     Dropdown::showFromArray('crit', $crits, array('value' => $crit, 'on_change' => 'reloadTab("start=0&criterion="+this.value)'));
     if ($group->haveChildren()) {
         echo "</td><td class='center'>" . __('Child groups');
         Dropdown::showYesNo('tree', $tree, -1, array('on_change' => 'reloadTab("start=0&tree="+this.value)'));
     } else {
         $tree = 0;
     }
     echo "</td></tr></table>";
     $number = count($used);
     $start = isset($_GET['start']) ? intval($_GET['start']) : 0;
     if ($start >= $number) {
         $start = 0;
     }
     // Display results
     if ($number) {
         echo "<div class='spaced'>";
         Html::printAjaxPager(sprintf(__('%1$s (%2$s)'), User::getTypeName(Session::getPluralNumber()), __('D=Dynamic')), $start, $number);
         Session::initNavigateListItems('User', sprintf(__('%1$s = %2$s'), Group::getTypeName(1), $group->getName()));
         if ($canedit) {
             Html::openMassiveActionsForm('mass' . __CLASS__ . $rand);
             $massiveactionparams = array('num_displayed' => min($number - $start, $_SESSION['glpilist_limit']), 'container' => 'mass' . __CLASS__ . $rand);
             Html::showMassiveActions($massiveactionparams);
         }
         echo "<table class='tab_cadre_fixehov table-striped table-hover'>";
         $header_begin = "<tr>";
         $header_top = '';
         $header_bottom = '';
         $header_end = '';
         if ($canedit) {
             $header_begin .= "<th width='10'>";
             $header_top .= Html::getCheckAllAsCheckbox('mass' . __CLASS__ . $rand);
             $header_bottom .= Html::getCheckAllAsCheckbox('mass' . __CLASS__ . $rand);
             $header_end .= "</th>";
         }
         $header_end .= "<th>" . User::getTypeName(1) . "</th>";
         if ($tree) {
             $header_end .= "<th>" . Group::getTypeName(1) . "</th>";
         }
         $header_end .= "<th>" . __('Dynamic') . "</th>";
         $header_end .= "<th>" . __('Manager') . "</th>";
         $header_end .= "<th>" . __('Delegatee') . "</th></tr>";
         echo $header_begin . $header_top . $header_end;
         $tmpgrp = new Group();
         for ($i = $start, $j = 0; $i < $number && $j < $_SESSION['glpilist_limit']; $i++, $j++) {
             $data = $used[$i];
             $user->getFromDB($data["id"]);
             Session::addToNavigateListItems('User', $data["id"]);
             echo "\n<tr class='tab_bg_" . ($user->isDeleted() ? '1_2' : '1') . "'>";
             if ($canedit) {
                 echo "<td width='10'>";
                 Html::showMassiveActionCheckBox(__CLASS__, $data["linkID"]);
                 echo "</td>";
             }
             echo "<td>" . $user->getLink();
             if ($tree) {
                 echo "</td><td>";
                 if ($tmpgrp->getFromDB($data['groups_id'])) {
                     echo $tmpgrp->getLink(array('comments' => true));
                 }
             }
             echo "</td><td class='center'>";
             if ($data['is_dynamic']) {
                 echo "<img src='" . $CFG_GLPI["root_doc"] . "/pics/ok.png' width='14' height='14' alt=\"" . __('Dynamic') . "\">";
             }
             echo "</td><td class='center'>";
             if ($data['is_manager']) {
                 echo "<img src='" . $CFG_GLPI["root_doc"] . "/pics/ok.png' width='14' height='14' alt=\"" . __('Manager') . "\">";
             }
             echo "</td><td class='center'>";
             if ($data['is_userdelegate']) {
                 echo "<img src='" . $CFG_GLPI["root_doc"] . "/pics/ok.png' width='14' height='14' alt=\"" . __('Delegatee') . "\">";
             }
             echo "</tr>";
         }
         echo $header_begin . $header_bottom . $header_end;
         echo "</table>";
         if ($canedit) {
             $massiveactionparams['ontop'] = false;
             Html::showMassiveActions($massiveactionparams);
             Html::closeForm();
         }
         Html::printAjaxPager(sprintf(__('%1$s (%2$s)'), User::getTypeName(Session::getPluralNumber()), __('D=Dynamic')), $start, $number);
         echo "</div>";
     } else {
         echo "<p class='center b'>" . __('No item found') . "</p>";
     }
 }
 function reconstrucTimeline()
 {
     global $DB;
     $query = "TRUNCATE `" . $this->getTable() . "`";
     $DB->query($query);
     $query = "SELECT id\n               FROM `glpi_tickets`";
     $result = $DB->query($query);
     while ($data = $DB->fetch_array($result)) {
         $queryGroup = "SELECT * FROM `glpi_logs`";
         $queryGroup .= " WHERE `itemtype_link` = 'Group'";
         $queryGroup .= " AND `items_id` = " . $data['id'];
         $queryGroup .= " AND `itemtype` = 'Ticket'";
         $queryGroup .= " ORDER BY date_mod ASC";
         $resultGroup = $DB->query($queryGroup);
         if ($resultGroup) {
             while ($dataGroup = $DB->fetch_array($resultGroup)) {
                 if ($dataGroup['new_value'] != null) {
                     $start = Toolbox::strpos($dataGroup['new_value'], "(");
                     $end = Toolbox::strpos($dataGroup['new_value'], ")");
                     $length = $end - $start;
                     $groups_id = Toolbox::substr($dataGroup['new_value'], $start + 1, $length - 1);
                     $group = new Group();
                     if ($group->getFromDB($groups_id)) {
                         if ($group->fields['is_requester'] == 0 && $group->fields['is_assign'] == 1) {
                             $ticket = new Ticket();
                             $ticket->getFromDB($data['id']);
                             $this->createGroup($ticket, $dataGroup['date_mod'], $groups_id, 'new');
                         }
                     }
                 } else {
                     if ($dataGroup['old_value'] != null) {
                         $start = Toolbox::strpos($dataGroup['old_value'], "(");
                         $end = Toolbox::strpos($dataGroup['old_value'], ")");
                         $length = $end - $start;
                         $groups_id = Toolbox::substr($dataGroup['old_value'], $start + 1, $length - 1);
                         $group = new Group();
                         if ($group->getFromDB($groups_id)) {
                             if ($group->fields['is_requester'] == 0 && $group->fields['is_assign'] == 1) {
                                 $ticket = new Ticket();
                                 $ticket->getFromDB($data['id']);
                                 $this->createGroup($ticket, $dataGroup['date_mod'], $groups_id, 'delete');
                             }
                         }
                     }
                 }
             }
         }
     }
 }
 /**
  * get SQL condition for filtered dropdown assign groups
  * @param int $tickets_id
  * @param int $itilcategories_id
  * @return string
  */
 static function getSQLCondition($tickets_id, $itilcategories_id)
 {
     $ticket = new Ticket();
     $group = new Group();
     $params = array('entities_id' => $_SESSION['glpiactive_entity'], 'is_recursive' => 1);
     if (!empty($tickets_id) && $ticket->getFromDB($tickets_id)) {
         // == UPDATE EXISTING TICKET ==
         $params['entities_id'] = $ticket->fields['entities_id'];
         $params['condition'] = " AND " . ($ticket->fields['type'] == Ticket::DEMAND_TYPE ? "`is_request`='1'" : "`is_incident`='1'");
     }
     $found_groups = self::getGroupsForCategory($itilcategories_id, $params);
     $groups_id_toshow = array();
     //init
     if (!empty($found_groups)) {
         for ($lvl = 1; $lvl <= 4; $lvl++) {
             if (isset($found_groups['groups_id_level' . $lvl])) {
                 if ($found_groups['groups_id_level' . $lvl] === "all") {
                     foreach (PluginItilcategorygroupsGroup_Level::getAllGroupForALevel($lvl, $params['entities_id']) as $groups_id) {
                         if ($group->getFromDB($groups_id)) {
                             $groups_id_toshow[] = $group->getID();
                         }
                     }
                 } else {
                     foreach ($found_groups['groups_id_level' . $lvl] as $groups_id) {
                         if (countElementsInTableForEntity("glpi_groups", $ticket->getEntityID(), "`id`='{$groups_id}'") > 0) {
                             $group->getFromDB($groups_id);
                             $groups_id_toshow[] = $group->getID();
                         }
                     }
                 }
             }
         }
     }
     $condition = "";
     if (count($groups_id_toshow) > 0) {
         // transform found groups (2 dimensions) in a flat array
         $groups_id_toshow_flat = array();
         array_walk_recursive($groups_id_toshow, function ($v, $k) use(&$groups_id_toshow_flat) {
             array_push($groups_id_toshow_flat, $v);
         });
         $newarray = implode(", ", $groups_id_toshow_flat);
         $condition = " id IN ({$newarray})";
     }
     return $condition;
 }
Example #21
0
 /**
  * @see CommonDBTM::doSpecificMassiveActions()
  **/
 function doSpecificMassiveActions($input = array())
 {
     $res = array('ok' => 0, 'ko' => 0, 'noright' => 0);
     switch ($input['action']) {
         case "add_user_group":
         case "add_supervisor_group":
         case "add_delegatee_group":
             foreach ($input["item"] as $key => $val) {
                 if ($val == 1) {
                     if (isset($input['users_id'])) {
                         // Add users to groups
                         $input2 = array('groups_id' => $key, 'users_id' => $input['users_id']);
                     } else {
                         if (isset($input['groups_id'])) {
                             // Add groups to users
                             $input2 = array('groups_id' => $input["groups_id"], 'users_id' => $key);
                         } else {
                             return false;
                         }
                     }
                     $updateifnotfound = false;
                     if ($input["action"] == 'add_supervisor_group') {
                         $input2['is_manager'] = 1;
                         $updateifnotfound = true;
                     }
                     if ($input["action"] == 'add_delegatee_group') {
                         $input2['is_userdelegate'] = 1;
                         $updateifnotfound = true;
                     }
                     $group = new Group();
                     $user = new user();
                     if ($group->getFromDB($input2['groups_id']) && $user->getFromDB($input2['users_id'])) {
                         if ($updateifnotfound && $this->getFromDBForItems($user, $group)) {
                             if ($this->can($this->getID(), 'w')) {
                                 $input2['id'] = $this->getID();
                                 if ($this->update($input2)) {
                                     $res['ok']++;
                                 } else {
                                     $res['ko']++;
                                 }
                             } else {
                                 $res['noright']++;
                             }
                         } else {
                             if ($this->can(-1, 'w', $input2)) {
                                 if ($this->add($input2)) {
                                     $res['ok']++;
                                 } else {
                                     $res['ko']++;
                                 }
                             } else {
                                 $res['noright']++;
                             }
                         }
                     } else {
                         $res['ko']++;
                     }
                 }
             }
             break;
         default:
             return parent::doSpecificMassiveActions($input);
     }
     return $res;
 }
Example #22
0
 /**
  * show tooltip for user notification informations
  *
  * @param $type integer : user type
  * @param $canedit boolean : can edit ?
  *
  * @return nothing display
  **/
 function showGroupsAssociated($type, $canedit)
 {
     global $CFG_GLPI, $LANG;
     $showgrouplink = 0;
     if (haveRight('group', 'r')) {
         $showgrouplink = 1;
     }
     $groupicon = self::getActorIcon('group', $type);
     $group = new Group();
     if (isset($this->groups[$type]) && count($this->groups[$type])) {
         foreach ($this->groups[$type] as $k => $d) {
             echo "{$groupicon}&nbsp;";
             if ($group->getFromDB($k)) {
                 echo $group->getLink($showgrouplink);
             }
             if ($canedit) {
                 echo "&nbsp;<a href='" . $CFG_GLPI["root_doc"] . "/front/ticket.form.php?delete_group=delete_group&amp;id=" . $d['id'] . "&amp;tickets_id=" . $this->fields['id'] . "' title=\"" . $LANG['reservation'][6] . "\">\n                     <img src='" . $CFG_GLPI["root_doc"] . "/pics/delete.png'\n                     alt=\"" . $LANG['buttons'][6] . "\" title=\"" . $LANG['buttons'][6] . "\"></a>";
             }
             echo '<br>';
         }
     }
 }
 /**
  * Show the Form edit form the the adminsitrator in the config page
  *
  * @param  Array  $options Optional options
  *
  * @return NULL         Nothing, just display the form
  */
 public function showForm($options = array())
 {
     $rand = mt_rand();
     $obj = new PluginFormcreatorTarget();
     $found = $obj->find("itemtype = '" . __CLASS__ . "' AND items_id = " . (int) $this->getID());
     $target = array_shift($found);
     $form = new PluginFormcreatorForm();
     $form->getFromDB($target['plugin_formcreator_forms_id']);
     echo '<div class="center" style="width: 950px; margin: 0 auto;">';
     echo '<form name="form_target" method="post" action="' . $GLOBALS['CFG_GLPI']['root_doc'] . '/plugins/formcreator/front/targetticket.form.php">';
     // General information : name
     echo '<table class="tab_cadre_fixe">';
     echo '<tr><th colspan="2">' . __('Edit a destination', 'formcreator') . '</th></tr>';
     echo '<tr class="line1">';
     echo '<td width="15%"><strong>' . __('Name') . ' <span style="color:red;">*</span></strong></td>';
     echo '<td width="85%"><input type="text" name="name" style="width:704px;" value="' . $target['name'] . '"></textarea</td>';
     echo '</tr>';
     echo '</table>';
     // Ticket information : title, template...
     echo '<table class="tab_cadre_fixe">';
     echo '<tr><th colspan="4">' . _n('Target ticket', 'Target tickets', 1, 'formcreator') . '</th></tr>';
     echo '<tr class="line1">';
     echo '<td><strong>' . __('Ticket title', 'formcreator') . ' <span style="color:red;">*</span></strong></td>';
     echo '<td colspan="3"><input type="text" name="title" style="width:704px;" value="' . $this->fields['name'] . '"></textarea</td>';
     echo '</tr>';
     echo '<tr class="line0">';
     echo '<td><strong>' . __('Description') . ' <span style="color:red;">*</span></strong></td>';
     echo '<td colspan="3">';
     echo '<textarea name="comment" style="width:700px;" rows="15">' . $this->fields['comment'] . '</textarea>';
     if ($GLOBALS['CFG_GLPI']["use_rich_text"]) {
         Html::initEditorSystem('comment');
     }
     echo '</td>';
     echo '</tr>';
     // Ticket Template
     echo '<tr class="line1">';
     echo '<td width="15%">' . _n('Ticket template', 'Ticket templates', 1) . '</td>';
     echo '<td width="25%">';
     Dropdown::show('TicketTemplate', array('name' => 'tickettemplates_id', 'value' => $this->fields['tickettemplates_id']));
     echo '</td>';
     echo '<td width="15%">' . __('Due date') . '</td>';
     echo '<td width="45%">';
     // -------------------------------------------------------------------------------------------
     // Due date type selection
     // -------------------------------------------------------------------------------------------
     Dropdown::showFromArray('due_date_rule', array('' => Dropdown::EMPTY_VALUE, 'answer' => __('equals to the answer to the question', 'formcreator'), 'ticket' => __('calculated from the ticket creation date', 'formcreator'), 'calcul' => __('calculated from the answer to the question', 'formcreator')), array('value' => $this->fields['due_date_rule'], 'on_change' => 'formcreatorChangeDueDate(this.value)'));
     // for each section ...
     $questions_list = array(Dropdown::EMPTY_VALUE);
     $query = "SELECT s.id, s.name\n                FROM glpi_plugin_formcreator_targets t\n                INNER JOIN glpi_plugin_formcreator_sections s ON s.plugin_formcreator_forms_id = t.plugin_formcreator_forms_id\n                WHERE t.items_id = " . (int) $this->getID() . "\n                ORDER BY s.order";
     $result = $GLOBALS['DB']->query($query);
     while ($section = $GLOBALS['DB']->fetch_array($result)) {
         // select all date and datetime questions
         $query2 = "SELECT q.id, q.name\n                   FROM glpi_plugin_formcreator_questions q\n                   INNER JOIN glpi_plugin_formcreator_sections s ON s.id = q.plugin_formcreator_sections_id\n                   WHERE s.id = {$section['id']}\n                   AND q.fieldtype IN ('date', 'datetime')";
         $result2 = $GLOBALS['DB']->query($query2);
         $section_questions = array();
         while ($question = $GLOBALS['DB']->fetch_array($result2)) {
             $section_questions[$question['id']] = $question['name'];
         }
         if (count($section_questions) > 0) {
             $questions_list[$section['name']] = $section_questions;
         }
     }
     // List questions
     if ($this->fields['due_date_rule'] != 'answer' && $this->fields['due_date_rule'] != 'calcul') {
         echo '<div id="due_date_questions" style="display:none">';
     } else {
         echo '<div id="due_date_questions">';
     }
     Dropdown::showFromArray('due_date_question', $questions_list, array('value' => $this->fields['due_date_question']));
     echo '</div>';
     if ($this->fields['due_date_rule'] != 'ticket' && $this->fields['due_date_rule'] != 'calcul') {
         echo '<div id="due_date_time" style="display:none">';
     } else {
         echo '<div id="due_date_time">';
     }
     Dropdown::showNumber("due_date_value", array('value' => $this->fields['due_date_value'], 'min' => -30, 'max' => 30));
     Dropdown::showFromArray('due_date_period', array('minute' => _n('Minute', 'Minutes', 2), 'hour' => _n('Hour', 'Hours', 2), 'day' => _n('Day', 'Days', 2), 'month' => __('Month')), array('value' => $this->fields['due_date_period']));
     echo '</div>';
     echo '</td>';
     echo '</tr>';
     // -------------------------------------------------------------------------------------------
     // Due date type selection end
     // -------------------------------------------------------------------------------------------
     if ($form->fields['validation_required']) {
         echo '<tr class="line0">';
         echo '<td colspan="4">';
         echo '<input type="hidden" name="validation_followup" value="0" />';
         echo '<input type="checkbox" name="validation_followup" id="validation_followup" value="1" ';
         if (!isset($this->fields['validation_followup']) || $this->fields['validation_followup'] == 1) {
             echo ' checked="checked"';
         }
         echo '/>';
         echo ' <label for="validation_followup">';
         echo __('Add validation message as first ticket followup', 'formcreator');
         echo '</label>';
         echo '</td>';
         echo '</tr>';
     }
     echo '</table>';
     // Buttons
     echo '<table class="tab_cadre_fixe">';
     echo '<tr class="line1">';
     echo '<td colspan="5" class="center">';
     echo '<input type="reset" name="reset" class="submit_button" value="' . __('Cancel', 'formcreator') . '"
            onclick="document.location = \'form.form.php?id=' . $target['plugin_formcreator_forms_id'] . '\'" /> &nbsp; ';
     echo '<input type="hidden" name="id" value="' . $this->getID() . '" />';
     echo '<input type="submit" name="update" class="submit_button" value="' . __('Save') . '" />';
     echo '</td>';
     echo '</tr>';
     echo '</table>';
     Html::closeForm();
     // Get available questions for actors lists
     $questions_user_list = array(Dropdown::EMPTY_VALUE);
     $questions_group_list = array(Dropdown::EMPTY_VALUE);
     $questions_supplier_list = array(Dropdown::EMPTY_VALUE);
     $query = "SELECT s.id, s.name\n                FROM glpi_plugin_formcreator_targets t\n                INNER JOIN glpi_plugin_formcreator_sections s ON s.plugin_formcreator_forms_id = t.plugin_formcreator_forms_id\n                WHERE t.items_id = " . (int) $this->getID() . "\n                ORDER BY s.order";
     $result = $GLOBALS['DB']->query($query);
     while ($section = $GLOBALS['DB']->fetch_array($result)) {
         // select all user, group or supplier questions (GLPI Object)
         $query2 = "SELECT q.id, q.name, q.values\n                   FROM glpi_plugin_formcreator_questions q\n                   INNER JOIN glpi_plugin_formcreator_sections s ON s.id = q.plugin_formcreator_sections_id\n                   WHERE s.id = {$section['id']}\n                   AND q.fieldtype = 'glpiselect'\n                   AND q.values IN ('User', 'Group', 'Supplier')";
         $result2 = $GLOBALS['DB']->query($query2);
         $section_questions_user = array();
         $section_questions_group = array();
         $section_questions_supplier = array();
         while ($question = $GLOBALS['DB']->fetch_array($result2)) {
             switch ($question['values']) {
                 case 'User':
                     $section_questions_user[$question['id']] = $question['name'];
                     break;
                 case 'Group':
                     $section_questions_group[$question['id']] = $question['name'];
                     break;
                 case 'Supplier':
                     $section_questions_supplier[$question['id']] = $question['name'];
                     break;
             }
         }
         $questions_user_list[$section['name']] = $section_questions_user;
         $questions_group_list[$section['name']] = $section_questions_group;
         $questions_supplier_list[$section['name']] = $section_questions_supplier;
     }
     // Get available questions for actors lists
     $actors = array('requester' => array(), 'observer' => array(), 'assigned' => array());
     $query = "SELECT id, actor_role, actor_type, actor_value, use_notification\n                FROM glpi_plugin_formcreator_targettickets_actors\n                WHERE plugin_formcreator_targettickets_id = " . $this->getID();
     $result = $GLOBALS['DB']->query($query);
     while ($actor = $GLOBALS['DB']->fetch_array($result)) {
         $actors[$actor['actor_role']][$actor['id']] = array('actor_type' => $actor['actor_type'], 'actor_value' => $actor['actor_value'], 'use_notification' => $actor['use_notification']);
     }
     $img_user = '******' . __('User') . '" title="' . __('User') . '" width="20" />';
     $img_group = '<img src="../../../pics/groupes.png" alt="' . __('Group') . '" title="' . __('Group') . '" width="20" />';
     $img_supplier = '<img src="../../../pics/supplier.png" alt="' . __('Supplier') . '" title="' . __('Supplier') . '" width="20" />';
     $img_mail = '<img src="../pics/email.png" alt="' . __('Yes') . '" title="' . __('Email followup') . ' ' . __('Yes') . '" />';
     $img_nomail = '<img src="../pics/email-no.png" alt="' . __('No') . '" title="' . __('Email followup') . ' ' . __('No') . '" />';
     echo '<table class="tab_cadre_fixe">';
     echo '<tr><th colspan="3">' . __('Ticket actors', 'formcreator') . '</th></tr>';
     echo '<tr>';
     echo '<th width="33%">';
     echo _n('Requester', 'Requesters', 1) . ' &nbsp;';
     echo '<img title="Ajouter" alt="Ajouter" onclick="displayRequesterForm()" class="pointer"
            id="btn_add_requester" src="../../../pics/add_dropdown.png">';
     echo '<img title="Annuler" alt="Annuler" onclick="hideRequesterForm()" class="pointer"
            id="btn_cancel_requester" src="../../../pics/delete.png" style="display:none">';
     echo '</th>';
     echo '<th width="34%">';
     echo _n('Watcher', 'Watchers', 1) . ' &nbsp;';
     echo '<img title="Ajouter" alt="Ajouter" onclick="displayWatcherForm()" class="pointer"
            id="btn_add_watcher" src="../../../pics/add_dropdown.png">';
     echo '<img title="Annuler" alt="Annuler" onclick="hideWatcherForm()" class="pointer"
            id="btn_cancel_watcher" src="../../../pics/delete.png" style="display:none">';
     echo '</th>';
     echo '<th width="33%">';
     echo __('Assigned to') . ' &nbsp;';
     echo '<img title="Ajouter" alt="Ajouter" onclick="displayAssignedForm()" class="pointer"
            id="btn_add_assigned" src="../../../pics/add_dropdown.png">';
     echo '<img title="Annuler" alt="Annuler" onclick="hideAssignedForm()" class="pointer"
            id="btn_cancel_assigned" src="../../../pics/delete.png" style="display:none">';
     echo '</th>';
     echo '</tr>';
     echo '<tr>';
     // Requester
     echo '<td valign="top">';
     // => Add requester form
     echo '<form name="form_target" id="form_add_requester" method="post" style="display:none" action="' . $GLOBALS['CFG_GLPI']['root_doc'] . '/plugins/formcreator/front/targetticket.form.php">';
     Dropdown::showFromArray('actor_type', array('' => Dropdown::EMPTY_VALUE, 'creator' => __('Form requester', 'formcreator'), 'validator' => __('Form validator', 'formcreator'), 'person' => __('Specific person', 'formcreator'), 'question_person' => __('Person from the question', 'formcreator'), 'group' => __('Specific group', 'formcreator'), 'question_group' => __('Group from the question', 'formcreator')), array('on_change' => 'formcreatorChangeActorRequester(this.value)'));
     echo '<div id="block_requester_user" style="display:none">';
     User::dropdown(array('name' => 'actor_value_person', 'right' => 'all', 'all' => 0));
     echo '</div>';
     echo '<div id="block_requester_group" style="display:none">';
     Group::dropdown(array('name' => 'actor_value_group'));
     echo '</div>';
     echo '<div id="block_requester_question_user" style="display:none">';
     Dropdown::showFromArray('actor_value_question_person', $questions_user_list, array('value' => $this->fields['due_date_question']));
     echo '</div>';
     echo '<div id="block_requester_question_group" style="display:none">';
     Dropdown::showFromArray('actor_value_question_group', $questions_group_list, array('value' => $this->fields['due_date_question']));
     echo '</div>';
     echo '<div>';
     echo __('Email followup');
     Dropdown::showYesNo('use_notification', 1);
     echo '</div>';
     echo '<p align="center">';
     echo '<input type="hidden" name="id" value="' . $this->getID() . '" />';
     echo '<input type="hidden" name="actor_role" value="requester" />';
     echo '<input type="submit" value="' . __('Add') . '" class="submit_button" />';
     echo '</p>';
     echo "<hr>";
     Html::closeForm();
     // => List of saved requesters
     foreach ($actors['requester'] as $id => $values) {
         echo '<div>';
         switch ($values['actor_type']) {
             case 'creator':
                 echo $img_user . ' <b>' . __('Form requester', 'formcreator') . '</b>';
                 break;
             case 'validator':
                 echo $img_user . ' <b>' . __('Form validator', 'formcreator') . '</b>';
                 break;
             case 'person':
                 $user = new User();
                 $user->getFromDB($values['actor_value']);
                 echo $img_user . ' <b>' . __('User') . ' </b> "' . $user->getName() . '"';
                 break;
             case 'question_person':
                 $question = new PluginFormcreatorQuestion();
                 $question->getFromDB($values['actor_value']);
                 echo $img_user . ' <b>' . __('Person from the question', 'formcreator') . '</b> "' . $question->getName() . '"';
                 break;
             case 'group':
                 $group = new Group();
                 $group->getFromDB($values['actor_value']);
                 echo $img_user . ' <b>' . __('Group') . ' </b> "' . $group->getName() . '"';
                 break;
             case 'question_group':
                 $question = new PluginFormcreatorQuestion();
                 $question->getFromDB($values['actor_value']);
                 echo $img_group . ' <b>' . __('Group from the question', 'formcreator') . '</b> "' . $question->getName() . '"';
                 break;
         }
         echo $values['use_notification'] ? ' ' . $img_mail . ' ' : ' ' . $img_nomail . ' ';
         echo self::getDeleteImage($id);
         echo '</div>';
     }
     echo '</td>';
     // Observer
     echo '<td valign="top">';
     // => Add observer form
     echo '<form name="form_target" id="form_add_watcher" method="post" style="display:none" action="' . $GLOBALS['CFG_GLPI']['root_doc'] . '/plugins/formcreator/front/targetticket.form.php">';
     Dropdown::showFromArray('actor_type', array('' => Dropdown::EMPTY_VALUE, 'creator' => __('Form requester', 'formcreator'), 'validator' => __('Form validator', 'formcreator'), 'person' => __('Specific person', 'formcreator'), 'question_person' => __('Person from the question', 'formcreator'), 'group' => __('Specific group', 'formcreator'), 'question_group' => __('Group from the question', 'formcreator')), array('on_change' => 'formcreatorChangeActorWatcher(this.value)'));
     echo '<div id="block_watcher_user" style="display:none">';
     User::dropdown(array('name' => 'actor_value_person', 'right' => 'all', 'all' => 0));
     echo '</div>';
     echo '<div id="block_watcher_group" style="display:none">';
     Group::dropdown(array('name' => 'actor_value_group'));
     echo '</div>';
     echo '<div id="block_watcher_question_user" style="display:none">';
     Dropdown::showFromArray('actor_value_question_person', $questions_user_list, array('value' => $this->fields['due_date_question']));
     echo '</div>';
     echo '<div id="block_watcher_question_group" style="display:none">';
     Dropdown::showFromArray('actor_value_question_group', $questions_group_list, array('value' => $this->fields['due_date_question']));
     echo '</div>';
     echo '<div>';
     echo __('Email followup');
     Dropdown::showYesNo('use_notification', 1);
     echo '</div>';
     echo '<p align="center">';
     echo '<input type="hidden" name="id" value="' . $this->getID() . '" />';
     echo '<input type="hidden" name="actor_role" value="observer" />';
     echo '<input type="submit" value="' . __('Add') . '" class="submit_button" />';
     echo '</p>';
     echo "<hr>";
     Html::closeForm();
     // => List of saved observers
     foreach ($actors['observer'] as $id => $values) {
         echo '<div>';
         switch ($values['actor_type']) {
             case 'creator':
                 echo $img_user . ' <b>' . __('Form requester', 'formcreator') . '</b>';
                 break;
             case 'validator':
                 echo $img_user . ' <b>' . __('Form validator', 'formcreator') . '</b>';
                 break;
             case 'person':
                 $user = new User();
                 $user->getFromDB($values['actor_value']);
                 echo $img_user . ' <b>' . __('User') . ' </b> "' . $user->getName() . '"';
                 break;
             case 'question_person':
                 $question = new PluginFormcreatorQuestion();
                 $question->getFromDB($values['actor_value']);
                 echo $img_user . ' <b>' . __('Person from the question', 'formcreator') . '</b> "' . $question->getName() . '"';
                 break;
             case 'group':
                 $group = new Group();
                 $group->getFromDB($values['actor_value']);
                 echo $img_user . ' <b>' . __('Group') . ' </b> "' . $group->getName() . '"';
                 break;
             case 'question_group':
                 $question = new PluginFormcreatorQuestion();
                 $question->getFromDB($values['actor_value']);
                 echo $img_group . ' <b>' . __('Group from the question', 'formcreator') . '</b> "' . $question->getName() . '"';
                 break;
         }
         echo $values['use_notification'] ? ' ' . $img_mail . ' ' : ' ' . $img_nomail . ' ';
         echo self::getDeleteImage($id);
         echo '</div>';
     }
     echo '</td>';
     // Assigned to
     echo '<td valign="top">';
     // => Add assigned to form
     echo '<form name="form_target" id="form_add_assigned" method="post" style="display:none" action="' . $GLOBALS['CFG_GLPI']['root_doc'] . '/plugins/formcreator/front/targetticket.form.php">';
     Dropdown::showFromArray('actor_type', array('' => Dropdown::EMPTY_VALUE, 'creator' => __('Form requester', 'formcreator'), 'validator' => __('Form validator', 'formcreator'), 'person' => __('Specific person', 'formcreator'), 'question_person' => __('Person from the question', 'formcreator'), 'group' => __('Specific group', 'formcreator'), 'question_group' => __('Group from the question', 'formcreator'), 'supplier' => __('Specific supplier', 'formcreator'), 'question_supplier' => __('Supplier from the question', 'formcreator')), array('on_change' => 'formcreatorChangeActorAssigned(this.value)'));
     echo '<div id="block_assigned_user" style="display:none">';
     User::dropdown(array('name' => 'actor_value_person', 'right' => 'all', 'all' => 0));
     echo '</div>';
     echo '<div id="block_assigned_group" style="display:none">';
     Group::dropdown(array('name' => 'actor_value_group'));
     echo '</div>';
     echo '<div id="block_assigned_supplier" style="display:none">';
     Supplier::dropdown(array('name' => 'actor_value_supplier'));
     echo '</div>';
     echo '<div id="block_assigned_question_user" style="display:none">';
     Dropdown::showFromArray('actor_value_question_person', $questions_user_list, array('value' => $this->fields['due_date_question']));
     echo '</div>';
     echo '<div id="block_assigned_question_group" style="display:none">';
     Dropdown::showFromArray('actor_value_question_group', $questions_group_list, array('value' => $this->fields['due_date_question']));
     echo '</div>';
     echo '<div id="block_assigned_question_supplier" style="display:none">';
     Dropdown::showFromArray('actor_value_question_supplier', $questions_supplier_list, array('value' => $this->fields['due_date_question']));
     echo '</div>';
     echo '<div>';
     echo __('Email followup');
     Dropdown::showYesNo('use_notification', 1);
     echo '</div>';
     echo '<p align="center">';
     echo '<input type="hidden" name="id" value="' . $this->getID() . '" />';
     echo '<input type="hidden" name="actor_role" value="assigned" />';
     echo '<input type="submit" value="' . __('Add') . '" class="submit_button" />';
     echo '</p>';
     echo "<hr>";
     Html::closeForm();
     // => List of saved assigned to
     foreach ($actors['assigned'] as $id => $values) {
         echo '<div>';
         switch ($values['actor_type']) {
             case 'creator':
                 echo $img_user . ' <b>' . __('Form requester', 'formcreator') . '</b>';
                 break;
             case 'validator':
                 echo $img_user . ' <b>' . __('Form validator', 'formcreator') . '</b>';
                 break;
             case 'person':
                 $user = new User();
                 $user->getFromDB($values['actor_value']);
                 echo $img_user . ' <b>' . __('User') . ' </b> "' . $user->getName() . '"';
                 break;
             case 'question_person':
                 $question = new PluginFormcreatorQuestion();
                 $question->getFromDB($values['actor_value']);
                 echo $img_user . ' <b>' . __('Person from the question', 'formcreator') . '</b> "' . $question->getName() . '"';
                 break;
             case 'group':
                 $group = new Group();
                 $group->getFromDB($values['actor_value']);
                 echo $img_user . ' <b>' . __('Group') . ' </b> "' . $group->getName() . '"';
                 break;
             case 'question_group':
                 $question = new PluginFormcreatorQuestion();
                 $question->getFromDB($values['actor_value']);
                 echo $img_group . ' <b>' . __('Group from the question', 'formcreator') . '</b> "' . $question->getName() . '"';
                 break;
             case 'supplier':
                 $group = new Group();
                 $group->getFromDB($values['actor_value']);
                 echo $img_supplier . ' <b>' . __('Supplier') . ' </b> "' . $group->getName() . '"';
                 break;
             case 'question_supplier':
                 $question = new PluginFormcreatorQuestion();
                 $question->getFromDB($values['actor_value']);
                 echo $img_supplier . ' <b>' . __('Supplier from the question', 'formcreator') . '</b> "' . $question->getName() . '"';
                 break;
         }
         echo $values['use_notification'] ? ' ' . $img_mail . ' ' : ' ' . $img_nomail . ' ';
         echo self::getDeleteImage($id);
         echo '</div>';
     }
     echo '</td>';
     echo '</tr>';
     echo '</table>';
     // List of available tags
     echo '<table class="tab_cadre_fixe">';
     echo '<tr><th colspan="5">' . __('List of available tags') . '</th></tr>';
     echo '<tr>';
     echo '<th width="40%" colspan="2">' . _n('Question', 'Questions', 1, 'formcreator') . '</th>';
     echo '<th width="20%">' . __('Title') . '</th>';
     echo '<th width="20%">' . _n('Answer', 'Answers', 1, 'formcreator') . '</th>';
     echo '<th width="20%">' . _n('Section', 'Sections', 1, 'formcreator') . '</th>';
     echo '</tr>';
     echo '<tr class="line0">';
     echo '<td colspan="2"><strong>' . __('Full form', 'formcreator') . '</strong></td>';
     echo '<td align="center"><code>-</code></td>';
     echo '<td align="center"><code><strong>##FULLFORM##</strong></code></td>';
     echo '<td align="center">-</td>';
     echo '</tr>';
     $table_questions = getTableForItemType('PluginFormcreatorQuestion');
     $table_sections = getTableForItemType('PluginFormcreatorSection');
     $query = "SELECT q.`id`, q.`name` AS question, s.`name` AS section\n                FROM {$table_questions} q\n                LEFT JOIN {$table_sections} s ON q.`plugin_formcreator_sections_id` = s.`id`\n                WHERE s.`plugin_formcreator_forms_id` = " . $target['plugin_formcreator_forms_id'] . "\n                ORDER BY s.`order`, q.`order`";
     $result = $GLOBALS['DB']->query($query);
     $i = 0;
     while ($question = $GLOBALS['DB']->fetch_array($result)) {
         $i++;
         echo '<tr class="line' . $i % 2 . '">';
         echo '<td colspan="2">' . $question['question'] . '</td>';
         echo '<td align="center"><code>##question_' . $question['id'] . '##</code></td>';
         echo '<td align="center"><code>##answer_' . $question['id'] . '##</code></td>';
         echo '<td align="center">' . $question['section'] . '</td>';
         echo '</tr>';
     }
     echo '</table>';
     echo '</div>';
 }
Example #24
0
 /**
  * @since version 0.90
  *
  * @param $rand
  **/
 function showTimeline($rand)
 {
     global $CFG_GLPI, $DB, $autolink_options;
     //get ticket actors
     $ticket_users_keys = $this->getTicketActors();
     $user = new User();
     $group = new Group();
     $followup_obj = new TicketFollowup();
     $pics_url = $CFG_GLPI['root_doc'] . "/pics/timeline";
     $timeline = $this->getTimelineItems();
     $autolink_options['strip_protocols'] = false;
     //display timeline
     echo "<div class='timeline_history'>";
     $tmp = array_values($timeline);
     $first_item = array_shift($tmp);
     // show approbation form on top when ticket is solved
     if ($this->fields["status"] == CommonITILObject::SOLVED) {
         echo "<div class='approbation_form' id='approbation_form{$rand}'>";
         $followup_obj->showApprobationForm($this);
         echo "</div>";
     }
     // show title for timeline
     self::showTimelineHeader();
     $timeline_index = 0;
     foreach ($timeline as $item) {
         $options = array('parent' => $this, 'rand' => $rand);
         if ($obj = getItemForItemtype($item['type'])) {
             $obj->fields = $item['item'];
         } else {
             $obj = $item;
         }
         Plugin::doHook('pre_show_item', array('item' => &$obj, 'options' => &$options));
         if (is_array($obj)) {
             $item_i = $obj['item'];
         } else {
             $item_i = $obj->fields;
         }
         $date = "";
         if (isset($item_i['date'])) {
             $date = $item_i['date'];
         }
         if (isset($item_i['date_mod'])) {
             $date = $item_i['date_mod'];
         }
         // check if curent item user is assignee or requester
         $user_position = 'left';
         if (isset($ticket_users_keys[$item_i['users_id']]) && $ticket_users_keys[$item_i['users_id']] == CommonItilActor::ASSIGN || $item['type'] == 'Assign') {
             $user_position = 'right';
         }
         //display solution in middle
         if ($timeline_index == 0 && $item['type'] == "Solution" && $this->fields["status"] == CommonITILObject::SOLVED) {
             $user_position .= ' middle';
         }
         echo "<div class='h_item {$user_position}'>";
         echo "<div class='h_info'>";
         echo "<div class='h_date'>" . Html::convDateTime($date) . "</div>";
         if ($item_i['users_id'] !== false) {
             echo "<div class='h_user'>";
             if (isset($item_i['users_id']) && $item_i['users_id'] != 0) {
                 $user->getFromDB($item_i['users_id']);
                 echo "<div class='tooltip_picture_border'>";
                 echo "<img class='user_picture' alt=\"" . __s('Picture') . "\" src='" . User::getThumbnailURLForPicture($user->fields['picture']) . "'>";
                 echo "</div>";
                 echo "<span class='h_user_name'>";
                 $userdata = getUserName($item_i['users_id'], 2);
                 echo $user->getLink() . "&nbsp;";
                 echo Html::showToolTip($userdata["comment"], array('link' => $userdata['link']));
                 echo "</span>";
             } else {
                 _e("Requester");
             }
             echo "</div>";
             // h_user
         }
         echo "</div>";
         //h_date
         echo "<div class='h_content " . $item['type'] . (isset($item_i['status']) ? " " . $item_i['status'] : "") . "'" . "id='viewitem" . $item['type'] . $item_i['id'] . $rand . "'>";
         if (isset($item_i['can_edit']) && $item_i['can_edit']) {
             echo "<div class='edit_item_content'></div>";
             echo "<span class='cancel_edit_item_content'></span>";
         }
         echo "<div class='displayed_content'>";
         if (!in_array($item['type'], array('Document_Item', 'Assign')) && $item_i['can_edit']) {
             echo "<span class='edit_item' ";
             echo "onclick='javascript:viewEditSubitem" . $this->fields['id'] . "{$rand}(event, \"" . $item['type'] . "\", " . $item_i['id'] . ", this, \"viewitem" . $item['type'] . $item_i['id'] . $rand . "\")'";
             echo "></span>";
         }
         if (isset($item_i['requesttypes_id']) && file_exists("{$pics_url}/" . $item_i['requesttypes_id'] . ".png")) {
             echo "<img src='{$pics_url}/" . $item_i['requesttypes_id'] . ".png' title='' class='h_requesttype' />";
         }
         if (isset($item_i['content'])) {
             $content = $item_i['content'];
             $content = autolink($content, 40);
             //$content = nl2br($content);
             $long_text = "";
             if (substr_count($content, "<br") > 30 || strlen($content) > 2000) {
                 $long_text = "long_text";
             }
             echo "<div class='item_content {$long_text}'>";
             echo "<p>";
             if (isset($item_i['state'])) {
                 $onClick = "onclick='change_task_state(" . $item_i['id'] . ", this)'";
                 if (!$item_i['can_edit']) {
                     $onClick = "style='cursor: not-allowed;'";
                 }
                 echo "<span class='state state_" . $item_i['state'] . "'\n                           {$onClick}\n                           title='" . Planning::getState($item_i['state']) . "'>";
                 echo "</span>";
             }
             echo $content;
             echo "</p>";
             if (!empty($long_text)) {
                 echo "<p class='read_more'>";
                 echo "<a class='read_more_button'>.....</a>";
                 echo "</p>";
             }
             echo "</div>";
         }
         echo "<div class='b_right'>";
         if (isset($item_i['solutiontypes_id']) && !empty($item_i['solutiontypes_id'])) {
             echo Dropdown::getDropdownName("glpi_solutiontypes", $item_i['solutiontypes_id']) . "<br>";
         }
         if (isset($item_i['taskcategories_id']) && !empty($item_i['taskcategories_id'])) {
             echo Dropdown::getDropdownName("glpi_taskcategories", $item_i['taskcategories_id']) . "<br>";
         }
         if (isset($item_i['requesttypes_id']) && !empty($item_i['requesttypes_id'])) {
             echo Dropdown::getDropdownName("glpi_requesttypes", $item_i['requesttypes_id']) . "<br>";
         }
         if (isset($item_i['actiontime']) && !empty($item_i['actiontime'])) {
             echo "<span class='actiontime'>";
             echo Html::timestampToString($item_i['actiontime'], false);
             echo "</span>";
         }
         if (isset($item_i['begin'])) {
             echo "<span class='planification'>";
             echo Html::convDateTime($item_i["begin"]);
             echo " &rArr; ";
             echo Html::convDateTime($item_i["end"]);
             echo "</span>";
         }
         if (isset($item_i['users_id_tech']) && $item_i['users_id_tech'] > 0) {
             echo "<div class='users_id_tech' id='users_id_tech_" . $item_i['users_id_tech'] . "'>";
             $user->getFromDB($item_i['users_id_tech']);
             echo Html::image($CFG_GLPI['root_doc'] . "/pics/user.png") . "&nbsp;";
             $userdata = getUserName($item_i['users_id_tech'], 2);
             echo $user->getLink() . "&nbsp;";
             echo Html::showToolTip($userdata["comment"], array('link' => $userdata['link']));
             echo "</div>";
         }
         if (isset($item_i['groups_id_tech']) && $item_i['groups_id_tech'] > 0) {
             echo "<div class='groups_id_tech'>";
             $group->getFromDB($item_i['groups_id_tech']);
             echo Html::image($CFG_GLPI['root_doc'] . "/pics/group.png") . "&nbsp;";
             echo $group->getLink() . "&nbsp;";
             echo Html::showToolTip($group->getComments(), array('link' => $group->getLinkURL()));
             echo "</div>";
         }
         // show "is_private" icon
         if (isset($item_i['is_private']) && $item_i['is_private']) {
             echo "<div class='private'>" . __('Private') . "</div>";
         }
         echo "</div>";
         // b_right
         if ($item['type'] == 'Document_Item') {
             $filename = $item_i['filename'];
             $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
             echo "<img src='";
             if (empty($filename)) {
                 $filename = $item_i['name'];
             }
             if (file_exists(GLPI_ROOT . "/pics/icones/{$ext}-dist.png")) {
                 echo $CFG_GLPI['root_doc'] . "/pics/icones/{$ext}-dist.png";
             } else {
                 echo "{$pics_url}/file.png";
             }
             echo "' title='file' />&nbsp;";
             echo "<a href='" . $CFG_GLPI['root_doc'] . "/front/document.send.php?docid=" . $item_i['id'] . "&tickets_id=" . $this->getID() . "' target='_blank'>{$filename}";
             if (in_array($ext, array('jpg', 'jpeg', 'png', 'bmp'))) {
                 echo "<div class='timeline_img_preview'>";
                 echo "<img src='" . $CFG_GLPI['root_doc'] . "/front/document.send.php?docid=" . $item_i['id'] . "&tickets_id=" . $this->getID() . "'/>";
                 echo "</div>";
             }
             echo "</a>";
             if (!empty($item_i['mime'])) {
                 echo "&nbsp;(" . $item_i['mime'] . ")";
             }
             echo "<a href='" . $CFG_GLPI['root_doc'] . "/front/document.form.php?id=" . $item_i['id'] . "' class='edit_document' title='" . _sx("button", "Update") . "'>";
             echo "<img src='{$pics_url}/edit.png' /></a>";
             echo "<a href='" . $CFG_GLPI['root_doc'] . "/front/ticket.form.php?delete_document&documents_id=" . $item_i['id'] . "&tickets_id=" . $this->getID() . "' class='delete_document' title='" . _sx("button", "Delete permanently") . "'>";
             echo "<img src='{$pics_url}/delete.png' /></a>";
         }
         echo "</div>";
         // displayed_content
         echo "</div>";
         //end h_content
         echo "</div>";
         //end  h_info
         $timeline_index++;
         Plugin::doHook('post_show_item', array('item' => $obj, 'options' => $options));
     }
     // end foreach timeline
     echo "<div class='break'></div>";
     // recall ticket content (not needed in classic and splitted layout)
     if (!CommonGLPI::isLayoutWithMain()) {
         echo "<div class='h_item middle'>";
         echo "<div class='h_info'>";
         echo "<div class='h_date'>" . Html::convDateTime($this->fields['date']) . "</div>";
         echo "<div class='h_user'>";
         $dem = '0';
         foreach ($DB->request("glpi_tickets_users", "`tickets_id` = " . $this->fields['id'] . " AND `type` = 1") as $req) {
             $dem = $req['users_id'];
         }
         if ((!isset($item_i['users_id_recipient']) || $item_i['users_id_recipient'] == 0) && $dem == 0) {
             _e("Requester");
         } else {
             if (isset($item_i['users_id_recipient']) && $item_i['users_id_recipient'] != 0) {
                 $user->getFromDB($this->fields['users_id_recipient']);
             } else {
                 if ($dem > 0) {
                     $requester = new User();
                     if ($requester->getFromDB($dem)) {
                         $user = $requester;
                     }
                 }
             }
             echo "<div class='tooltip_picture_border'>";
             $picture = "";
             if (isset($user->fields['picture'])) {
                 $picture = $user->fields['picture'];
             }
             echo "<img class='user_picture' alt=\"" . __s('Picture') . "\" src='" . User::getThumbnailURLForPicture($picture) . "'>";
             echo "</div>";
             echo $user->getLink();
         }
         echo "</div>";
         // h_user
         echo "</div>";
         //h_info
         echo "<div class='h_content TicketContent'>";
         echo "<div class='b_right'>" . __("Ticket recall") . "</div>";
         echo "<div class='ticket_title'>";
         echo html_entity_decode($this->fields['name']);
         echo "</div>";
         echo "<div class='ticket_description'>";
         echo $this->setSimpleTextContent($this->fields['content']);
         echo "</div>";
         echo "</div>";
         // h_content TicketContent
         echo "</div>";
         // h_item middle
         echo "<div class='break'></div>";
     }
     // end timeline
     echo "</div>";
     // h_item $user_position
     echo "<script type='text/javascript'>read_more();</script>";
 }
Example #25
0
             $canview = false;
             // If not mine check global right
             if (!$ismine) {
                 // First check user
                 $entities = Profile_User::getUserEntitiesForRight($user->getID(), Planning::READALL);
                 if ($_GET["uID"]) {
                     $userentities = Profile_User::getUserEntities($user->getID());
                     $intersect = array_intersect($entities, $userentities);
                     if (count($intersect)) {
                         $canview = true;
                     }
                 }
                 // Else check group
                 if (!$canview && $_GET['gID']) {
                     $group = new Group();
                     if ($group->getFromDB($_GET['gID'])) {
                         if (in_array($group->getEntityID(), $entities)) {
                             $canview = true;
                         }
                     }
                 }
             }
             if ($ismine || $canview) {
                 Planning::generateIcal($_GET["uID"], $_GET["gID"], $_GET["limititemtype"]);
             }
         }
     }
 } else {
     Html::header(__('Planning'), $_SERVER['PHP_SELF'], "helpdesk", "planning");
     Session::haveRightsOr('planning', array(Planning::READALL, Planning::READMY));
     if (!isset($_GET["date"]) || empty($_GET["date"])) {
Example #26
0
   function generateServicesCfg($file=0, $tag='') {
      global $DB;

      PluginMonitoringToolbox::logIfExtradebug(
         'pm-shinken',
         "Starting generateServicesCfg services ($tag) ...\n"
      );
      $pMonitoringCommand      = new PluginMonitoringCommand();
      $pmEventhandler          = new PluginMonitoringEventhandler();
      $pMonitoringCheck        = new PluginMonitoringCheck();
      $pmComponent             = new PluginMonitoringComponent();
      $pmEntity                = new PluginMonitoringEntity();
      $pmContact_Item          = new PluginMonitoringContact_Item();
      $networkPort             = new NetworkPort();
      $pmService               = new PluginMonitoringService();
      $pmComponentscatalog     = new PluginMonitoringComponentscatalog();
      $pmHostconfig            = new PluginMonitoringHostconfig();
      $calendar                = new Calendar();
      $user                    = new User();
      $profile_User = new Profile_User();

      $a_services = array();
      $i=0;

      // TODO: only contacts in allowed entities ...
      // Prepare individual contacts
      $a_contacts_entities = array();
      $a_list_contact = $pmContact_Item->find("`itemtype`='PluginMonitoringComponentscatalog'
         AND `users_id`>0");
      foreach ($a_list_contact as $data) {
         $contactentities = getSonsOf('glpi_entities', $data['entities_id']);
         if (isset($a_contacts_entities[$data['items_id']][$data['users_id']])) {
            $contactentities = array_merge($contactentities, $a_contacts_entities[$data['items_id']][$data['users_id']]);
         }
         $a_contacts_entities[$data['items_id']][$data['users_id']] = $contactentities;
      }
      // Prepare groups contacts
      $group = new Group();
      $a_list_contact = $pmContact_Item->find("`itemtype`='PluginMonitoringComponentscatalog'
         AND `groups_id`>0");
      foreach ($a_list_contact as $data) {
         $group->getFromDB($data['groups_id']);
         if ($group->fields['is_recursive'] == 1) {
            $contactentities = getSonsOf('glpi_entities', $group->fields['entities_id']);
         } else {
            $contactentities = array($group->fields['entities_id'] => $group->fields['entities_id']);
         }
         $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_contacts_entities[$data['items_id']][$datag['users_id']])) {
               $contactentities = array_merge($contactentities, $a_contacts_entities[$data['items_id']][$datag['users_id']]);
            }
            $a_contacts_entities[$data['items_id']][$datag['users_id']] = $contactentities;
         }
      }



      $a_entities_allowed = $pmEntity->getEntitiesByTag($tag);
      // Toolbox::logInFile("pm-shinken", " Allowed entities:\n");
      $a_entities_list = array();
      foreach ($a_entities_allowed as $entity) {
         $a_entities_list = getSonsOf("glpi_entities", $entity);
      }
      $where = '';
      if (! isset($a_entities_allowed['-1'])) {
         $where = getEntitiesRestrictRequest("WHERE", "glpi_plugin_monitoring_services", '', $a_entities_list);
      }

      // --------------------------------------------------
      // "Normal" services ....
      $query = "SELECT * FROM `glpi_plugin_monitoring_services` $where";
      PluginMonitoringToolbox::logIfExtradebug(
         'pm-shinken',
         "Services: $query\n"
      );
      $result = $DB->query($query);
      while ($data=$DB->fetch_array($result)) {
         // Toolbox::logInFile("pm-shinken", " - fetch service ".$data['id']."\n");

         // if (isset($a_entities_allowed['-1'])
                 // OR isset($a_entities_allowed[$item->fields['entities_id']])) {
            $notadd = 0;
            $notadddescription = '';
            $a_component = current($pmComponent->find("`id`='".$data['plugin_monitoring_components_id']."'", "", 1));
            if (empty($a_component)) {
               continue;
            }
            $a_hostname = array();
            $a_hostname_type = array();
            $a_hostname_id = array();
            $queryh = "SELECT * FROM `glpi_plugin_monitoring_componentscatalogs_hosts`
               WHERE `id` = '".$data['plugin_monitoring_componentscatalogs_hosts_id']."'
               LIMIT 1";
            $resulth = $DB->query($queryh);
            $hostname = '';
            $plugin_monitoring_componentscatalogs_id = 0;
            while ($datah=$DB->fetch_array($resulth)) {
               $itemtype = $datah['itemtype'];
               $item = new $itemtype();
               if ($item->getFromDB($datah['items_id'])) {
                  // if (isset($a_entities_allowed['-1'])
                          // OR isset($a_entities_allowed[$item->fields['entities_id']])) {

                     // Fix if hostname is not defined ...
                     if (! empty($item->fields['name'])) {
                        $a_hostname[] = preg_replace("/[^A-Za-z0-9\-_]/","",$item->fields['name']);
                        $a_hostname_type[] = $datah['itemtype'];
                        $a_hostname_id[] = $datah['items_id'];
                        $hostname = $item->fields['name'];
                        $plugin_monitoring_componentscatalogs_id = $datah['plugin_monitoring_componentscalalog_id'];
                     }
                  // }
               }
            }
            if (count($a_hostname) > 0) {
               if (isset($_SESSION['plugin_monitoring']['servicetemplates'][$a_component['id']])) {
                  $a_services[$i]['use'] = $_SESSION['plugin_monitoring']['servicetemplates'][$a_component['id']];
               }
               $a_services[$i]['host_name'] = implode(",", array_unique($a_hostname));
               $a_services[$i]['_HOSTITEMSID'] = implode(",", array_unique($a_hostname_id));
               $a_services[$i]['_HOSTITEMTYPE'] = implode(",", array_unique($a_hostname_type));

               // Define display_name / service_description
               $a_services[$i]['service_description'] = (! empty($a_component['description'])) ? $a_component['description'] : preg_replace("/[^A-Za-z0-9\-_]/","",$a_component['name']);
               // In case have multiple networkt port, may have description different, else be dropped by shinken
               if ($data['networkports_id'] > 0) {
                  $networkPort->getFromDB($data['networkports_id']);
                  $a_services[$i]['service_description'] .= '-'.preg_replace("/[^A-Za-z0-9\-_]/", "", $networkPort->fields['name']);
               }
               $a_services[$i]['display_name'] = $a_component['name'];
               // $a_services[$i]['_ENTITIESID'] = $item->fields['entities_id'];
               // $a_services[$i]['_ITEMSID'] = $data['id'];
               // $a_services[$i]['_ITEMTYPE'] = 'Service';
               PluginMonitoringToolbox::logIfExtradebug(
                  'pm-shinken',
                  " - add service ".$a_services[$i]['service_description']." on ".$a_services[$i]['host_name']."\n"
               );

               if (isset(self::$shinkenParameters['glpi']['entityId'])) {
                  $a_services[$i][self::$shinkenParameters['glpi']['entityId']] =
                     $item->fields['entities_id'];
               }
               if (isset(self::$shinkenParameters['glpi']['itemType'])) {
                  $a_services[$i][self::$shinkenParameters['glpi']['itemType']] =
                     'Service';
               }
               if (isset(self::$shinkenParameters['glpi']['itemId'])) {
                  $a_services[$i][self::$shinkenParameters['glpi']['itemId']] =
                     $data['id'];
               }

               // Manage freshness
               if ($a_component['freshness_count'] == 0) {
                  $a_services[$i]['check_freshness'] = '0';
                  $a_services[$i]['freshness_threshold'] = '3600';
               } else {
                  $multiple = 1;
                  if ($a_component['freshness_type'] == 'seconds') {
                     $multiple = 1;
                  } else if ($a_component['freshness_type'] == 'minutes') {
                     $multiple = 60;
                  } else if ($a_component['freshness_type'] == 'hours') {
                     $multiple = 3600;
                  } else if ($a_component['freshness_type'] == 'days') {
                     $multiple = 86400;
                  }
                  $a_services[$i]['check_freshness'] = '1';
                  $a_services[$i]['freshness_threshold'] = (string)($a_component['freshness_count'] * $multiple);
               }

               $pMonitoringCommand->getFromDB($a_component['plugin_monitoring_commands_id']);
               // Manage arguments
               $array = array();
               preg_match_all("/\\$(ARG\d+)\\$/", $pMonitoringCommand->fields['command_line'], $array);
               sort($array[0]);
               $a_arguments = importArrayFromDB($a_component['arguments']);
               $a_argumentscustom = importArrayFromDB($data['arguments']);
               foreach ($a_argumentscustom as $key=>$value) {
                  $a_arguments[$key] = $value;
               }
               foreach ($a_arguments as $key=>$value) {
                  $a_arguments[$key] = str_replace('!', '\!', html_entity_decode($value));
               }
               $args = '';
               foreach ($array[0] as $arg) {
                  if ($arg != '$PLUGINSDIR$'
                          AND $arg != '$NAGIOSPLUGINSDIR$'
                          AND $arg != '$HOSTADDRESS$'
                          AND $arg != '$MYSQLUSER$'
                          AND $arg != '$MYSQLPASSWORD$') {
                     $arg = str_replace('$', '', $arg);
                     if (!isset($a_arguments[$arg])) {
                        $args .= '!';
                     } else {
                        if (strstr($a_arguments[$arg], "[[HOSTNAME]]")) {
                           $a_arguments[$arg] = str_replace("[[HOSTNAME]]", $hostname, $a_arguments[$arg]);
                        } elseif (strstr($a_arguments[$arg], "[[NETWORKPORTDESCR]]")){
                           if (class_exists("PluginFusioninventoryNetworkPort")) {
                              $pfNetworkPort = new PluginFusioninventoryNetworkPort();
                              $pfNetworkPort->loadNetworkport($data['networkports_id']);
                              $descr = $pfNetworkPort->getValue("ifdescr");
                              $a_arguments[$arg] = str_replace("[[NETWORKPORTDESCR]]", $descr, $a_arguments[$arg]);
                           }
                        } elseif (strstr($a_arguments[$arg], "[[NETWORKPORTNUM]]")){
                           $networkPort = new NetworkPort();
                           $networkPort->getFromDB($data['networkports_id']);
                           $logicalnum = $pfNetworkPort->fields['logical_number'];
                           $a_arguments[$arg] = str_replace("[[NETWORKPORTNUM]]", $logicalnum, $a_arguments[$arg]);
                        } elseif (strstr($a_arguments[$arg], "[[NETWORKPORTNAME]]")){
                           if (isset($data['networkports_id'])
                                   && $data['networkports_id'] > 0) {
                              $networkPort = new NetworkPort();
                              $networkPort->getFromDB($data['networkports_id']);
                              $portname = $pfNetworkPort->fields['name'];
                              $a_arguments[$arg] = str_replace("[[NETWORKPORTNAME]]", $portname, $a_arguments[$arg]);
                           } else if ($a_services[$i]['_HOSTITEMTYPE'] == 'Computer') {
                              // Get networkportname of networkcard defined
                              $pmHostaddress = new PluginMonitoringHostaddress();
                              $a_hostaddresses = $pmHostaddress->find("`itemtype`='Computer'"
                                      . " AND  `items_id`='".$a_services[$i]['_HOSTITEMSID']."'", '', 1);
                              if (count($a_hostaddresses) == 1) {
                                 $a_hostaddress = current($a_hostaddresses);
                                 if ($a_hostaddress['networkports_id'] > 0) {
                                    $networkPort = new NetworkPort();
                                    $networkPort->getFromDB($a_hostaddress['networkports_id']);
                                    $a_arguments[$arg] = str_replace("[[NETWORKPORTNAME]]", $networkPort->fields['name'], $a_arguments[$arg]);
                                 }
                              }
                           }
                        } else if (strstr($a_arguments[$arg], "[")) {
                           $a_arguments[$arg] = PluginMonitoringService::convertArgument($data['id'], $a_arguments[$arg]);
                        }
                        if ($a_arguments == '') {
                           $notadd = 1;
                           if ($notadddescription != '') {
                              $notadddescription .= ", ";
                           }
                           $notadddescription .= "Argument ".$a_arguments[$arg]." do not have value";
                        }
                        $args .= '!'.$a_arguments[$arg];
                        if ($a_arguments[$arg] == ''
                                AND $a_component['alias_command'] != '') {
                           $args .= $a_component['alias_command'];
                        }
                     }
                  }
               }
               // End manage arguments
               if ($a_component['remotesystem'] == 'nrpe') {
                  if ($a_component['alias_command'] != '') {
                     $alias_command = $a_component['alias_command'];
                     if (strstr($alias_command, '[[IP]]')) {
                        $split = explode('-', current($a_hostname));
                        $ip = PluginMonitoringHostaddress::getIp($split[1], $split[0], '');
                        $alias_command = str_replace("[[IP]]", $ip, $alias_command);
                     }
                     $a_services[$i]['check_command'] = PluginMonitoringCommand::$command_prefix . "check_nrpe!".$alias_command;
                  } else {
                     $a_services[$i]['check_command'] = PluginMonitoringCommand::$command_prefix . "check_nrpe!".$pMonitoringCommand->fields['command_name'];
                  }
               } else {
                  $a_services[$i]['check_command'] = PluginMonitoringCommand::$command_prefix . $pMonitoringCommand->fields['command_name'].$args;
               }

               // * Manage event handler
               if ($a_component['plugin_monitoring_eventhandlers_id'] > 0) {
                  if ($pmEventhandler->getFromDB($a_component['plugin_monitoring_eventhandlers_id'])) {
                     $a_services[$i]['event_handler'] = $pmEventhandler->fields['command_name'];
                  }
               }

               if (! empty(self::$shinkenParameters['shinken']['services']['process_perf_data'])) $a_services[$i]['process_perf_data'] = self::$shinkenParameters['shinken']['services']['process_perf_data'];

               if (! empty(self::$shinkenParameters['shinken']['services']['notes'])) $a_services[$i]['notes'] = self::$shinkenParameters['shinken']['services']['notes'];
               if (! empty(self::$shinkenParameters['shinken']['services']['notes_url'])) $a_services[$i]['notes_url'] = self::$shinkenParameters['shinken']['services']['notes_url'];
               if (! empty(self::$shinkenParameters['shinken']['services']['action_url'])) $a_services[$i]['action_url'] = self::$shinkenParameters['shinken']['services']['action_url'];
               if (! empty(self::$shinkenParameters['shinken']['services']['icon_image'])) $a_services[$i]['icon_image'] = self::$shinkenParameters['shinken']['services']['icon_image'];
               if (! empty(self::$shinkenParameters['shinken']['services']['icon_image_alt'])) $a_services[$i]['icon_image_alt'] = self::$shinkenParameters['shinken']['services']['icon_image_alt'];

               // * Contacts
               $a_contacts = array();
               $a_list_contact = $pmContact_Item->find("`itemtype`='PluginMonitoringComponentscatalog'
                  AND `items_id`='".$plugin_monitoring_componentscatalogs_id."'");
               foreach ($a_list_contact as $data_contact) {
                  if ($data_contact['users_id'] > 0) {
                     if (isset($a_contacts_entities[$plugin_monitoring_componentscatalogs_id][$data_contact['users_id']])) {
                        if (in_array($data['entities_id'], $a_contacts_entities[$plugin_monitoring_componentscatalogs_id][$data_contact['users_id']])) {
                           $user->getFromDB($data_contact['users_id']);
                           $a_contacts[] = $user->fields['name'];
                        }
                     }
                  } else if ($data_contact['groups_id'] > 0) {
                     $queryg = "SELECT * FROM `glpi_groups_users`
                        WHERE `groups_id`='".$data_contact['groups_id']."'";
                     $resultg = $DB->query($queryg);
                     while ($datag=$DB->fetch_array($resultg)) {
                        if (in_array($data['entities_id'], $a_contacts_entities[$plugin_monitoring_componentscatalogs_id][$datag['users_id']])) {
                           $user->getFromDB($datag['users_id']);
                           $a_contacts[] = $user->fields['name'];
                        }
                     }
                  }
               }

               $a_contacts_unique = array_unique($a_contacts);
               $a_services[$i]['contacts'] = implode(',', $a_contacts_unique);

               // ** If shinken not use templates or template not defined :
               if (!isset($_SESSION['plugin_monitoring']['servicetemplates'][$a_component['id']])) {
                  $pMonitoringCheck->getFromDB($a_component['plugin_monitoring_checks_id']);
                  $a_services[$i]['check_interval'] = $pMonitoringCheck->fields['check_interval'];
                  $a_services[$i]['retry_interval'] = $pMonitoringCheck->fields['retry_interval'];
                  $a_services[$i]['max_check_attempts'] = $pMonitoringCheck->fields['max_check_attempts'];
                  if ($calendar->getFromDB($a_component['calendars_id'])) {
                     $a_services[$i]['check_period'] = $calendar->fields['name'];
                  }
                  $a_services[$i]['notification_interval'] = '30';
                  $a_services[$i]['notification_period'] = "24x7";
                  $a_services[$i]['notification_options'] = 'w,u,c,r,f,s';
                  $a_services[$i]['process_perf_data'] = '1';
                  $a_services[$i]['active_checks_enabled'] = '1';
                  $a_services[$i]['passive_checks_enabled'] = '1';
                  $a_services[$i]['parallelize_check'] = '1';
                  $a_services[$i]['obsess_over_service'] = '1';
                  $a_services[$i]['check_freshness'] = '1';
                  $a_services[$i]['freshness_threshold'] = '3600';
                  $a_services[$i]['notifications_enabled'] = '1';

                  if (isset($a_services[$i]['event_handler'])) {
                     $a_services[$i]['event_handler_enabled'] = '1';
                  } else {
                     $a_services[$i]['event_handler_enabled'] = '0';
                     // $a_services[$i]['event_handler_enabled'] = '';
                  }
                  $a_services[$i]['flap_detection_enabled'] = '1';
                  $a_services[$i]['failure_prediction_enabled'] = '1';
                  $a_services[$i]['retain_status_information'] = '1';
                  $a_services[$i]['retain_nonstatus_information'] = '1';
                  $a_services[$i]['is_volatile'] = '0';
                  // $a_services[$i]['_httpstink'] = 'NO';
               } else {
                  // Notification options
                  $a_services[$i]['notification_interval'] = '30';
                  $pmComponentscatalog->getFromDB($plugin_monitoring_componentscatalogs_id);
                  if ($pmComponentscatalog->fields['notification_interval'] != '30') {
                     $a_services[$i]['notification_interval'] = $pmComponentscatalog->fields['notification_interval'];
                  }
                  $a_services[$i]['notification_period'] = '24x7';
                  $a_services[$i]['check_period'] = '24x7';
                  if ($calendar->getFromDB($a_component['calendars_id'])) {
                     $a_services[$i]['check_period'] = $calendar->fields['name'];
                  }
               }

               // WebUI user interface ...
               if (isset(self::$shinkenParameters['webui']['serviceIcons']['name'])) {
                  $a_services[$i][self::$shinkenParameters['webui']['serviceIcons']['name']] =
                     self::$shinkenParameters['webui']['serviceIcons']['value'];
               }

               if ($notadd == '1') {
                  unset($a_services[$i]);
                  $input = array();
                  $input['id'] = $data['id'];
                  $input['event'] = $notadddescription;
                  $input['state'] = "CRITICAL";
                  $input['state_type'] = "HARD";
                  $pmService->update($input);
               } else {
                  $i++;
               }
            }
         // }
      }

      PluginMonitoringToolbox::logIfExtradebug(
         'pm-shinken',
         "End generateServicesCfg services\n"
      );

      PluginMonitoringToolbox::logIfExtradebug(
         'pm-shinken',
         "Starting generateServicesCfg business rules ...\n"
      );

      // --------------------------------------------------
      // Business rules services ...
      $pmService = new PluginMonitoringService();
      $pmServicescatalog = new PluginMonitoringServicescatalog();
      $pmBusinessrulegroup = new PluginMonitoringBusinessrulegroup();
      $pmBusinessrule = new PluginMonitoringBusinessrule();
      $pmComponentscatalog_Host = new PluginMonitoringComponentscatalog_Host();
      $pmBusinessrule_component = new PluginMonitoringBusinessrule_component();
      // Prepare individual contacts
      $a_contacts_entities = array();
      $a_list_contact = $pmContact_Item->find("`itemtype`='PluginMonitoringServicescatalog'
         AND `users_id`>0");
      foreach ($a_list_contact as $data) {
         $contactentities = getSonsOf('glpi_entities', $data['entities_id']);
         if (isset($a_contacts_entities[$data['items_id']][$data['users_id']])) {
            $contactentities = array_merge($contactentities, $a_contacts_entities[$data['items_id']][$data['users_id']]);
         }
         $a_contacts_entities[$data['items_id']][$data['users_id']] = $contactentities;
      }
      // Prepare groups contacts
      $group = new Group();
      $a_list_contact = $pmContact_Item->find("`itemtype`='PluginMonitoringServicescatalog'
         AND `groups_id`>0");
      foreach ($a_list_contact as $data) {
         $group->getFromDB($data['groups_id']);
         if ($group->fields['is_recursive'] == 1) {
            $contactentities = getSonsOf('glpi_entities', $group->fields['entities_id']);
         } else {
            $contactentities = array($group->fields['entities_id'] => $group->fields['entities_id']);
         }
         $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_contacts_entities[$data['items_id']][$datag['users_id']])) {
               $contactentities = array_merge($contactentities, $a_contacts_entities[$data['items_id']][$datag['users_id']]);
            }
            $a_contacts_entities[$data['items_id']][$datag['users_id']] = $contactentities;
         }
      }

      // Services catalogs
      $a_listBA = $pmServicescatalog->find("`is_generic`='0'");
      foreach ($a_listBA as $dataBA) {

         if (isset($a_entities_allowed['-1'])
                 OR isset($a_entities_allowed[$dataBA['entities_id']])) {

            $a_grouplist = $pmBusinessrulegroup->find("`plugin_monitoring_servicescatalogs_id`='".$dataBA['id']."'");
            $a_group = array();
            foreach ($a_grouplist as $gdata) {

               $pmBusinessrule_component->replayDynamicServices($gdata['id']);
               $a_listBR = $pmBusinessrule->find(
                       "`plugin_monitoring_businessrulegroups_id`='".$gdata['id']."'");
               foreach ($a_listBR as $dataBR) {
                  if ($pmService->getFromDB($dataBR['plugin_monitoring_services_id'])) {
                     if ($pmService->getHostName() != '') {
                        $hostname = preg_replace("/[^A-Za-z0-9\-_]/","",$pmService->getHostName());

                        if ($gdata['operator'] == 'and'
                                OR $gdata['operator'] == 'or'
                                OR strstr($gdata['operator'], ' of:')) {

                           $operator = '|';
                           if ($gdata['operator'] == 'and') {
                              $operator = '&';
                           }
                           if (!isset($a_group[$gdata['id']])) {
                              $a_group[$gdata['id']] = '';
                              if (strstr($gdata['operator'], ' of:')) {
                                 $a_group[$gdata['id']] = $gdata['operator'];
                              }
                              $a_group[$gdata['id']] .= $hostname.",".preg_replace("/[^A-Za-z0-9\-_]/","",$pmService->getName(array('shinken'=>true)));
                           } else {
                              $a_group[$gdata['id']] .= $operator.$hostname.",".preg_replace("/[^A-Za-z0-9\-_]/","",$pmService->getName(array('shinken'=>true)));
                           }
                        } else {
                           $a_group[$gdata['id']] = $gdata['operator']." ".$hostname.",".preg_replace("/[^A-Za-z0-9\-_]/","",$item->getName());
                        }
                     }
                  }
                  PluginMonitoringToolbox::logIfExtradebug(
                     'pm-shinken',
                     "   - SC group : ".$a_group[$gdata['id']]."\n"
                  );
               }
            }
            if (count($a_group) > 0) {
               $pMonitoringCheck->getFromDB($dataBA['plugin_monitoring_checks_id']);
               $a_services[$i]['check_interval'] = $pMonitoringCheck->fields['check_interval'];
               $a_services[$i]['retry_interval'] = $pMonitoringCheck->fields['retry_interval'];
               $a_services[$i]['max_check_attempts'] = $pMonitoringCheck->fields['max_check_attempts'];
               if ($calendar->getFromDB($dataBA['calendars_id'])) {
                  $a_services[$i]['check_period'] = $calendar->fields['name'];
               }
               $a_services[$i]['host_name'] = self::$shinkenParameters['shinken']['fake_hosts']['name_prefix'] . self::$shinkenParameters['shinken']['fake_hosts']['bp_host'];
               $a_services[$i]['business_impact'] = $dataBA['business_priority'];
               $a_services[$i]['service_description'] = preg_replace("/[^A-Za-z0-9\-_]/","",$dataBA['name']);
               $a_services[$i]['_ENTITIESID'] = $dataBA['id'];
               $a_services[$i]['_ITEMSID'] = $dataBA['id'];
               $a_services[$i]['_ITEMTYPE'] = 'ServiceCatalog';
               $command = "bp_rule!";

               foreach ($a_group as $key=>$value) {
                  if (!strstr($value, "&")
                          AND !strstr($value, "|")) {
                     $a_group[$key] = trim($value);
                  } else {
                     $a_group[$key] = "(".trim($value).")";
                  }
               }
               $a_services[$i]['check_command'] = $command.implode("&", $a_group);
               if ($dataBA['notification_interval'] != '30') {
                  $a_services[$i]['notification_interval'] = $dataBA['notification_interval'];
               } else {
                  $a_services[$i]['notification_interval'] = '30';
               }
               $a_services[$i]['notification_period'] = "24x7";
               $a_services[$i]['notification_options'] = 'w,u,c,r,f,s';
               $a_services[$i]['active_checks_enabled'] = '1';
               $a_services[$i]['process_perf_data'] = '1';
               $a_services[$i]['active_checks_enabled'] = '1';
               $a_services[$i]['passive_checks_enabled'] = '1';
               $a_services[$i]['parallelize_check'] = '1';
               $a_services[$i]['obsess_over_service'] = '1';
               $a_services[$i]['check_freshness'] = '1';
               $a_services[$i]['freshness_threshold'] = '3600';
               $a_services[$i]['notifications_enabled'] = '1';
               $a_services[$i]['event_handler_enabled'] = '0';
               //$a_services[$i]['event_handler'] = 'super_event_kill_everyone!DIE';
               $a_services[$i]['flap_detection_enabled'] = '1';
               $a_services[$i]['failure_prediction_enabled'] = '1';
               $a_services[$i]['retain_status_information'] = '1';
               $a_services[$i]['retain_nonstatus_information'] = '1';
               $a_services[$i]['is_volatile'] = '0';
               // $a_services[$i]['_httpstink'] = 'NO';

               // * Contacts
               $a_contacts = array();
               $a_list_contact = $pmContact_Item->find("`itemtype`='PluginMonitoringServicescatalog'
                  AND `items_id`='".$dataBA['id']."'");
               foreach ($a_list_contact as $data_contact) {
                  if ($data_contact['users_id'] > 0) {
                     if (isset($a_contacts_entities[$dataBA['id']][$data_contact['users_id']])) {
                        if (in_array($data['entities_id'], $a_contacts_entities[$dataBA['id']][$data_contact['users_id']])) {
                           $user->getFromDB($data_contact['users_id']);
                           $a_contacts[] = $user->fields['name'];
                        }
                     }
                  } else if ($data_contact['groups_id'] > 0) {
                     $queryg = "SELECT * FROM `glpi_groups_users`
                        WHERE `groups_id`='".$data_contact['groups_id']."'";
                     $resultg = $DB->query($queryg);
                     while ($datag=$DB->fetch_array($resultg)) {
                        if (in_array($data['entities_id'], $a_contacts_entities[$dataBA['id']][$datag['users_id']])) {
                           $user->getFromDB($datag['users_id']);
                           $a_contacts[] = $user->fields['name'];
                        }
                     }
                  }
               }

               $a_contacts_unique = array_unique($a_contacts);
               $a_services[$i]['contacts'] = implode(',', $a_contacts_unique);
               $i++;
            }
         }
      }

      PluginMonitoringToolbox::logIfExtradebug(
         'pm-shinken',
         "End generateServicesCfg business rules\n"
      );

      PluginMonitoringToolbox::logIfExtradebug(
         'pm-shinken',
         "Starting generateServicesCfg business rules templates ...\n"
      );

      // Services catalogs templates
      // TODO : correctly test and improve it !
      $a_listBA = $pmServicescatalog->find("`is_generic`='1'");
      foreach ($a_listBA as $dataBA) {
         PluginMonitoringToolbox::logIfExtradebug(
            'pm-shinken',
            "   - SC : ".$dataBA['id']."\n"
         );

         if (isset($a_entities_allowed['-1'])
                 OR isset($a_entities_allowed[$dataBA['entities_id']])) {

            $pmServicescatalog->getFromDB($dataBA['id']);

            $a_entitiesServices = $pmServicescatalog->getGenericServicesEntities();
            foreach ($a_entitiesServices as $idEntity=>$a_entityServices) {
               // New entity ... so new business rule !
               PluginMonitoringToolbox::logIfExtradebug(
                  'pm-shinken',
                  "   - SC templated services for an entity : ".$idEntity."\n"
               );

               $pmDerivatedSC = new PluginMonitoringServicescatalog();
               $a_derivatedSC = $pmDerivatedSC->find("`entities_id`='$idEntity' AND `name` LIKE '".$dataBA['name']."%'");
               foreach ($a_derivatedSC as $a_derivated) {
                  PluginMonitoringToolbox::logIfExtradebug(
                     'pm-shinken',
                     "   - a_derivated : ".$a_derivated['name']."\n"
                  );
                  $a_derivatedSC = $a_derivated;
               }

               $a_group = array();
               foreach ($a_entityServices as $services) {
                  if ($pmService->getFromDB($services['serviceId'])) {
                     // Toolbox::logInFile("pm-shinken", "   - SC templated service entity : ".$services['entityId'].", service :  ".$pmService->getName(true)." on ".$pmService->getHostName()."\n");
                     if ($pmService->getHostName() != '') {
                        $hostname = preg_replace("/[^A-Za-z0-9\-_]/","",$pmService->getHostName());

                        $serviceFakeId = $services['entityId'];

                        $pmBusinessrulegroup->getFromDB($services['BRgroupId']);
                        $BRoperator = $pmBusinessrulegroup->getField('operator');
                        if ($BRoperator == 'and'
                                OR $BRoperator == 'or'
                                OR strstr($BRoperator, ' of:')) {

                           $operator = '|';
                           if ($BRoperator == 'and') {
                              $operator = '&';
                           }
                           if (!isset($a_group[$serviceFakeId])) {
                              $a_group[$serviceFakeId] = '';
                              if (strstr($BRoperator, ' of:')) {
                                 $a_group[$serviceFakeId] = $BRoperator;
                              }
                              $a_group[$serviceFakeId] .= $hostname.",".preg_replace("/[^A-Za-z0-9\-_]/","",$pmService->getName(array('shinken'=>true)));
                           } else {
                              $a_group[$serviceFakeId] .= $operator.$hostname.",".preg_replace("/[^A-Za-z0-9\-_]/","",$pmService->getName(array('shinken'=>true)));
                           }
                        } else {
                           $a_group[$serviceFakeId] = $BRoperator." ".$hostname.",".preg_replace("/[^A-Za-z0-9\-_]/","",$pmService->getHostName());
                        }
                        // Toolbox::logInFile("pm-shinken", "   - SCT group : ".$a_group[$serviceFakeId]."\n");
                     }
                  }
               }
               if (count($a_group) > 0) {
                  $pMonitoringCheck->getFromDB($a_derivatedSC['plugin_monitoring_checks_id']);
                  $a_services[$i]['check_interval'] = $pMonitoringCheck->fields['check_interval'];
                  $a_services[$i]['retry_interval'] = $pMonitoringCheck->fields['retry_interval'];
                  $a_services[$i]['max_check_attempts'] = $pMonitoringCheck->fields['max_check_attempts'];
                  if ($calendar->getFromDB($a_derivatedSC['calendars_id'])) {
                     $a_services[$i]['check_period'] = $calendar->fields['name'];
                  }
                  $a_services[$i]['host_name'] = preg_replace("/[^A-Za-z0-9\-_]/","",$a_derivatedSC['name']);
                  $a_services[$i]['host_name'] = self::$shinkenParameters['shinken']['fake_hosts']['name_prefix'] . self::$shinkenParameters['shinken']['fake_hosts']['bp_host'];
                  $a_services[$i]['business_impact'] = $a_derivatedSC['business_priority'];
                  $a_services[$i]['service_description'] = preg_replace("/[^A-Za-z0-9\-_]/","",$a_derivatedSC['name']);
                  $a_services[$i]['_ENTITIESID'] = $a_derivatedSC['entities_id'];
                  $a_services[$i]['_ITEMSID'] = $a_derivatedSC['id'];
                  $a_services[$i]['_ITEMTYPE'] = 'ServiceCatalog';
                  $command = "bp_rule!";

                  foreach ($a_group as $key=>$value) {
                     if (!strstr($value, "&")
                             AND !strstr($value, "|")) {
                        $a_group[$key] = trim($value);
                     } else {
                        $a_group[$key] = "(".trim($value).")";
                     }
                  }
                  $a_services[$i]['check_command'] = $command.implode("&", $a_group);
                  if ($a_derivatedSC['notification_interval'] != '30') {
                     $a_services[$i]['notification_interval'] = $a_derivatedSC['notification_interval'];
                  } else {
                     $a_services[$i]['notification_interval'] = '30';
                  }
                  $a_services[$i]['notification_period'] = "24x7";
                  $a_services[$i]['notification_options'] = 'w,u,c,r,f,s';
                  $a_services[$i]['active_checks_enabled'] = '1';
                  $a_services[$i]['process_perf_data'] = '1';
                  $a_services[$i]['active_checks_enabled'] = '1';
                  $a_services[$i]['passive_checks_enabled'] = '1';
                  $a_services[$i]['parallelize_check'] = '1';
                  $a_services[$i]['obsess_over_service'] = '1';
                  $a_services[$i]['check_freshness'] = '1';
                  $a_services[$i]['freshness_threshold'] = '3600';
                  $a_services[$i]['notifications_enabled'] = '1';
                  $a_services[$i]['event_handler_enabled'] = '0';
                  //$a_services[$i]['event_handler'] = 'super_event_kill_everyone!DIE';
                  $a_services[$i]['flap_detection_enabled'] = '1';
                  $a_services[$i]['failure_prediction_enabled'] = '1';
                  $a_services[$i]['retain_status_information'] = '1';
                  $a_services[$i]['retain_nonstatus_information'] = '1';
                  $a_services[$i]['is_volatile'] = '0';
                  // $a_services[$i]['_httpstink'] = 'NO';

                  // * Contacts
                  $a_contacts = array();
                  $a_list_contact = $pmContact_Item->find("`itemtype`='PluginMonitoringServicescatalog'
                     AND `items_id`='".$dataBA['id']."'");
                  foreach ($a_list_contact as $data_contact) {
                     if ($data_contact['users_id'] > 0) {
                        if (isset($a_contacts_entities[$dataBA['id']][$data_contact['users_id']])) {
                           if (in_array($data['entities_id'], $a_contacts_entities[$dataBA['id']][$data_contact['users_id']])) {
                              $user->getFromDB($data_contact['users_id']);
                              $a_contacts[] = $user->fields['name'];
                           }
                        }
                     } else if ($data_contact['groups_id'] > 0) {
                        $queryg = "SELECT * FROM `glpi_groups_users`
                           WHERE `groups_id`='".$data_contact['groups_id']."'";
                        $resultg = $DB->query($queryg);
                        while ($datag=$DB->fetch_array($resultg)) {
                           if (in_array($data['entities_id'], $a_contacts_entities[$dataBA['id']][$datag['users_id']])) {
                              $user->getFromDB($datag['users_id']);
                              $a_contacts[] = $user->fields['name'];
                           }
                        }
                     }
                  }

                  $a_contacts_unique = array_unique($a_contacts);
                  $a_services[$i]['contacts'] = implode(',', $a_contacts_unique);
                  $i++;
               }
            }
         }
      }

      PluginMonitoringToolbox::logIfExtradebug(
         'pm-shinken',
         "End generateServicesCfg business rules templates\n"
      );

      if ($file == "1") {
         $config = "# Generated by plugin monitoring for GLPI\n# on ".date("Y-m-d H:i:s")."\n\n";

         foreach ($a_services as $data) {
            $config .= $this->writeFile("service", $data);
         }
         return array('services.cfg', $config);

      } else {
         return $a_services;
      }
   }
Example #27
0
 static function selectGroupOnAdd($item)
 {
     global $CFG_GLPI, $DB;
     if (isset($item->input['_auto_import']) || isset($item->input['bypassgrouponadd'])) {
         return;
     }
     $peGroup_group = new self();
     if ($_SESSION['glpiactiveprofile']['interface'] == 'central') {
         $peConfig = new PluginEscalationConfig();
         if ($peConfig->getValue('workflow', $item->fields['entities_id']) == '1') {
             if (isset($_POST['_groups_id_assign']) && $_POST['_groups_id_assign'] > 0) {
                 if (isset($_SESSION['plugin_escalation_files'])) {
                     $_FILES = $_SESSION['plugin_escalation_files'];
                 }
                 return;
             } else {
                 $group = new Group();
                 Html::header(__('Administration'), '', "maintain", "ticket");
                 if (isset($_POST['dropdown__groups_id_requester']) && $_POST['dropdown__groups_id_requester'] > 0) {
                     $_SESSION['plugin_escalation_groups_id_requester'] = $_POST['dropdown__groups_id_requester'];
                 }
                 if (isset($_FILES)) {
                     foreach ($_FILES['filename']['tmp_name'] as $numfile => $datafile) {
                         if ($datafile != '') {
                             $split = explode("/", $datafile);
                             Document::renameForce($datafile, GLPI_DOC_DIR . "/_tmp/" . end($split));
                             $_FILES['filename']['tmp_name'][$numfile] = GLPI_DOC_DIR . "/_tmp/" . end($split);
                         }
                     }
                     $_SESSION['plugin_escalation_files'] = $_FILES;
                 }
                 echo '<form action="' . $CFG_GLPI['root_doc'] . '/front/ticket.form.php"
               enctype="multipart/form-data" name="form_ticket" method="post">';
                 echo "<table class='tab_cadre_fixe'>";
                 echo "<tr class='tab_bg_1'>";
                 echo "<th colspan='2'>Sélection du groupe de techniciens</th>";
                 echo "</tr>";
                 echo "<tr class='tab_bg_1'>";
                 echo "<td>";
                 echo __('Group in charge of the ticket') . "&nbsp;:";
                 echo "</td>";
                 echo "<td>";
                 $a_groups = array();
                 foreach ($_SESSION['glpigroups'] as $groups_id) {
                     $group->getFromDB($groups_id);
                     $a_groups[$groups_id] = $group->getName();
                     $queryg = "SELECT * FROM `" . $peGroup_group->getTable() . "`\n                     WHERE `groups_id_source` = '" . $groups_id . "' ";
                     $resultg = $DB->query($queryg);
                     while ($datag = $DB->fetch_array($resultg)) {
                         $group->getFromDB($datag['groups_id_destination']);
                         $a_groups[$groups_id . "_" . $datag['groups_id_destination']] = "&nbsp;&nbsp;&nbsp;> " . $group->getName();
                     }
                 }
                 $rand = Dropdown::showFromArray("_groups_id_assign_escalation", $a_groups);
                 $params = array('groups_id' => '__VALUE__', 'entity' => $_POST['entities_id'], 'rand' => $rand);
                 Ajax::updateItemOnSelectEvent("dropdown__groups_id_assign" . $rand, "show_assignuser{$rand}", $CFG_GLPI["root_doc"] . "/plugins/escalation/ajax/dropdownUserassign.php", $params);
                 echo "</tr>";
                 echo "<tr class='tab_bg_1'>";
                 echo "<td colspan='2'>";
                 foreach ($_POST as $key => $value) {
                     if (is_array($value)) {
                         foreach ($value as $keyy => $valuee) {
                             echo '<input type="hidden" name="' . $key . '[' . $keyy . ']" value="' . $valuee . '" />';
                         }
                     } else {
                         if ($key == 'content') {
                             $value = Html::cleanPostForTextArea(Toolbox::clean_cross_side_scripting_deep($value));
                             echo '<textarea name="' . $key . '" style="display:none;">' . $value . '</textarea>';
                         } else {
                             if ($key == 'dropdown__groups_id_requester') {
                                 echo '<input type="hidden" name="_groups_id_requester" value="' . $value . '" />';
                             } else {
                                 $value = Html::cleanInputText(Toolbox::clean_cross_side_scripting_deep(stripslashes($value)));
                                 echo '<input type="hidden" name="' . $key . '" value="' . $value . '" />';
                             }
                         }
                     }
                 }
                 if (!isset($_POST['_users_id_assign']) or $_POST['_users_id_assign'] == '0') {
                     echo "<span id='show_assignuser{$rand}'></span>";
                 }
                 echo "</td>";
                 echo "</tr>";
                 echo "<tr class='tab_bg_1'>";
                 echo "<td colspan='2' align='center'>";
                 echo "<input type='submit' name='add' value=\"" . __('Add') . "\" class='submit'>";
                 echo "</td>";
                 echo "</tr>";
                 echo "</table>";
                 Html::closeForm();
                 Html::footer();
                 exit;
             }
         }
     }
 }