static function displayTabContentForItem(CommonGLPI $item, $tabnum = 1, $withtemplate = 0)
 {
     if ($tabnum == 49) {
         $pmServicescatalog = new PluginMonitoringServicescatalog();
         $pmDisplay = new PluginMonitoringDisplay();
         $pmDisplay->showCounters("Businessrules");
         $pmServicescatalog->showChecks();
     }
     return true;
 }
  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("servicescatalog", "w");
$dropdown = new PluginMonitoringServicescatalog();
if (isset($_GET['detail']) and isset($_GET['id'])) {
    Html::header(__('Monitoring', 'monitoring'), $_SERVER["PHP_SELF"], "plugins", "monitoring", "servicescatalog");
    $dropdown->showBADetail($_GET['id']);
    Html::footer();
} else {
    Html::header(__('Monitoring', 'monitoring'), $_SERVER["PHP_SELF"], "plugins", "monitoring", "servicescatalog");
    include GLPI_ROOT . "/front/dropdown.common.form.php";
}
 /**
  * This fonction search if a services catalog has a resource deleted
  *
  */
 function servicescatalogMessage()
 {
     global $DB;
     $pmServicescatalog = new PluginMonitoringServicescatalog();
     $input = '';
     $a_catalogs = array();
     $query = "SELECT `plugin_monitoring_servicescatalogs_id` FROM `glpi_plugin_monitoring_businessrulegroups`\n\n         LEFT JOIN `glpi_plugin_monitoring_businessrules` ON `glpi_plugin_monitoring_businessrulegroups`.`id` = `plugin_monitoring_businessrulegroups_id`\n\n         LEFT JOIN `glpi_plugin_monitoring_services` ON `plugin_monitoring_services_id` = `glpi_plugin_monitoring_services`.`id`\n\n         WHERE `glpi_plugin_monitoring_services`.`id` IS NULL";
     $result = $DB->query($query);
     while ($data = $DB->fetch_array($result)) {
         $pmServicescatalog->getFromDB($data['plugin_monitoring_servicescatalogs_id']);
         $a_catalogs[$data['plugin_monitoring_servicescatalogs_id']] = $pmServicescatalog->getLink();
     }
     if (count($a_catalogs) > 0) {
         $input = __('Services catalog with resources not available', 'monitoring') . " : <br/>";
         $input .= implode(" - ", $a_catalogs);
     }
     return $input;
 }
GLPI is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with GLPI; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
--------------------------------------------------------------------------
*/
// ----------------------------------------------------------------------
// Original Author of file: David DURIEUX
// Purpose of file:
// ----------------------------------------------------------------------
// Direct access to file
if (strpos($_SERVER['PHP_SELF'], "updateWidgetServicescatalog.php")) {
    include "../../../inc/includes.php";
    header("Content-Type: text/html; charset=UTF-8");
    Html::header_nocache();
}
session_write_close();
if (!defined('GLPI_ROOT')) {
    die("Can not acces directly to this file");
}
Session::checkLoginUser();
if (!isset($_SESSION['plugin_monitoring_reduced_interface'])) {
    $_SESSION['plugin_monitoring_reduced_interface'] = false;
}
$pmServicescatalog = new PluginMonitoringServicescatalog();
$pmServicescatalog->showWidgetFrame($_GET['id'], $_SESSION['plugin_monitoring_reduced_interface'], isset($_GET['is_minemap']) ? $_GET['is_minemap'] : false);
 function displayItem($data, $config)
 {
     global $CFG_GLPI;
     $itemtype = $data['itemtype'];
     $itemtype2 = '';
     if ($itemtype == 'host' || $itemtype == 'service') {
         $itemtype2 = $itemtype;
         $itemtype = 'PluginMonitoringDisplayview';
     }
     $item = new $itemtype();
     $content = '';
     $title = $item->getTypeName();
     $event = '';
     $width = '';
     if ($itemtype == "PluginMonitoringService") {
         $content = $item->showWidget($data['items_id'], $data['extra_infos']);
         if (!isset($item->fields['plugin_monitoring_components_id'])) {
             return false;
         }
         $title .= " : <a href=\"" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/front/display.form.php?itemtype=PluginMonitoringService&items_id=" . $data['items_id'] . "\">" . Dropdown::getDropdownName(getTableForItemType('PluginMonitoringComponent'), $item->fields['plugin_monitoring_components_id']);
         $title .= '</a> ' . __('on', 'monitoring') . ' ';
         $pmComponentscatalog_Host = new PluginMonitoringComponentscatalog_Host();
         $pmComponentscatalog_Host->getFromDB($item->fields["plugin_monitoring_componentscatalogs_hosts_id"]);
         if (isset($pmComponentscatalog_Host->fields['itemtype']) and $pmComponentscatalog_Host->fields['itemtype'] != '') {
             $itemtype2 = $pmComponentscatalog_Host->fields['itemtype'];
             $item2 = new $itemtype2();
             $item2->getFromDB($pmComponentscatalog_Host->fields['items_id']);
             $title .= str_replace("'", "\"", $item2->getLink() . " (" . $item2->getTypeName() . " / " . $data['extra_infos'] . ")");
         }
         $width = "width: 475,";
     } else {
         if ($itemtype == "PluginMonitoringWeathermap") {
             $content = $item->showWidget($data['items_id'], $data['extra_infos']);
             $content = '<div id="weathermap-' . $data['items_id'] . '">' . $content . "</div>";
             $event = ", " . $item->widgetEvent($data['items_id']);
             $title .= " : " . Dropdown::getDropdownName(getTableForItemType('PluginMonitoringWeathermap'), $data['items_id']);
             $item->getFromDB($data['items_id']);
             $width = "width:" . $item->fields['width'] * $data['extra_infos'] / 100 . ",";
         } else {
             if ($itemtype2 != '') {
                 $content = $item->showWidget2($data['id']);
             } else {
                 $content = $item->showWidget($data['items_id']);
             }
             if ($data['itemtype'] == 'PluginMonitoringServicescatalog') {
                 $width = "width: 202,";
             } else {
                 $width = "width: 180,";
             }
         }
     }
     if ($config == 0 && $itemtype != "PluginMonitoringService") {
         $title = '';
     }
     echo "<script>\n         var left = 0;\n         var topd = 0;\n         var obj = document.getElementById('panel');\n         if (obj.offsetParent) {\n           do {\n             left += obj.offsetLeft;\n             topd += obj.offsetTop;\n           } while (obj = obj.offsetParent);\n         }\n\n        var item" . $data['id'] . " = new Ext.Panel({\n             closable: true,           \n             title: '" . $title . "',\n             x: " . $data['x'] . ",\n             y: " . $data['y'] . ",\n             html       : '" . $content . "',\n             baseCls : 'x-panel',\n             layout : 'fit',\n             bodyStyle: 'background:transparent',\n             ";
     if ($config == 0 && $itemtype != "PluginMonitoringService") {
         echo "border: false,";
     }
     echo "renderTo: Ext.getBody(),\n             floating: false,\n             frame: false,\n             " . $width . "\n             autoHeight  : true,\n             layout: 'fit',\n             draggable: {\n                 //Config option of Ext.Panel.DD class.\n                 //It's a floating Panel, so do not show a placeholder proxy in the original position.\n                 insertProxy: false,\n\n                 //Called for each mousemove event while dragging the DD object.\n                 onDrag : function(e){\n                     //Record the x,y position of the drag proxy so that we can\n                     //position the Panel at end of drag.\n                     var el = this.proxy.getEl();\n                     this.x = el.getLeft(true) - left - 5;\n                     this.y = el.getTop(true) - topd - 5;\n\n\n                     //Keep the Shadow aligned if there is one.\n                     var s = this.panel.getEl().shadow;\n                     if (s) {\n                         s.realign(this.x, this.y, pel.getWidth(), pel.getHeight());\n                     }\n                 },\n\n                 //Called on the mouseup event.\n                 endDrag : function(e){\n                     this.panel.setPosition(this.x, this.y);\n";
     if ($config == '1') {
         echo "      Ext.get('updatecoordonates').load({\n                        url: '" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/ajax/displayview_itemcoordinates.php',\n                        scripts: true,\n                        params:'id=" . $data['id'] . "&x=' + (this.x)  + '&y=' + (this.y)\n                     });\n";
         echo "      if (this.x < 1) {\n                        this.panel.destroy();\n                     }\n                     if (this.y < 0) {\n                        this.panel.destroy();\n                     }\n            \n            ";
     }
     echo "      }\n             }\n             " . $event . "\n         });\n     </script>";
     //.show()
     if ($itemtype == "PluginMonitoringService") {
         $pmComponent = new PluginMonitoringComponent();
         $item = new $itemtype();
         $item->getFromDB($data['items_id']);
         $pmComponent->getFromDB($item->fields['plugin_monitoring_components_id']);
         $pmServicegraph = new PluginMonitoringServicegraph();
         $pmServicegraph->displayGraph($pmComponent->fields['graph_template'], "PluginMonitoringService", $data['items_id'], "0", $data['extra_infos'], "js");
     } else {
         if ($itemtype == "PluginMonitoringComponentscatalog") {
             $pmComponentscatalog = new PluginMonitoringComponentscatalog();
             $pmComponentscatalog->ajaxLoad($data['items_id']);
         } else {
             if ($itemtype == "PluginMonitoringServicescatalog") {
                 $pmServicescatalog = new PluginMonitoringServicescatalog();
                 $pmServicescatalog->ajaxLoad($data['items_id']);
             } else {
                 if ($itemtype2 != '') {
                     $pmDisplayview = new PluginMonitoringDisplayview();
                     $pmDisplayview->ajaxLoad2($data['id']);
                 } else {
                     if ($itemtype == "PluginMonitoringDisplayview") {
                         $pmDisplayview = new PluginMonitoringDisplayview();
                         $pmDisplayview->ajaxLoad($data['items_id']);
                     }
                 }
             }
         }
     }
     if ($itemtype == "PluginMonitoringWeathermap") {
         //         echo "<script type='text/javascript'>
         //            function updateimagew".$data['items_id']."() {
         //               var demain=new Date();
         //               document.getElementById('weathermap-".$data['items_id']."').innerHTML = demain.getTime() + '".$content."';
         //            }
         //            setInterval(updateimagew".$data['items_id'].", 50000);
         //         </script>";
         //      }
         echo "<script type='text/javascript'>\n         var mgr = new Ext.UpdateManager('weathermap-" . $data['items_id'] . "');\n         mgr.startAutoRefresh(50, \"" . $CFG_GLPI["root_doc"] . "/plugins/monitoring/ajax/widgetWeathermap.php\", \"id=" . $data['items_id'] . "&extra_infos=" . $data['extra_infos'] . "\", \"\", true);\n         </script>";
     }
     return true;
 }
Example #6
0
   function slideSlider($id) {
      global $CFG_GLPI, $DB;

      echo "<script type='text/javascript'>
         function fittext(itemid) {
            document.getElementById(itemid).style.fontSize = '50px';
            var fontsize = 50;
            while(document.getElementById(itemid).offsetWidth > 120) {
               fontsize--;
               if (fontsize > 20) {
                  fontsize--;
               }
               document.getElementById(itemid).style.fontSize = fontsize + 'px';
            }
            while(document.getElementById(itemid).offsetHeight > 67) {
               fontsize--;
               document.getElementById(itemid).style.fontSize = fontsize + 'px';
            }
            if (fontsize > 30) {
               document.getElementById(itemid).style.fontSize = '30px';
            }
            if (fontsize < 7) {
               document.getElementById(itemid).style.fontSize = '7px';
            }
         }
      </script>";
      PluginMonitoringToolbox::loadLib();

      $this->getFromDB($id);
      echo '<div id="custom_date" style="display:none"></div>';
      echo '<div id="custom_time" style="display:none"></div>';

      echo '<script src="'.$CFG_GLPI["root_doc"].'/plugins/monitoring/lib/slider.js-14/js/jssor.slider.mini.js"></script>
<script>
    jQuery(document).ready(function ($) {
        //Define an array of slideshow transition code
        var _SlideshowTransitions = [
        {$Duration:0001,$Opacity:2}
        ];
        var options = {
            $AutoPlay: true,
            $AutoPlayInterval: '.$this->fields['duration'].'000,
            $SlideshowOptions: {
                    $Class: $JssorSlideshowRunner$,
                    $Transitions: _SlideshowTransitions,
                    $TransitionsOrder: 1,
                    $ShowLink: true
        }
        };
        var jssor_slider1 = new $JssorSlider$(\'slider1_container\', options);
    });
</script>';
      echo "<table class='tab_cadre'>";

      echo "<tr>";
      echo "<td>";

      $query = "SELECT * FROM `glpi_plugin_monitoring_sliders_items`
              WHERE `plugin_monitoring_sliders_id`='".$id."'";

      $result = $DB->query($query);
      $maxWidth = 0;
      $maxHeight = 0;
      $is_minemap = 0;
      while ($data=$DB->fetch_array($result)) {
         if ($data['itemtype'] == 'PluginMonitoringServicescatalog'
                 || $data['itemtype'] == 'PluginMonitoringComponentscatalog'
                 || $data['itemtype'] == 'PluginMonitoringCustomitem_Gauge'
                 || $data['itemtype'] == 'PluginMonitoringCustomitem_Counter') {
            if ($maxWidth < 180) {
               $maxWidth = 180;
            }
            if ($maxHeight < 180) {
               $maxHeight = 180;
            }
            if ($data['is_minemap'] == 1) {
               $is_minemap = 1;
            }
         } else if ($data['itemtype'] == 'PluginMonitoringService') {
            if ($maxWidth < 475) {
               $maxWidth = 475;
            }
            if ($maxHeight < 330) {
               $maxHeight = 330;
            }
         } else if ($data['itemtype'] == "PluginMapsMap") {
            if ($maxWidth < 950) {
               $maxWidth = 950;
            }
            if ($maxHeight < 800) {
               $maxHeight = 800;
            }
         } else {
            $itemtype = $data['itemtype'];
            $item = new $itemtype();
            $item->getFromDB($data['items_id']);
            if ($maxWidth < $item->fields['width']) {
               $maxWidth = $item->fields['width'];
            }
            if (isset($item->fields['height'])) {
               if ($maxHeight < $item->fields['width']) {
                  $maxHeight = $item->fields['height'];
               }
            }
         }
      }
      if ($is_minemap) {
         $maxHeight = '1500';
      }

      $pm = new PluginMonitoringComponentscatalog();
      echo '<div id="slider1_container" style="position: relative;
top: 0px; left: 0px; width: '.$maxWidth.'px; height: '.$maxHeight.'px;">
    <!-- Slides Container -->
    <div u="slides" style="cursor: move; position: absolute; overflow: hidden;
    left: 0px; top: 0px; width: '.$maxWidth.'px; height: '.$maxHeight.'px;">';

      $result = $DB->query($query);
      while ($data=$DB->fetch_array($result)) {
         $itemtype = $data['itemtype'];
         $item = new $itemtype();
         if ($itemtype == "PluginMonitoringService") {
            echo '<div>';
            echo $item->showWidget($data['items_id'], $data['extra_infos']);
            echo '</div>';
         } else if ($itemtype == "PluginMonitoringWeathermap") {
            echo '<div>';
            echo '<div id="weathermap-'.$data['items_id'].'"></div>';
            echo '</div>';
         } else if ($itemtype == 'PluginMonitoringDisplayview') {
            echo '<div>';
            $pmDisplayview_item = new PluginMonitoringDisplayview_item();
            echo $pmDisplayview_item->view($data['items_id']);
            echo '</div>';
         } else if ($itemtype == "PluginMapsMap") {
            echo '<div>';
            echo '<div id="pluginmap"></div>';
            echo '</div>';
         } else {
            echo '<div>';
            echo $item->showWidget($data['items_id']);
            echo '</div>';
         }

      }
echo '    </div>
</div>';
      $result = $DB->query($query);
      while ($data=$DB->fetch_array($result)) {
         $itemtype = $data['itemtype'];
         $item = new $itemtype();
         // Ajax
         if ($itemtype == "PluginMonitoringService") {
            $pmComponent = new PluginMonitoringComponent();
            $item = new $itemtype();

            $item->getFromDB($data['items_id']);
            $pmComponent->getFromDB($item->fields['plugin_monitoring_components_id']);
            $pmServicegraph = new PluginMonitoringServicegraph();
            $pmServicegraph->displayGraph($pmComponent->fields['graph_template'],
                                          "PluginMonitoringService",
                                          $data['items_id'],
                                          "0",
                                          $data['extra_infos'],
                                          "js");
         } else if($itemtype == "PluginMonitoringComponentscatalog") {
            $pmComponentscatalog = new PluginMonitoringComponentscatalog();
            $pmComponentscatalog->ajaxLoad($data['items_id'], $data['is_minemap']);
         } else if($itemtype == "PluginMonitoringServicescatalog") {
            $pmServicescatalog = new PluginMonitoringServicescatalog();
            $pmServicescatalog->ajaxLoad($data['items_id']);
         } else if($itemtype == "PluginMonitoringDisplayview") {

         } else if($itemtype == "PluginMonitoringCustomitem_Gauge") {
            $pmCustomitem_Gauge = new PluginMonitoringCustomitem_Gauge();
            $pmCustomitem_Gauge->ajaxLoad($data['items_id']);
         } else if($itemtype == "PluginMonitoringCustomitem_Counter") {
            $pmCustomitem_Counter = new PluginMonitoringCustomitem_Counter();
            $pmCustomitem_Counter->ajaxLoad($data['items_id']);
         }
         if ($itemtype == "PluginMonitoringWeathermap") {
            $sess_id = session_id();
            PluginMonitoringSecurity::updateSession();

            echo "<script type='text/javascript'>
            var mgr = new Ext.UpdateManager('weathermap-".$data['items_id']."');
            mgr.startAutoRefresh(50, \"".$CFG_GLPI["root_doc"].
                    "/plugins/monitoring/ajax/widgetWeathermap.php\","
                    . " \"id=".$data['items_id']."&extra_infos=".
                    $data['extra_infos']."&sess_id=".$sess_id.
                    "&glpiID=".$_SESSION['glpiID'].
                    "&plugin_monitoring_securekey=".$_SESSION['plugin_monitoring_securekey'].
                    "\", \"\", true);
            </script>";
         }
         if ($itemtype == "PluginMapsMap") {
            $sess_id = session_id();
            PluginMonitoringSecurity::updateSession();

            echo "<script type='text/javascript'>
            var mgr = new Ext.UpdateManager('pluginmap');
            mgr.startAutoRefresh(50, \"".$CFG_GLPI["root_doc"].
                    "/plugins/monitoring/ajax/widgetPluginmap.php\","
                    . " \"extra_infos=".
                    $data['extra_infos']."&sess_id=".$sess_id.
                    "&glpiID=".$_SESSION['glpiID'].
                    "&plugin_monitoring_securekey=".$_SESSION['plugin_monitoring_securekey'].
                    "\", \"\", true);
            </script>";
         }
      }
      echo "</td>";
      echo "</tr>";
      echo "</table>";
   }
 function updateGenericServicesCatalogs($action = 'update')
 {
     global $DB;
     $entity = new Entity();
     $pmServicescatalog = new PluginMonitoringServicescatalog();
     $pmBusinessrulegroup = new PluginMonitoringBusinessrulegroup();
     $pmBusinessrulecomponent = new PluginMonitoringBusinessrule_component();
     $existingSCs = array();
     // Find existing instances of generic services catalog ...
     $a_SCs = $this->find("`name` LIKE '" . $this->getName() . "%'");
     foreach ($a_SCs as $a_SC) {
         // Toolbox::logInFile("pm", "SC : ".$a_SC['id'].", name : ".$a_SC['name'].", generic : ".$a_SC['is_generic']."\n");
         if ($a_SC['name'] == $this->getField('name')) {
             continue;
         }
         $existingSCs[$a_SC['name']] = $a_SC;
     }
     if ($action == 'delete') {
         foreach ($existingSCs as $name => $a_SC) {
             $pmServicescatalog->getFromDB($a_SC['id']);
             $pmServicescatalog->delete($pmServicescatalog->fields);
             // Toolbox::logInFile("pm", "Deleted : ".$a_SC['name']."\n");
             $pmBusinessrulecomponent = new PluginMonitoringBusinessrule_component();
             $pmBusinessrule = new PluginMonitoringBusinessrule();
             // Get business rules groups ...
             $a_BRgroups = $pmBusinessrulegroup->find("`plugin_monitoring_servicescatalogs_id`='" . $a_SC['id'] . "'");
             // Delete business groups components
             foreach ($a_BRgroups as $a_BRgroup) {
                 // Toolbox::logInFile("pm", "a_BRgroup : ".$a_BRgroup['id']."\n");
                 $a_brcomponents = $pmBusinessrulecomponent->find("`plugin_monitoring_businessrulegroups_id`='" . $a_BRgroup['id'] . "'");
                 foreach ($a_brcomponents as $a_brcomponent) {
                     // Toolbox::logInFile("pm", "a_brcomponent : ".$a_brcomponent['id']."\n");
                     $pmBusinessrulecomponent->getFromDB($a_brcomponent['id']);
                     $pmBusinessrulecomponent->delete($pmBusinessrulecomponent->fields);
                 }
             }
             // Delete business groups rules
             foreach ($a_BRgroups as $a_BRgroup) {
                 $a_brs = $pmBusinessrule->find("`plugin_monitoring_businessrulegroups_id`='" . $a_BRgroup['id'] . "'");
                 foreach ($a_brs as $a_br) {
                     // Toolbox::logInFile("pm", "a_br : ".$a_br['id']."\n");
                     $pmBusinessrulecomponent->getFromDB($a_brcomponent['id']);
                     $pmBusinessrulecomponent->delete($pmBusinessrulecomponent->fields);
                 }
             }
         }
         return;
     } else {
         foreach ($existingSCs as $name => $a_SC) {
             $pmServicescatalog->getFromDB($a_SC['id']);
             $pmBusinessrulegroup = new PluginMonitoringBusinessrulegroup();
             $pmBusinessrulecomponent = new PluginMonitoringBusinessrule_component();
             $pmBusinessrule = new PluginMonitoringBusinessrule();
             // Get business rules groups ...
             $a_BRgroups = $pmBusinessrulegroup->find("`plugin_monitoring_servicescatalogs_id`='" . $a_SC['id'] . "'");
             // Delete business groups components
             foreach ($a_BRgroups as $a_BRgroup) {
                 // Toolbox::logInFile("pm", "a_BRgroup : ".$a_BRgroup['id']."\n");
                 $a_brcomponents = $pmBusinessrulecomponent->find("`plugin_monitoring_businessrulegroups_id`='" . $a_BRgroup['id'] . "'");
                 foreach ($a_brcomponents as $a_brcomponent) {
                     // Toolbox::logInFile("pm", "a_brcomponent : ".$a_brcomponent['id']."\n");
                     $pmBusinessrulecomponent->getFromDB($a_brcomponent['id']);
                     $pmBusinessrulecomponent->delete($pmBusinessrulecomponent->fields);
                 }
             }
             // Delete business groups rules
             foreach ($a_BRgroups as $a_BRgroup) {
                 $a_brs = $pmBusinessrule->find("`plugin_monitoring_businessrulegroups_id`='" . $a_BRgroup['id'] . "'");
                 foreach ($a_brs as $a_br) {
                     // Toolbox::logInFile("pm", "a_br : ".$a_br['id']."\n");
                     $pmBusinessrulecomponent->getFromDB($a_brcomponent['id']);
                     $pmBusinessrulecomponent->delete($pmBusinessrulecomponent->fields);
                 }
             }
         }
     }
     // Find entities concerned ...
     $a_entitiesServices = $this->getGenericServicesEntities();
     foreach ($a_entitiesServices as $idEntity => $a_entityServices) {
         // New entity ... so it must exist a derivated SC !
         $entity->getFromDB($idEntity);
         // Toolbox::logInFile("pm", "Found entity : ".$idEntity." / ".$entity->getName()."\n");
         $scName = $this->getName() . " - " . $entity->getName();
         if (isset($existingSCs[$scName])) {
             // Update SC
             $pmServicescatalog->getFromDB($existingSCs[$scName]['id']);
             $pmServicescatalog->fields = $this->fields;
             unset($pmServicescatalog->fields['id']);
             $pmServicescatalog->fields['id'] = $existingSCs[$scName]['id'];
             $pmServicescatalog->fields['entities_id'] = $idEntity;
             $pmServicescatalog->fields['is_generic'] = 0;
             $pmServicescatalog->fields['name'] = $DB->escape($scName);
             $pmServicescatalog->update($pmServicescatalog->fields);
             /*            // Finish updating if needed ...
                         $a_BRgroups = $pmBusinessrulegroup->find("`plugin_monitoring_servicescatalogs_id`='".$this->fields['id']."'");
                         foreach ($a_BRgroups as $a_BRgroup) {
                            $pmBusinessrulegroup = $pmBusinessrulegroup->find("`plugin_monitoring_servicescatalogs_id`='".$a_SC['id']."' AND `name`='".$a_BRgroup['name']."'");
                            $pmBusinessrulegroup->fields = $a_BRgroup->fields;
                            unset($pmBusinessrulegroup->fields['id']);
                            $pmBusinessrulegroup->fields['plugin_monitoring_servicescatalogs_id'] = $pmServicescatalog->fields['id'];
                            $pmBusinessrulegroup->update($pmBusinessrulegroup->fields);
                         }
             */
             // Toolbox::logInFile("pm", "Updated : ".$scName."\n");
         } else {
             // Add SC
             $pmServicescatalog = new PluginMonitoringServicescatalog();
             $pmServicescatalog->getEmpty();
             $pmServicescatalog->fields = $this->fields;
             unset($pmServicescatalog->fields['id']);
             $pmServicescatalog->fields['entities_id'] = $idEntity;
             $pmServicescatalog->fields['is_recursive'] = 0;
             $pmServicescatalog->fields['is_generic'] = 0;
             $pmServicescatalog->fields['name'] = $DB->escape($scName);
             $pmServicescatalog->fields['plugin_monitoring_servicescatalogs_id'] = $this->fields['id'];
             $pmServicescatalog->add($pmServicescatalog->fields);
             /*
                         // Finish updating if needed ...
                         $a_BRgroups = $pmBusinessrulegroup->find("`plugin_monitoring_servicescatalogs_id`='".$this->fields['id']."'");
                         foreach ($a_BRgroups as $a_BRgroup) {
                            $ref = new PluginMonitoringBusinessrulegroup();
                            $ref->getFromDB($a_BRgroup['id']);
                            $pmBusinessrulegroup = new PluginMonitoringBusinessrulegroup();
                            $pmBusinessrulegroup->getEmpty();
                            $pmBusinessrulegroup->fields = $ref->fields;
                            unset($pmBusinessrulegroup->fields['id']);
                            $pmBusinessrulegroup->fields['plugin_monitoring_servicescatalogs_id'] = $pmServicescatalog->fields['id'];
                            $pmBusinessrulegroup->add($pmBusinessrulegroup->fields);
             
                            $a_brcomponents = $pmBusinessrulecomponent->find("`plugin_monitoring_businessrulegroups_id`='".$a_BRgroup['id']."'");
                            foreach ($a_brcomponents as $a_brcomponent) {
                               $ref = new PluginMonitoringBusinessrule_component();
                               $ref->getFromDB($a_brcomponent['id']);
                               $pmBusinessrule_component = new PluginMonitoringBusinessrule_component();
                               $pmBusinessrule_component->getEmpty();
                               $pmBusinessrule_component->fields = $ref->fields;
                               unset($pmBusinessrule_component->fields['id']);
                               $pmBusinessrule_component->fields['plugin_monitoring_businessrulegroups_id'] = $pmBusinessrulegroup->fields['id'];
                               $pmBusinessrule_component->add($pmBusinessrule_component->fields);
                            }
                         }
             */
             // Toolbox::logInFile("pm", "Added : ".$scName."\n");
         }
     }
 }
GLPI is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

GLPI is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with GLPI; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
--------------------------------------------------------------------------
*/
// ----------------------------------------------------------------------
// Original Author of file: David DURIEUX
// Purpose of file:
// ----------------------------------------------------------------------
// Direct access to file
if (strpos($_SERVER['PHP_SELF'], "updateWidgetServicescatalog.php")) {
    include "../../../inc/includes.php";
    header("Content-Type: text/html; charset=UTF-8");
    Html::header_nocache();
}
if (!defined('GLPI_ROOT')) {
    die("Can not acces directly to this file");
}
Session::checkLoginUser();
$pmServicescatalog = new PluginMonitoringServicescatalog();
$pmServicescatalog->showWidgetFrame($_POST['id']);
 static function getAdditionalMenuOptions()
 {
     global $CFG_GLPI;
     $main_menu = '<img src="' . $CFG_GLPI["root_doc"] . '/plugins/monitoring/pics/main_menu.png" alt="' . __('Main menu', 'monitoring') . '" title="' . __('Main menu', 'monitoring') . '"\\>';
     return array('componentscatalog' => array('title' => PluginMonitoringComponentscatalog::getTypeName(), 'page' => PluginMonitoringComponentscatalog::getSearchURL(false), 'links' => array($main_menu => '/plugins/monitoring/front/menu.php', 'search' => '/plugins/monitoring/front/componentscatalog.php', 'add' => '/plugins/monitoring/front/componentscatalog.form.php')), 'command' => array('title' => PluginMonitoringCommand::getTypeName(), 'page' => PluginMonitoringCommand::getSearchURL(false), 'links' => array($main_menu => '/plugins/monitoring/front/menu.php', 'search' => '/plugins/monitoring/front/command.php', 'add' => '/plugins/monitoring/front/command.form.php')), 'check' => array('title' => PluginMonitoringCheck::getTypeName(), 'page' => PluginMonitoringCheck::getSearchURL(false), 'links' => array($main_menu => '/plugins/monitoring/front/menu.php', 'search' => '/plugins/monitoring/front/check.php', 'add' => '/plugins/monitoring/front/check.form.php')), 'eventhandler' => array('title' => PluginMonitoringEventhandler::getTypeName(), 'page' => PluginMonitoringEventhandler::getSearchURL(false), 'links' => array($main_menu => '/plugins/monitoring/front/menu.php', 'search' => '/plugins/monitoring/front/eventhandler.php', 'add' => '/plugins/monitoring/front/eventhandler.form.php')), 'perfdata' => array('title' => PluginMonitoringPerfdata::getTypeName(), 'page' => PluginMonitoringPerfdata::getSearchURL(false), 'links' => array($main_menu => '/plugins/monitoring/front/menu.php', 'search' => '/plugins/monitoring/front/perfdata.php', 'add' => '/plugins/monitoring/front/perfdata.form.php')), 'component' => array('title' => PluginMonitoringComponent::getTypeName(), 'page' => PluginMonitoringComponent::getSearchURL(false), 'links' => array($main_menu => '/plugins/monitoring/front/menu.php', 'search' => '/plugins/monitoring/front/component.php', 'add' => '/plugins/monitoring/front/component.form.php')), 'contacttemplate' => array('title' => PluginMonitoringContacttemplate::getTypeName(), 'page' => PluginMonitoringContacttemplate::getSearchURL(false), 'links' => array($main_menu => '/plugins/monitoring/front/menu.php', 'search' => '/plugins/monitoring/front/contacttemplate.php', 'add' => '/plugins/monitoring/front/contacttemplate.form.php')), 'notificationcommand' => array('title' => PluginMonitoringNotificationcommand::getTypeName(), 'page' => PluginMonitoringNotificationcommand::getSearchURL(false), 'links' => array($main_menu => '/plugins/monitoring/front/menu.php', 'search' => '/plugins/monitoring/front/notificationcommand.php', 'add' => '/plugins/monitoring/front/notificationcommand.form.php')), 'realm' => array('title' => PluginMonitoringRealm::getTypeName(), 'page' => PluginMonitoringRealm::getSearchURL(false), 'links' => array($main_menu => '/plugins/monitoring/front/menu.php', 'search' => '/plugins/monitoring/front/realm.php', 'add' => '/plugins/monitoring/front/realm.form.php')), 'tag' => array('title' => PluginMonitoringTag::getTypeName(), 'page' => PluginMonitoringTag::getSearchURL(false), 'links' => array($main_menu => '/plugins/monitoring/front/menu.php', 'search' => '/plugins/monitoring/front/tag.php')), 'servicescatalog' => array('title' => PluginMonitoringServicescatalog::getTypeName(), 'page' => PluginMonitoringServicescatalog::getSearchURL(false), 'links' => array($main_menu => '/plugins/monitoring/front/menu.php', 'search' => '/plugins/monitoring/front/servicescatalog.php', 'add' => '/plugins/monitoring/front/servicescatalog.form.php')), 'weathermap' => array('title' => PluginMonitoringWeathermap::getTypeName(), 'page' => PluginMonitoringWeathermap::getSearchURL(false), 'links' => array($main_menu => '/plugins/monitoring/front/menu.php', 'search' => '/plugins/monitoring/front/weathermap.php', 'add' => '/plugins/monitoring/front/weathermap.form.php')), 'displayview' => array('title' => PluginMonitoringDisplayview::getTypeName(), 'page' => PluginMonitoringDisplayview::getSearchURL(false), 'links' => array('search' => '/plugins/monitoring/front/displayview.php', 'add' => '/plugins/monitoring/front/displayview.form.php')), 'slider' => array('title' => PluginMonitoringSlider::getTypeName(), 'page' => PluginMonitoringSlider::getSearchURL(false), 'links' => array($main_menu => '/plugins/monitoring/front/menu.php', 'search' => '/plugins/monitoring/front/slider.php', 'add' => '/plugins/monitoring/front/slider.form.php')), 'downtime' => array('title' => PluginMonitoringDowntime::getTypeName(), 'page' => PluginMonitoringDowntime::getSearchURL(false), 'links' => array('search' => '/plugins/monitoring/front/downtime.php')), 'acknowledge' => array('title' => PluginMonitoringAcknowledge::getTypeName(), 'page' => PluginMonitoringAcknowledge::getSearchURL(false), 'links' => array('search' => '/plugins/monitoring/front/acknowledge.php')), 'menu' => array('title' => PluginMonitoringMenu::getTypeName(), 'links' => array($main_menu => '/plugins/monitoring/front/menu.php', 'config' => '/plugins/monitoring/front/config.form.php')), 'dashboard' => array('title' => PluginMonitoringDisplay::getTypeName(), 'links' => array($main_menu => '/plugins/monitoring/front/menu.php', 'config' => '/plugins/monitoring/front/config.form.php')), 'config' => array('title' => PluginMonitoringConfig::getTypeName(), 'links' => array($main_menu => '/plugins/monitoring/front/menu.php')));
 }
  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";
Session::checkCentralAccess();
Html::header(__('Monitoring', 'monitoring'), $_SERVER["PHP_SELF"], "plugins", "monitoring", "display");
$pmDisplay = new PluginMonitoringDisplay();
$pmServicescatalog = new PluginMonitoringServicescatalog();
$pmMessage = new PluginMonitoringMessage();
$pmMessage->getMessages();
$pmDisplay->menu();
PluginMonitoringProfile::checkRight("servicescatalog", 'r');
$pmDisplay->showCounters("Businessrules");
$pmServicescatalog->showChecks();
Html::footer();
 function showForm($items_id, $servicescatalogs_id, $options = array())
 {
     global $CFG_GLPI;
     if ($items_id != '') {
         $this->getFromDB($items_id);
     } else {
         $this->getEmpty();
     }
     $this->showFormHeader($options);
     $pmBusinessrule_component = new PluginMonitoringBusinessrule_component();
     $pmBusinessrule_component->replayDynamicServices($items_id);
     $pmSC = new PluginMonitoringServicescatalog();
     $pmSC->getFromDB($servicescatalogs_id);
     $rand = mt_rand();
     echo "<tr class='tab_bg_1'>";
     echo "<td>";
     echo "<input type='hidden' name='plugin_monitoring_servicescatalogs_id' value='" . $servicescatalogs_id . "'/>";
     echo __('Name') . "&nbsp;:";
     echo "</td>";
     echo "<td>";
     echo "<input type='text' name='name' value='" . $this->fields["name"] . "' size='30'/>";
     echo "</td>";
     if ($items_id != '') {
         if (Session::haveRight("plugin_monitoring_servicescatalog", CREATE)) {
             echo "<th colspan='2' width='60%'>";
             echo __('Resources', 'monitoring');
             echo "&nbsp;";
             echo "<img onClick=\"Ext.get('ressources" . $rand . "').setDisplayed('block')\"\n                       title=\"" . __('add') . "\" alt=\"" . __('add') . "\"\n                       class='pointer'  src='" . $CFG_GLPI["root_doc"] . "/pics/add_dropdown.png'>";
             echo "</th>";
         }
     }
     echo "</tr>";
     echo "<tr>";
     echo "<td valign='top'>";
     echo __('Logical operator') . "&nbsp;:";
     echo "</td>";
     echo "<td valign='top'>";
     $first_operator = array();
     $first_operator['and'] = "and";
     $first_operator['or'] = "or";
     $first_operator['2 of:'] = __('2 of', 'monitoring');
     $first_operator['3 of:'] = __('3 of', 'monitoring');
     $first_operator['4 of:'] = __('4 of', 'monitoring');
     $first_operator['5 of:'] = __('5 of', 'monitoring');
     $first_operator['6 of:'] = __('6 of', 'monitoring');
     $first_operator['7 of:'] = __('7 of', 'monitoring');
     $first_operator['8 of:'] = __('8 of', 'monitoring');
     $first_operator['9 of:'] = __('9 of', 'monitoring');
     $first_operator['10 of:'] = __('10 of', 'monitoring');
     Dropdown::showFromArray('operator', $first_operator, array("value" => $this->fields['operator']));
     echo "</td>";
     if ($items_id != '') {
         echo "<td colspan='2'>";
         if (Session::haveRight("plugin_monitoring_servicescatalog", CREATE)) {
             // ** Dropdown to display
             echo "<div style='display:none' id='ressources" . $rand . "' >";
             // Static (a service for an host)
             echo "<table>";
             echo "<tr class='tab_bg_1'>";
             echo "<td>";
             echo "<form name='form' method='post' action='" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/front/businessrule.form.php'>";
             echo "<input type='hidden' name='plugin_monitoring_businessrulegroups_id' value='" . $items_id . "' />";
             echo "<input type='hidden' name='is_generic' value='" . $pmSC->getField('is_generic') . "' />";
             PluginMonitoringBusinessrule::dropdownService(0, array('name' => 'type'));
             echo "<input type='submit' name='add' value=\"" . __('Add') . "\" class='submit'>";
             Html::closeForm();
             echo "</td>";
             echo "</tr>";
             echo "</table>";
             echo "<hr>";
             // Dynamique (all service of component of component catalog)
             echo "<table>";
             echo "<tr class='tab_bg_1'>";
             echo "<td><strong>";
             echo __('Components catalog', 'monitoring');
             echo ' + ';
             echo __('Component', 'monitoring');
             echo " (" . __('Dynamic', 'monitoring') . ")";
             echo " :</strong></td>";
             echo "</tr>";
             echo "<tr class='tab_bg_1'>";
             echo "<td>";
             echo "<form name='form' method='post' action='" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/front/businessrule_component.form.php'>";
             echo "<input type='hidden' name='plugin_monitoring_businessrulegroups_id' value='" . $items_id . "' />";
             $options = array('toupdate' => array('value_fieldname' => 'plugin_monitoring_componentscalalog_id', 'to_update' => "componentdropdown" . $rand, 'url' => $CFG_GLPI["root_doc"] . "/plugins/monitoring/ajax/dropdownComponent.php", 'moreparams' => array()));
             Dropdown::show('PluginMonitoringComponentscatalog', $options);
             echo '<div id="componentdropdown' . $rand . '"></div>';
             //PluginMonitoringBusinessrule::dropdownService(0, array('name' => 'type'));
             echo "<input type='submit' name='add' value=\"" . __('Add') . "\" class='submit'>";
             Html::closeForm();
             echo "</td>";
             echo "</tr>";
             echo "</table>";
             echo "<hr>";
             echo "</div>";
         }
         $pmBusinessrule = new PluginMonitoringBusinessrule();
         $pmService = new PluginMonitoringService();
         $a_services = $pmBusinessrule->find("`plugin_monitoring_businessrulegroups_id`='" . $items_id . "'" . " AND `is_dynamic`='0'");
         if (count($a_services) > 0) {
             echo "<strong>" . __('Static hosts', 'monitoring') . " :</strong>";
             echo "<table width='100%'>";
             foreach ($a_services as $gdata) {
                 if ($pmService->getFromDB($gdata['plugin_monitoring_services_id'])) {
                     $shortstate = $pmService->getShortState();
                     echo "<tr class='tab_bg_1'>";
                     echo "<td>";
                     echo "<img src='" . $pmService->getShortState(array('image' => '32')) . "'/>";
                     echo "</td>";
                     echo "<td>";
                     echo $pmService->getLink();
                     echo "</td>";
                     echo "<td>";
                     echo "<input type='submit' name='deletebusinessrules-" . $gdata['id'] . "' value=\"" . _sx('button', 'Delete permanently') . "\" class='submit'>";
                     echo "</td>";
                     echo "</tr>";
                 } else {
                     // resource deleted
                     echo "<tr class='tab_bg_1'>";
                     echo "<td colspan='2' bgcolor='#ff0000'>";
                     echo __('Resource deleted', 'monitoring');
                     echo "</td>";
                     echo "<td>";
                     echo "<input type='submit' name='deletebusinessrules-" . $gdata['id'] . "' value=\"" . __('Clean') . "\" class='submit'>";
                     echo "</td>";
                     echo "</tr>";
                 }
             }
             echo "</table>";
             echo "<hr/>";
         }
         $a_br_components = $pmBusinessrule_component->find("`plugin_monitoring_businessrulegroups_id`='" . $items_id . "'");
         $pmComponentscatalog_Component = new PluginMonitoringComponentscatalog_Component();
         $pmComponentscatalog = new PluginMonitoringComponentscatalog();
         $pmComponent = new PluginMonitoringComponent();
         if (count($a_br_components) > 0) {
             echo "<strong>" . __('Dynamic hosts', 'monitoring') . " :</strong>";
             echo "<table width='100%'>";
             foreach ($a_br_components as $a_br_component) {
                 echo "<tr class='tab_bg_1'>";
                 echo "<td>";
                 $pmComponentscatalog_Component->getFromDB($a_br_component['plugin_monitoring_componentscatalogs_components_id']);
                 $pmComponentscatalog->getFromDB($pmComponentscatalog_Component->fields['plugin_monitoring_componentscalalog_id']);
                 echo $pmComponentscatalog->getLink();
                 echo ' > ';
                 $pmComponent->getFromDB($pmComponentscatalog_Component->fields['plugin_monitoring_components_id']);
                 echo $pmComponent->getLink();
                 echo "</td>";
                 echo "<td>";
                 echo "<input type='submit' name='deletebrcomponents-" . $a_br_component['id'] . "' value=\"" . _sx('button', 'Delete permanently') . "\" class='submit'>";
                 echo "</td>";
                 echo "</tr>";
             }
             echo "</table>";
         }
         if (!($pmSC->fields['is_generic'] && $pmSC->fields['is_recursive'])) {
             echo "<table width='100%'>";
             $a_services = $pmBusinessrule->find("`plugin_monitoring_businessrulegroups_id`='" . $items_id . "'" . " AND `is_dynamic`='1'");
             foreach ($a_services as $gdata) {
                 $pmService->getFromDB($gdata["plugin_monitoring_services_id"]);
                 $shortstate = $pmService->getShortState();
                 echo "<tr class='tab_bg_1'>";
                 echo "<td width='130'>&nbsp;";
                 echo "</td>";
                 echo "<td>";
                 echo "<img src='" . $pmService->getShortState(array('image' => '32')) . "'/>";
                 echo "</td>";
                 echo "<td>";
                 $pmComponentscatalog_Host = new PluginMonitoringComponentscatalog_Host();
                 $pmComponentscatalog_Host->getFromDB($pmService->fields['plugin_monitoring_componentscatalogs_hosts_id']);
                 echo $pmService->getLink();
                 echo "</td>";
                 echo "</tr>";
             }
             echo "</table>";
         } else {
             echo "<strong>" . __('Dynamic hosts list will be defined during Shinken configuration build.', 'monitoring') . "</strong>";
         }
     }
     echo "</td>";
     echo "</tr>";
     $this->showFormButtons($options);
     return true;
 }
 function replayDynamicServices($plugin_monitoring_businessrulegroups_id)
 {
     global $DB;
     if ($plugin_monitoring_businessrulegroups_id == 0) {
         return;
     }
     // Get entity and if recursif
     $pmBusinessrulegroup = new PluginMonitoringBusinessrulegroup();
     $pmServicescatalog = new PluginMonitoringServicescatalog();
     $pmBusinessrulegroup->getFromDB($plugin_monitoring_businessrulegroups_id);
     $pmServicescatalog->getFromDB($pmBusinessrulegroup->fields['plugin_monitoring_servicescatalogs_id']);
     if ($pmServicescatalog->fields['is_recursive']) {
         $a_sons = getSonsOf("glpi_entities", $pmServicescatalog->fields['entities_id']);
         $restrict_entities = "AND ( `glpi_plugin_monitoring_services`.`entities_id` IN ('" . implode("','", $a_sons) . "') )";
     } else {
         $restrict_entities = "AND ( `glpi_plugin_monitoring_services`.`entities_id` = '" . $pmServicescatalog->fields['entities_id'] . "' )";
     }
     $a_brcomponents = $this->find("`plugin_monitoring_businessrulegroups_id`='" . $plugin_monitoring_businessrulegroups_id . "'");
     $a_services = array();
     foreach ($a_brcomponents as $a_brcomponent) {
         $pmComponentscatalog_Component = new PluginMonitoringComponentscatalog_Component();
         $pmComponentscatalog_Component->getFromDB($a_brcomponent['plugin_monitoring_componentscatalogs_components_id']);
         // Get all services of component of component catalog
         $query = "SELECT `glpi_plugin_monitoring_services`.`id` FROM `glpi_plugin_monitoring_services`" . " LEFT JOIN `glpi_plugin_monitoring_componentscatalogs_hosts`" . "    ON plugin_monitoring_componentscatalogs_hosts_id=" . "       `glpi_plugin_monitoring_componentscatalogs_hosts`.`id`" . " WHERE `glpi_plugin_monitoring_services`.`plugin_monitoring_components_id`" . "          = '" . $pmComponentscatalog_Component->fields['plugin_monitoring_components_id'] . "' " . $restrict_entities;
         $result = $DB->query($query);
         while ($data = $DB->fetch_array($result)) {
             $a_services[$data['id']] = $data['id'];
         }
     }
     // get static services of the group (so not add dynamic if yet in static)
     $pmBusinessrule_component = new PluginMonitoringBusinessrule_component();
     $pmBusinessrule = new PluginMonitoringBusinessrule();
     $a_static = $pmBusinessrule->find("`plugin_monitoring_businessrulegroups_id`='" . $plugin_monitoring_businessrulegroups_id . "'" . " AND `is_dynamic`=0");
     foreach ($a_static as $data) {
         if (isset($a_services[$data['plugin_monitoring_services_id']])) {
             unset($a_services[$data['plugin_monitoring_services_id']]);
             // Update generic status
             $pmBusinessrule->getFromDB($data['id']);
             $input = array('id' => $data['id'], 'is_generic' => $pmServicescatalog->fields['is_generic']);
             $pmBusinessrule->update($input);
         }
     }
     // update services + is_dynamic=1
     $query = "SELECT * FROM `glpi_plugin_monitoring_businessrules`" . " WHERE `plugin_monitoring_businessrulegroups_id`='" . $plugin_monitoring_businessrulegroups_id . "'" . " AND `is_dynamic`=1";
     $result = $DB->query($query);
     while ($data = $DB->fetch_array($result)) {
         // Update if yet in DB
         if (isset($a_services[$data['plugin_monitoring_services_id']])) {
             unset($a_services[$data['plugin_monitoring_services_id']]);
             // Update generic status
             $pmBusinessrule->getFromDB($data['id']);
             $input = array('id' => $data['id'], 'is_generic' => $pmServicescatalog->fields['is_generic']);
             $pmBusinessrule->update($input);
         } else {
             // delete if not exist
             $pmBusinessrule->delete($data);
         }
     }
     // Add new
     foreach ($a_services as $services_id) {
         $input = array('plugin_monitoring_businessrulegroups_id' => $plugin_monitoring_businessrulegroups_id, 'plugin_monitoring_services_id' => $services_id, 'is_dynamic' => '1', 'is_generic' => $pmServicescatalog->fields['is_generic']);
         $pmBusinessrule->add($input);
     }
 }
 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 addItem($sliders_id)
 {
     global $DB, $CFG_GLPI;
     $this->getEmpty();
     $pmSlider = new PluginMonitoringSlider();
     $pmSlider->getFromDB($sliders_id);
     // Manage entity_sons
     $a_entities = array();
     if (!($pmSlider->fields['entities_id'] < 0)) {
         if ($pmSlider->fields['is_recursive'] == '0') {
             $a_entities[$pmSlider->fields['entities_id']] = $pmSlider->fields['entities_id'];
         } else {
             $a_entities = getSonsOf('glpi_entities', $pmSlider->fields['entities_id']);
         }
     }
     $options = array();
     $this->showFormHeader($options);
     echo "<tr class='tab_bg_1'>";
     echo "<td>";
     echo "<input type='hidden' name='plugin_monitoring_sliders_id' value='" . $sliders_id . "' />";
     echo __('Element to display', 'monitoring') . " :</td>";
     echo "<td>";
     $elements = array();
     $elements['NULL'] = Dropdown::EMPTY_VALUE;
     $elements['PluginMonitoringDisplayview'] = __('Views', 'monitoring');
     $elements['PluginMonitoringServicescatalog'] = PluginMonitoringServicescatalog::getTypeName();
     $elements['PluginMonitoringService'] = __('Resources (graph)', 'monitoring');
     $elements['PluginMonitoringComponentscatalog'] = __('Components catalog', 'monitoring');
     $elements['PluginMonitoringWeathermap'] = __('Weathermap', 'monitoring');
     $elements['PluginMonitoringCustomitem_Gauge'] = PluginMonitoringCustomitem_Gauge::getTypeName();
     $elements['PluginMonitoringCustomitem_Counter'] = PluginMonitoringCustomitem_Counter::getTypeName();
     if (in_array('maps', $_SESSION['glpi_plugins'])) {
         $elements['PluginMapsMap'] = 'Maps';
     }
     $rand = Dropdown::showFromArray('itemtype', $elements, array('value' => $this->fields['itemtype']));
     $params = array('itemtype' => '__VALUE__', 'sliders_id' => $sliders_id, 'myname' => "items_id", 'a_entities' => $a_entities);
     Ajax::updateItemOnSelectEvent("dropdown_itemtype" . $rand, "items_id", $CFG_GLPI["root_doc"] . "/plugins/monitoring/ajax/dropdownDisplayviewItemtype.php", $params);
     echo "<span id='items_id'></span>";
     echo "<input type='hidden' name='x' value='1' />";
     echo "<input type='hidden' name='y' value='1' />";
     echo "</td>";
     echo "<td colspan='2'></td>";
     echo "</tr>";
     $this->showFormButtons($options);
     // Show items
     $query = "SELECT * FROM `glpi_plugin_monitoring_sliders_items`\n              WHERE `plugin_monitoring_sliders_id`='" . $sliders_id . "'";
     $result = $DB->query($query);
     echo "<table class='tab_cadre' width='600'>";
     echo "<tr class='tab_bg_1'>";
     echo "<th colspan='3'>";
     echo _n('Associated item', 'Associated items', 2);
     echo "</th>";
     echo "</tr>";
     while ($data = $DB->fetch_array($result)) {
         echo "<tr class='tab_bg_1'>";
         echo "<td>";
         $itemtype = $data['itemtype'];
         $item = new $itemtype();
         echo $item->getTypeName();
         echo "</td>";
         echo "<td>";
         $item->getFromDB($data['items_id']);
         echo $item->getLink();
         echo "</td>";
         echo "<td>";
         echo "<form name='form' method='post' action='" . $this->getFormURL() . "' >";
         echo "<input type='hidden' name='id' value='" . $data['id'] . "'>";
         echo "<input type='submit' name='delete' value=\"" . _sx('button', 'Delete permanently') . "\"\n                class='submit' " . Html::addConfirmationOnAction(__('Confirm the final deletion?')) . ">";
         Html::closeForm();
         echo "</td>";
         echo "</tr>";
     }
     echo "</table>";
     return true;
 }
 function addItem($displayviews_id)
 {
     global $DB, $CFG_GLPI;
     $this->getEmpty();
     $pmDisplayview = new PluginMonitoringDisplayview();
     $pmDisplayview->getFromDB($displayviews_id);
     // Manage entity_sons
     $a_entities = array();
     if (!($pmDisplayview->fields['entities_id'] < 0)) {
         if ($pmDisplayview->fields['is_recursive'] == '0') {
             $a_entities[$pmDisplayview->fields['entities_id']] = $pmDisplayview->fields['entities_id'];
         } else {
             $a_entities = getSonsOf('glpi_entities', $pmDisplayview->fields['entities_id']);
         }
     }
     $options = array();
     $this->showFormHeader($options);
     echo "<tr class='tab_bg_1'>";
     echo "<td>";
     echo "<input type='hidden' name='plugin_monitoring_displayviews_id' value='" . $displayviews_id . "' />";
     echo __('Element to display', 'monitoring') . " :</td>";
     echo "<td>";
     $elements = array();
     $elements['NULL'] = Dropdown::EMPTY_VALUE;
     $elements['PluginMonitoringDisplayview'] = __('Views', 'monitoring');
     $elements['PluginMonitoringServicescatalog'] = PluginMonitoringServicescatalog::getTypeName();
     //      $elements['service']                             = __('Resources (info)', 'monitoring');
     $elements['host'] = __('Host (info)', 'monitoring');
     $elements['PluginMonitoringService'] = __('Resources (graph)', 'monitoring');
     $elements['PluginMonitoringComponentscatalog'] = __('Components catalog', 'monitoring');
     $elements['PluginMonitoringWeathermap'] = __('Weathermap', 'monitoring');
     $elements['PluginMonitoringCustomitem_Gauge'] = PluginMonitoringCustomitem_Gauge::getTypeName();
     $elements['PluginMonitoringCustomitem_Counter'] = PluginMonitoringCustomitem_Counter::getTypeName();
     $rand = Dropdown::showFromArray('itemtype', $elements, array('value' => $this->fields['itemtype']));
     $params = array('itemtype' => '__VALUE__', 'displayviews_id' => $displayviews_id, 'myname' => "items_id", 'a_entities' => $a_entities);
     Ajax::updateItemOnSelectEvent("dropdown_itemtype" . $rand, "items_id", $CFG_GLPI["root_doc"] . "/plugins/monitoring/ajax/dropdownDisplayviewItemtype.php", $params);
     echo "<span id='items_id'></span>";
     echo "<input type='hidden' name='x' value='1' />";
     echo "<input type='hidden' name='y' value='1' />";
     echo "</td>";
     echo "<td colspan='2'></td>";
     echo "</tr>";
     $this->showFormButtons($options);
     return true;
 }
Example #16
0
function plugin_headings_monitoring_dashboadservicecatalog($item)
{
    $pmServicescatalog = new PluginMonitoringServicescatalog();
    $pmDisplay = new PluginMonitoringDisplay();
    $pmDisplay->displayCounters("Businessrules");
    $pmServicescatalog->showBAChecks();
}
Example #17
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;
      }
   }
  ------------------------------------------------------------------------

  @package   Plugin Monitoring for GLPI
  @author    David Durieux
  @co-author
  @comment
  @copyright Copyright (c) 2011-2014 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";
Session::checkCentralAccess();
Html::header(__('Monitoring - dashboard (services catalogs)', 'monitoring'), $_SERVER["PHP_SELF"], "plugins", "PluginMonitoringDashboard", "dashboard");
// Reduced or normal interface ?
if (!isset($_SESSION['plugin_monitoring_reduced_interface'])) {
    $_SESSION['plugin_monitoring_reduced_interface'] = false;
}
$pmDisplay = new PluginMonitoringDisplay();
$pmServicescatalog = new PluginMonitoringServicescatalog();
$pmMessage = new PluginMonitoringMessage();
$pmMessage->getMessages();
$pmDisplay->menu();
Session::checkRight("plugin_monitoring_servicescatalog", PluginMonitoringServicescatalog::DASHBOARD);
$pmDisplay->showCounters("Businessrules");
$pmServicescatalog->showChecks($_SESSION['plugin_monitoring_reduced_interface']);
Html::footer();