Esempio n. 1
0
 static function displayTabContentForItem(CommonGLPI $item, $tabnum = 1, $withtemplate = 0)
 {
     if ($item->getID() > -1) {
         $pmEntity = new PluginMonitoringEntity();
         $pmHostconfig = new PluginMonitoringHostconfig();
         $pmHostconfig->showForm($item->getID(), "Entity");
         $pmEntity->showForm($item->fields['id']);
     }
     return true;
 }
 function sendAcknowledge($services_id)
 {
     global $DB;
     $pmService = new PluginMonitoringService();
     $pmComponent = new PluginMonitoringComponent();
     $pmTag = new PluginMonitoringTag();
     $pmService->getFromDB($services_id);
     $hostname = '';
     $queryh = "SELECT * FROM `glpi_plugin_monitoring_componentscatalogs_hosts` \n         WHERE `id` = '" . $pmService->fields['plugin_monitoring_componentscatalogs_hosts_id'] . "'\n         LIMIT 1";
     $resulth = $DB->query($queryh);
     while ($datah = $DB->fetch_array($resulth)) {
         $itemtype = $datah['itemtype'];
         $item = new $itemtype();
         if ($item->getFromDB($datah['items_id'])) {
             $hostname = $itemtype . "-" . $datah['items_id'] . "-" . preg_replace("/[^A-Za-z0-9]/", "", $item->fields['name']);
         }
     }
     $a_component = current($pmComponent->find("`id`='" . $pmService->fields['plugin_monitoring_components_id'] . "'", "", 1));
     $service_description = preg_replace("/[^A-Za-z0-9]/", "", $a_component['name']) . "-" . $pmService->fields['id'];
     $tag = PluginMonitoringEntity::getTagByEntities($pmService->fields['entities_id']);
     $ip = $pmTag->getIP($tag);
     $auth = $pmTag->getAuth($tag);
     $url = 'http://' . $ip . ':7760/';
     $action = 'acknowledge';
     $a_fields = array('host_name' => urlencode($hostname), 'service_description' => urlencode($service_description), 'author' => urlencode($_SESSION['glpiname']), 'comment' => urlencode(''));
     $this->sendCommand($url, $action, $a_fields, '', $auth);
 }
Esempio n. 3
0
   function generateContactsCfg($file=0, $tag='') {
      global $DB;

      $pmEntity      = new PluginMonitoringEntity();
      $calendar      = new Calendar();

      PluginMonitoringToolbox::logIfExtradebug(
         'pm-shinken',
         "Starting generateContactsCfg ($tag) ...\n"
      );

      $a_users_used = array();
      $a_contacts = array();
      // Add default contact 'monitoring' for fake hosts
//      $a_calendars = current($calendar->find("", "", 1));
//      $cal = '24x7';
//      if (isset($a_calendars['name'])) {
//         $cal = $a_calendars['name'];
//      }
//      $a_contacts[-1] = array(
//          'contact_name'                   => 'monitoring',
//          'alias'                          => 'monitoring',
//          'host_notifications_enabled'     => '0',
//          'service_notifications_enabled'  => '0',
//          'service_notification_period'    => $cal,
//          'host_notification_period'       => $cal,
//          'service_notification_options' => '',
//          'host_notification_options'    => '',
//          'service_notification_commands'  => '',
//          'host_notification_commands'     => '',
//          'email'                          => '',
//          'pager'                          => '',
//      );


      $a_entities_allowed = $pmEntity->getEntitiesByTag($tag);
      $a_entities_list = array();
      foreach ($a_entities_allowed as $entity) {
         $a_entities_list = getSonsOf("glpi_entities", $entity);
      }
	  // Always add root entity
      $a_entities_list[] = '0';
      $where = '';
      if (! isset($a_entities_allowed['-1'])) {
         $where = getEntitiesRestrictRequest("WHERE", "glpi_plugin_monitoring_contacts_items", '', $a_entities_list);
      }


      $i=0;

      $query = "SELECT * FROM `glpi_plugin_monitoring_contacts_items` $where";
      // Toolbox::logInFile("pm-shinken", "- Contacts query: $query\n");
      $result = $DB->query($query);
      while ($data=$DB->fetch_array($result)) {
         if ($data['users_id'] > 0) {
            if ((!isset($a_users_used[$data['users_id']]))) {
               $a_contacts = $this->_addContactUser($a_contacts, $data['users_id'], $i);
               $i++;
               $a_users_used[$data['users_id']] = 1;
            }
         } else if ($data['groups_id'] > 0) {
            $queryg = "SELECT * FROM `glpi_groups_users`
               WHERE `groups_id`='".$data['groups_id']."'";
            $resultg = $DB->query($queryg);
            while ($datag=$DB->fetch_array($resultg)) {
               if ((!isset($a_users_used[$datag['users_id']]))) {
                  $a_contacts = $this->_addContactUser($a_contacts, $datag['users_id'], $i);
                  $i++;
                  $a_users_used[$datag['users_id']] = 1;
               }
            }
         }
      }
      // Add user monitoring
      $user = new User();
      $a_monit_user = current($user->find("`name`='monitoring'", '', 1));
      if ((!isset($a_users_used[$a_monit_user['id']]))) {
         $a_contacts = $this->_addContactUser($a_contacts, $a_monit_user['id'], $i);
      }

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

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

         foreach ($a_contacts as $data) {
            $config .= $this->writeFile("contact", $data);
         }
         return array('contacts.cfg', $config);

      } else {
         return $a_contacts;
      }
   }
Esempio n. 4
0
  Plugin Monitoring for GLPI is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  GNU Affero General Public License for more details.

  You should have received a copy of the GNU Affero General Public License
  along with Monitoring. If not, see <http://www.gnu.org/licenses/>.

  ------------------------------------------------------------------------

  @package   Plugin Monitoring for GLPI
  @author    David Durieux
  @co-author 
  @comment   
  @copyright Copyright (c) 2011-2013 Plugin Monitoring for GLPI team
  @license   AGPL License 3.0 or (at your option) any later version
             http://www.gnu.org/licenses/agpl-3.0-standalone.html
  @link      https://forge.indepnet.net/projects/monitoring/
  @since     2011

  ------------------------------------------------------------------------
*/
include "../../../inc/includes.php";
PluginMonitoringProfile::checkRight("config", "w");
Html::header(__('Monitoring', 'monitoring'), $_SERVER["PHP_SELF"], "plugins", "monitoring", "entity");
if (isset($_POST["update"])) {
    $pmEntity = new PluginMonitoringEntity();
    $pmEntity->update($_POST);
    Html::back();
}
Html::footer();
Esempio n. 5
0
function plugin_headings_monitoring_entitytag($item)
{
    $pmEntity = new PluginMonitoringEntity();
    $pmHostconfig = new PluginMonitoringHostconfig();
    $pmHostconfig->showForm($item->getID(), "Entity");
    $pmEntity->showForm($item->fields['id']);
}
 function sendDowntime($host_id = -1, $service_id = -1, $author = '', $comment = '', $flexible = '0', $start_time = '0', $end_time = '0', $duration = '3600', $operation = '')
 {
     global $DB;
     if ($host_id == -1 && $service_id == -1) {
         return false;
     }
     $pmTag = new PluginMonitoringTag();
     $pmService = new PluginMonitoringService();
     $pmService->getFromDB($service_id);
     $service_description = $pmService->getName(array('shinken' => '1'));
     $pmHost = new PluginMonitoringHost();
     $pmHost->getFromDB($host_id == -1 ? $pmService->getHostID() : $host_id);
     $hostname = $pmHost->getName(true);
     // Downtime an host ...
     $acknowledgeServiceOnly = true;
     $a_fields = array();
     if ($host_id == -1) {
         $tag = PluginMonitoringEntity::getTagByEntities($pmService->getEntityID());
     } else {
         // ... one service of the host.
         $tag = PluginMonitoringEntity::getTagByEntities($pmHost->getEntityID());
     }
     $ip = $pmTag->getIP($tag);
     $auth = $pmTag->getAuth($tag);
     $port = $pmTag->getPort($tag);
     $url = 'http://' . $ip . ':' . $port . '/';
     $action = 'downtime';
     $a_fields = array('action' => empty($operation) ? 'add' : $operation, 'host_name' => $hostname, 'service_description' => $service_description, 'author' => $author, 'comment' => mb_convert_encoding($comment, "iso-8859-1"), 'flexible' => $flexible, 'start_time' => PluginMonitoringServiceevent::convert_datetime_timestamp($start_time), 'end_time' => PluginMonitoringServiceevent::convert_datetime_timestamp($end_time), 'trigger_id' => '0', 'duration' => $duration);
     // Send downtime command ...
     return $this->sendCommand($url, $action, $a_fields, '', $auth);
 }
 function generateServicesCfg($file = 0, $tag = '')
 {
     global $DB;
     $pMonitoringCommand = new PluginMonitoringCommand();
     $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;
     }
     $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("PluginFusinvsnmpNetworkPort")) {
                                 $pfNetworkPort = new PluginFusinvsnmpNetworkPort();
                                 $pfNetworkPort->loadNetworkport($data['networkports_id']);
                                 $descr = '';
                                 $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'] != '') {
                     $a_services[$i]['check_command'] = "check_nrpe!" . $a_component['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;
             }
             // * 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 (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']])) {
                         //                  $pmContact->getFromDB($data_contact['plugin_monitoring_contacts_id']);
                         $user->getFromDB($data_contact['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';
                 $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';
             }
             $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;
     }
 }
 function generateTimeperiodsCfg($file = 0, $tag = '')
 {
     global $DB;
     PluginMonitoringToolbox::logIfExtradebug('pm-shinken', "Starting generateTimeperiodsCfg ...\n");
     $calendar = new Calendar();
     $calendarSegment = new CalendarSegment();
     $calendar_Holiday = new Calendar_Holiday();
     $holiday = new Holiday();
     $hostconfig = new PluginMonitoringHostconfig();
     $pmEntity = new PluginMonitoringEntity();
     // Get list of entities
     $a_entities_allowed = $pmEntity->getEntitiesByTag($tag);
     $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_entities", '', $a_entities_list);
     }
     foreach ($a_entities_list as $entities_id) {
         $jetlag = $hostconfig->getValueAncestor('jetlag', $entities_id);
         $a_entities_list[$entities_id] = $jetlag;
     }
     // Get all calendars of components
     $cals_entities = array();
     $query = "SELECT `entities_id`, `calendars_id`\n         FROM `glpi_plugin_monitoring_services`\n         LEFT JOIN `glpi_plugin_monitoring_components`\n            ON `plugin_monitoring_components_id` = `glpi_plugin_monitoring_components`.`id` ";
     if ($where == '') {
         $query .= "WHERE `glpi_plugin_monitoring_components`.`id` IS NOT NULL";
     } else {
         $query .= $where . " AND `glpi_plugin_monitoring_components`.`id` IS NOT NULL";
     }
     $result = $DB->query($query);
     while ($data = $DB->fetch_array($result)) {
         if (!isset($cals_entities[$data['entities_id']])) {
             $cals_entities[$data['entities_id']] = array();
         }
         $cals_entities[$data['entities_id']][$data['calendars_id']] = $data['calendars_id'];
     }
     // get all calendars of servciescatalog
     $query = "SELECT `entities_id`, `calendars_id`\n         FROM `glpi_plugin_monitoring_servicescatalogs` " . $where;
     $result = $DB->query($query);
     while ($data = $DB->fetch_array($result)) {
         if (!isset($cals_entities[$data['entities_id']])) {
             $cals_entities[$data['entities_id']] = array();
         }
         $cals_entities[$data['entities_id']][$data['calendars_id']] = $data['calendars_id'];
     }
     // Get all calendars of contacts TODO
     $calendars_added = array();
     $a_timeperiods = array();
     $i = 0;
     foreach ($cals_entities as $entities_id => $calendars) {
         foreach ($calendars as $calendars_id) {
             $jetlag = $a_entities_list[$entities_id];
             if (!isset($calendars_added[$calendars_id . "-" . $jetlag])) {
                 $calendars_added[$calendars_id . "-" . $jetlag] = 1;
                 $calendar->getFromDB($calendars_id);
                 $tmp = array();
                 $tmp['timeperiod_name'] = $calendar->fields['name'];
                 $tmp['alias'] = $calendar->fields['name'];
                 $a_listsegment = $calendarSegment->find("`calendars_id`='" . $calendar->fields['id'] . "'");
                 $a_cal = array();
                 foreach ($a_listsegment as $datasegment) {
                     $begin = preg_replace("/:00\$/", "", $datasegment['begin']);
                     $end = preg_replace("/:00\$/", "", $datasegment['end']);
                     $day = "";
                     switch ($datasegment['day']) {
                         case "0":
                             $day = "sunday";
                             break;
                         case "1":
                             $day = "monday";
                             break;
                         case "2":
                             $day = "tuesday";
                             break;
                         case "3":
                             $day = "wednesday";
                             break;
                         case "4":
                             $day = "thursday";
                             break;
                         case "5":
                             $day = "friday";
                             break;
                         case "6":
                             $day = "saturday";
                             break;
                     }
                     $a_cal[$day][] = $begin . "-" . $end;
                 }
                 foreach ($a_cal as $day => $a_times) {
                     $tmp[$day] = implode(',', $a_times);
                 }
                 $a_cholidays = $calendar_Holiday->find("`calendars_id`='" . $calendar->fields['id'] . "'");
                 foreach ($a_cholidays as $a_choliday) {
                     $holiday->getFromDB($a_choliday['holidays_id']);
                     if ($holiday->fields['is_perpetual'] == 1 && $holiday->fields['begin_date'] == $holiday->fields['end_date']) {
                         $datetime = strtotime($holiday->fields['begin_date']);
                         $tmp[strtolower(date('F', $datetime)) . ' ' . date('j', $datetime)] = '00:00-00:00';
                     }
                 }
                 if ($jetlag == 0) {
                     $tmp['timeperiod_name'] = $tmp['timeperiod_name'];
                     $tmp['alias'] = $tmp['alias'];
                 } else {
                     $tmp['timeperiod_name'] = $tmp['timeperiod_name'] . "-" . $jetlag;
                     $tmp['alias'] = $tmp['alias'] . "-" . $jetlag;
                 }
                 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
                 $saturday = '';
                 $reportHours = 0;
                 $beforeday = 'saturday';
                 foreach ($days as $numday => $day) {
                     if (isset($tmp[$day])) {
                         $splitDay = explode(',', $tmp[$day]);
                         $toAdd = '';
                         if ($reportHours > 0) {
                             $toAdd = '00:00-' . sprintf("%02s", $reportHours) . ':00';
                             $reportHours = 0;
                         }
                         foreach ($splitDay as $num => $hourMinute) {
                             $previous_begin = 0;
                             $beginEnd = explode('-', $hourMinute);
                             // ** Begin **
                             $split = explode(':', $beginEnd[0]);
                             $split[0] += $jetlag;
                             if ($split[0] > 24) {
                                 //$reportHours = $split[0] - 24;
                                 unset($splitDay[$num]);
                             } else {
                                 if ($split[0] < 0) {
                                     $reportHours = $split[0];
                                     $previous_begin = 24 + $split[0];
                                     $split[0] = '00';
                                 }
                                 $beginEnd[0] = sprintf("%02s", $split[0]) . ':' . $split[1];
                                 // ** End **
                                 $split = explode(':', $beginEnd[1]);
                                 $split[0] += $jetlag;
                                 if ($split[0] < 0) {
                                     if ($numday - 1 == -1) {
                                         $saturday .= "," . sprintf("%02s", $previous_begin) . ":00-" . sprintf("%02s", 24 + $split[0]) . ":00";
                                     } else {
                                         $tmp[$days[$numday - 1]] .= "," . sprintf("%02s", $previous_begin) . ":00-" . sprintf("%02s", 24 + $split[0]) . ":00";
                                     }
                                     unset($splitDay[$num]);
                                 } else {
                                     if ($split[0] > 24) {
                                         $reportHours = $split[0] - 24;
                                         $split[0] = 24;
                                     }
                                     $beginEnd[1] = sprintf("%02s", $split[0]) . ':' . $split[1];
                                     $hourMinute = implode('-', $beginEnd);
                                     $splitDay[$num] = $hourMinute;
                                 }
                             }
                         }
                         if ($reportHours < 0) {
                             //                     if (!isset($tmp[$beforeday])) {
                             //                        $tmp[$beforeday] = array();
                             //                     }
                             //                     $splitBeforeDay = explode(',', $tmp[$beforeday]);
                             //                     $splitBeforeDay[] = sprintf("%02s", (24 + $reportHours)).':00-24:00';
                             //                     $tmp[$beforeday] = implode(',', $splitBeforeDay);
                             $reportHours = 0;
                         }
                         if (!empty($toAdd)) {
                             array_unshift($splitDay, $toAdd);
                         }
                         $tmp[$day] = implode(',', $splitDay);
                     } else {
                         if ($reportHours > 0) {
                             //$tmp[$day] = '00:00-'.$reportHours.':00';
                             $reportHours = 0;
                         }
                     }
                     $beforeday = $day;
                 }
                 // Manage for report hours from saturday to sunday
                 if ($reportHours > 0) {
                     $splitDay = explode(',', $tmp['sunday']);
                     array_unshift($splitDay, '00:00-' . sprintf("%02s", $reportHours) . ':00');
                     $tmp['sunday'] = implode(',', $splitDay);
                 }
                 if ($saturday != '') {
                     if (isset($tmp['saturday'])) {
                         $tmp['saturday'] .= $saturday;
                     } else {
                         $tmp['saturday'] = $saturday;
                     }
                 }
                 // concatain if need
                 foreach ($days as $day) {
                     if (isset($tmp[$day])) {
                         $splitDay = explode(',', $tmp[$day]);
                         $beforeHour = '';
                         $beforeNum = 0;
                         foreach ($splitDay as $num => $data) {
                             if (substr($data, 0, 2) == $beforeHour) {
                                 $splitDay[$beforeNum] = substr($splitDay[$beforeNum], 0, 6) . substr($data, 6, 5);
                                 $beforeHour = substr($data, 6, 2);
                                 unset($splitDay[$num]);
                             } else {
                                 $beforeHour = substr($data, 6, 2);
                                 $beforeNum = $num;
                             }
                         }
                         $tmp[$day] = implode(',', $splitDay);
                     }
                 }
                 $a_timeperiods[$i] = $tmp;
                 $i++;
             }
         }
     }
     PluginMonitoringToolbox::logIfExtradebug('pm-shinken', "End generateTimeperiodsCfg\n");
     if ($file == "1") {
         $config = "# Generated by plugin monitoring for GLPI\n# on " . date("Y-m-d H:i:s") . "\n\n";
         foreach ($a_timeperiods as $data) {
             $config .= $this->writeFile("timeperiod", $data);
         }
         return array('timeperiods.cfg', $config);
     } else {
         return $a_timeperiods;
     }
 }