Search::constructDatas PHP Method

constructDatas() static public method

add to data array a field data containing : cols : columns definition rows : rows data
static public constructDatas ( array &$data ) : nothing
$data array array of search datas prepared to get datas
return nothing
    static function constructDatas(array &$data)
    {
        global $CFG_GLPI;
        if (!isset($data['sql']) || !isset($data['sql']['search'])) {
            return false;
        }
        $data['data'] = array();
        // Use a ReadOnly connection if available and configured to be used
        $DBread = DBConnection::getReadConnection();
        $DBread->query("SET SESSION group_concat_max_len = 16384;");
        // directly increase group_concat_max_len to avoid double query
        if (count($data['search']['metacriteria'])) {
            foreach ($data['search']['metacriteria'] as $metacriterion) {
                if ($metacriterion['link'] == 'AND NOT' || $metacriterion['link'] == 'OR NOT') {
                    $DBread->query("SET SESSION group_concat_max_len = 4194304;");
                    break;
                }
            }
        }
        $result = $DBread->query($data['sql']['search']);
        /// Check group concat limit : if warning : increase limit
        if ($result2 = $DBread->query('SHOW WARNINGS')) {
            if ($DBread->numrows($result2) > 0) {
                $res = $DBread->fetch_assoc($result2);
                if ($res['Code'] == 1260) {
                    $DBread->query("SET SESSION group_concat_max_len = 8194304;");
                    $result = $DBread->query($data['sql']['search']);
                }
            }
        }
        if ($result) {
            $data['data']['totalcount'] = 0;
            // if real search or complete export : get numrows from request
            if (!$data['search']['no_search'] || $data['search']['export_all']) {
                $data['data']['totalcount'] = $DBread->numrows($result);
            } else {
                if (!isset($data['sql']['count']) || count($data['sql']['count']) == 0) {
                    $data['data']['totalcount'] = $DBread->numrows($result);
                } else {
                    foreach ($data['sql']['count'] as $sqlcount) {
                        $result_num = $DBread->query($sqlcount);
                        $data['data']['totalcount'] += $DBread->result($result_num, 0, 0);
                    }
                }
            }
            // Search case
            $data['data']['begin'] = $data['search']['start'];
            $data['data']['end'] = min($data['data']['totalcount'], $data['search']['start'] + $data['search']['list_limit']) - 1;
            // No search Case
            if ($data['search']['no_search']) {
                $data['data']['begin'] = 0;
                $data['data']['end'] = min($data['data']['totalcount'] - $data['search']['start'], $data['search']['list_limit']) - 1;
            }
            // Export All case
            if ($data['search']['export_all']) {
                $data['data']['begin'] = 0;
                $data['data']['end'] = $data['data']['totalcount'] - 1;
            }
            // Get columns
            $data['data']['cols'] = array();
            $num = 0;
            $searchopt =& self::getOptions($data['itemtype']);
            foreach ($data['toview'] as $key => $val) {
                $data['data']['cols'][$num] = array();
                $data['data']['cols'][$num]['itemtype'] = $data['itemtype'];
                $data['data']['cols'][$num]['id'] = $val;
                $data['data']['cols'][$num]['name'] = $searchopt[$val]["name"];
                $data['data']['cols'][$num]['meta'] = 0;
                $data['data']['cols'][$num]['searchopt'] = $searchopt[$val];
                $num++;
            }
            // Display columns Headers for meta items
            $already_printed = array();
            if (count($data['search']['metacriteria'])) {
                foreach ($data['search']['metacriteria'] as $metacriteria) {
                    if (isset($metacriteria['itemtype']) && !empty($metacriteria['itemtype']) && isset($metacriteria['value']) && strlen($metacriteria['value']) > 0) {
                        if (!isset($already_printed[$metacriteria['itemtype'] . $metacriteria['field']])) {
                            $searchopt =& self::getOptions($metacriteria['itemtype']);
                            $data['data']['cols'][$num]['itemtype'] = $metacriteria['itemtype'];
                            $data['data']['cols'][$num]['id'] = $metacriteria['field'];
                            $data['data']['cols'][$num]['name'] = $searchopt[$metacriteria['field']]["name"];
                            $data['data']['cols'][$num]['meta'] = 1;
                            $data['data']['cols'][$num]['searchopt'] = $searchopt[$metacriteria['field']];
                            $num++;
                            $already_printed[$metacriteria['itemtype'] . $metacriteria['field']] = 1;
                        }
                    }
                }
            }
            // search group (corresponding of dropdown optgroup) of current col
            foreach ($data['data']['cols'] as $num => $col) {
                // search current col in searchoptions ()
                while (key($searchopt) !== null && key($searchopt) != $col['id']) {
                    next($searchopt);
                }
                if (key($searchopt) !== null) {
                    //search optgroup (non array option)
                    while (key($searchopt) !== null && is_numeric(key($searchopt)) && is_array(current($searchopt))) {
                        prev($searchopt);
                    }
                    if (key($searchopt) !== null && key($searchopt) !== "common") {
                        $data['data']['cols'][$num]['groupname'] = current($searchopt);
                    }
                }
                //reset
                reset($searchopt);
            }
            // Get rows
            // if real search seek to begin of items to display (because of complete search)
            if (!$data['search']['no_search']) {
                $DBread->data_seek($result, $data['search']['start']);
            }
            $i = $data['data']['begin'];
            $data['data']['warning'] = "For compatibility keep raw data  (ITEM_X, META_X) at the top for the moment. Will be drop in next version";
            $data['data']['rows'] = array();
            $data['data']['items'] = array();
            self::$output_type = $data['display_type'];
            while ($i < $data['data']['totalcount'] && $i <= $data['data']['end']) {
                $row = $DBread->fetch_assoc($result);
                $newrow = array();
                $newrow['raw'] = $row;
                // Parse datas
                foreach ($newrow['raw'] as $key => $val) {
                    // For compatibility keep data at the top for the moment
                    // $newrow[$key] = $val;
                    $keysplit = explode('_', $key);
                    if (isset($keysplit[1]) && $keysplit[0] == 'ITEM') {
                        $j = $keysplit[1];
                        $fieldname = 'name';
                        if (isset($keysplit[2])) {
                            $fieldname = $keysplit[2];
                            $fkey = 3;
                            while (isset($keysplit[$fkey])) {
                                $fieldname .= '_' . $keysplit[$fkey];
                                $fkey++;
                            }
                        }
                        // No Group_concat case
                        if (strpos($val, self::LONGSEP) === false) {
                            $newrow[$j]['count'] = 1;
                            if (strpos($val, self::SHORTSEP) === false) {
                                if ($val == self::NULLVALUE) {
                                    $newrow[$j][0][$fieldname] = NULL;
                                } else {
                                    $newrow[$j][0][$fieldname] = $val;
                                }
                            } else {
                                $split2 = self::explodeWithID(self::SHORTSEP, $val);
                                $newrow[$j][0][$fieldname] = $split2[0];
                                $newrow[$j][0]['id'] = $split2[1];
                            }
                        } else {
                            if (!isset($newrow[$j])) {
                                $newrow[$j] = array();
                            }
                            $split = explode(self::LONGSEP, $val);
                            $newrow[$j]['count'] = count($split);
                            foreach ($split as $key2 => $val2) {
                                if (strpos($val2, self::SHORTSEP) === false) {
                                    $newrow[$j][$key2][$fieldname] = $val2;
                                } else {
                                    $split2 = self::explodeWithID(self::SHORTSEP, $val2);
                                    $newrow[$j][$key2]['id'] = $split2[1];
                                    if ($split2[0] == self::NULLVALUE) {
                                        $newrow[$j][$key2][$fieldname] = NULL;
                                    } else {
                                        $newrow[$j][$key2][$fieldname] = $split2[0];
                                    }
                                }
                            }
                        }
                    } else {
                        if ($key == 'currentuser') {
                            if (!isset($data['data']['currentuser'])) {
                                $data['data']['currentuser'] = $val;
                            }
                        } else {
                            $newrow[$key] = $val;
                            // Add id to items list
                            if ($key == 'id') {
                                $data['data']['items'][$val] = $i;
                            }
                        }
                    }
                }
                foreach ($data['data']['cols'] as $key => $val) {
                    $newrow[$key]['displayname'] = self::giveItem($val['itemtype'], $val['id'], $newrow, $key);
                }
                $data['data']['rows'][$i] = $newrow;
                $i++;
            }
            $data['data']['count'] = count($data['data']['rows']);
        } else {
            echo $DBread->error();
        }
    }

Usage Example

 /**
  * Display list of hosts
  */
 function showHostsBoard($params, $width = '', $limit = '')
 {
     global $DB, $CFG_GLPI;
     if (!isset($_SESSION['plugin_monitoring_reduced_interface'])) {
         $_SESSION['plugin_monitoring_reduced_interface'] = false;
     }
     $col_to_display = array(0, 10, 1, 2, 3, 6, 7, 8, 9, 11);
     $data = Search::prepareDatasForSearch('PluginMonitoringHost', $params, $col_to_display);
     $data['tocompute'] = $data['toview'];
     Search::constructSQL($data);
     //echo "<pre>";      print_r($data['sql']['search']);
     Search::constructDatas($data);
     //      if (! isset($_GET['order'])) {
     //         $_GET['order'] = "ASC";
     //      }
     //      if (! isset($_GET['sort'])) {
     //         $_GET['sort'] = "";
     //      }
     //
     //      $order = "ASC";
     //      if (isset($_GET['order'])) {
     //         $order = $_GET['order'];
     //      }
     //      $where = '';
     //      if (isset($_GET['field'])) {
     //         foreach ($_GET['field'] as $key=>$value) {
     //            $wheretmp = '';
     //            if (isset($_GET['link'][$key])) {
     //               $wheretmp.= " ".$_GET['link'][$key]." ";
     //            }
     //            $wheretmp .= Search::addWhere(
     //                                   "",
     //                                   0,
     //                                   "PluginMonitoringHost",
     //                                   $_GET['field'][$key],
     //                                   $_GET['searchtype'][$key],
     //                                   $_GET['contains'][$key]);
     //            if (!strstr($wheretmp, "``.``")) {
     //               if ($where != ''
     //                       AND !isset($_GET['link'][$key])) {
     //                  $where .= " AND ";
     //               }
     //               $where .= $wheretmp;
     //            }
     //         }
     //      }
     //      if ($where != '') {
     //         $where = "(".$where;
     //         $where .= ") AND ";
     //      }
     //      $where .= " CONCAT_WS('', `glpi_computers`.`entities_id`, `glpi_printers`.`entities_id`, `glpi_networkequipments`.`entities_id`) IN (".$_SESSION['glpiactiveentities_string'].")";
     //
     //      if ($where != '') {
     //         $where = " WHERE ".$where;
     //         $where = str_replace("`".getTableForItemType("PluginMonitoringDisplay")."`.",
     //                 "", $where);
     //
     //      }
     //
     //      $leftjoin = "
     //         LEFT JOIN `glpi_computers`
     //            ON `glpi_plugin_monitoring_hosts`.`items_id` = `glpi_computers`.`id`
     //               AND `glpi_plugin_monitoring_hosts`.`itemtype`='Computer'
     //         LEFT JOIN `glpi_printers`
     //            ON `glpi_plugin_monitoring_hosts`.`items_id` = `glpi_printers`.`id`
     //               AND `glpi_plugin_monitoring_hosts`.`itemtype`='Printer'
     //         LEFT JOIN `glpi_networkequipments`
     //            ON `glpi_plugin_monitoring_hosts`.`items_id` = `glpi_networkequipments`.`id`
     //               AND `glpi_plugin_monitoring_hosts`.`itemtype`='NetworkEquipment'
     //         LEFT JOIN `glpi_entities`
     //            ON CONCAT_WS('', `glpi_computers`.`entities_id`, `glpi_printers`.`entities_id`, `glpi_networkequipments`.`entities_id`) = `glpi_entities`.`id`
     //
     //      ";
     //
     //      // * ORDER
     //      $ORDERQUERY = "ORDER BY entity_name ASC, host_name ASC";
     //      $toview = array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
     //      $toviewComplete = array(
     //          'ITEM_0' => 'entity_name',
     //          'ITEM_1' => 'host_name',
     //          'ITEM_2' => 'host_state',
     //          'ITEM_3' => 'service_state',
     //          'ITEM_4' => 'last_check',
     //          'ITEM_5' => 'event',
     //          'ITEM_6' => 'perf_data',
     //          'ITEM_7' => 'is_acknowledged'
     //      );
     //      foreach ($toview as $key => $val) {
     //         if ($_GET['sort']==$val) {
     //            $ORDERQUERY = Search::addOrderBy("PluginMonitoringHost", $_GET['sort'],
     //                                             $_GET['order'], $key);
     //            foreach ($toviewComplete as $keyi=>$vali) {
     //               $ORDERQUERY= str_replace($keyi, $vali, $ORDERQUERY);
     //            }
     //         }
     //      }
     //
     ////            `glpi_computers`.*
     //
     //      $query = "SELECT
     //            `glpi_entities`.`name` AS entity_name,
     //            CONCAT_WS('', `glpi_computers`.`id`, `glpi_printers`.`id`, `glpi_networkequipments`.`id`) AS idComputer,
     //            CONCAT_WS('', `glpi_computers`.`name`, `glpi_printers`.`name`, `glpi_networkequipments`.`name`) AS host_name,
     //            `glpi_plugin_monitoring_hosts`.*,
     //            `glpi_plugin_monitoring_hosts`.`state` AS host_state,
     //            `glpi_plugin_monitoring_hosts`.`is_acknowledged` AS host_acknowledged
     //         FROM `glpi_plugin_monitoring_hosts`
     //         ".$leftjoin."
     //         ".$where."
     //         ".$ORDERQUERY;
     //      // Toolbox::logInFile("pm", "Query hosts - $query\n");
     //
     //      $result = $DB->query($query);
     //
     //      if (! isset($_GET["start"])) {
     //         $_GET["start"]=0;
     //      }
     //      $start=$_GET['start'];
     //      if (! isset($_GET["order"])) {
     //         $_GET["order"]="ASC";
     //      }
     $rand = mt_rand();
     if (!isset($data['data']) || !isset($data['data']['totalcount'])) {
         return false;
     }
     // Contruct Pager parameters
     $globallinkto = Toolbox::append_params(array('criteria' => Toolbox::stripslashes_deep($data['search']['criteria']), 'metacriteria' => Toolbox::stripslashes_deep($data['search']['metacriteria'])), '&amp;');
     $parameters = "sort=" . $data['search']['sort'] . "&amp;order=" . $data['search']['order'] . '&amp;' . $globallinkto;
     if (isset($_GET['_in_modal'])) {
         $parameters .= "&amp;_in_modal=1";
     }
     // If the begin of the view is before the number of items
     if ($data['data']['count'] > 0) {
         // Display pager only for HTML
         if ($data['display_type'] == Search::HTML_OUTPUT) {
             $search_config_top = "";
             $search_config_bottom = "";
             Html::printPager($data['search']['start'], $data['data']['totalcount'], $data['search']['target'], $parameters, $data['itemtype'], 0, $search_config_top);
         }
         // Define begin and end var for loop
         // Search case
         $begin_display = $data['data']['begin'];
         $end_display = $data['data']['end'];
     }
     echo '<div id="custom_date" style="display:none"></div>';
     echo '<div id="custom_time" style="display:none"></div>';
     if ($width == '') {
         echo "<table class='tab_cadrehov' style='width:100%;'>";
     } else {
         echo "<table class='tab_cadrehov' style='width:" . $width . "px;'>";
     }
     $num = 0;
     if (Session::haveRight("plugin_monitoring_hostcommand", CREATE)) {
         // Host test command ...
         $pmCommand = new PluginMonitoringCommand();
         $a_commands = array();
         $a_list = $pmCommand->find("command_name LIKE 'host_action'");
         foreach ($a_list as $dt) {
             $host_command_name = $dt['name'];
             $host_command_command = $dt['command_line'];
         }
     }
     echo "<tr class='tab_bg_1'>";
     $this->showHeaderItem(__('Entity'), 0, $num, $begin_display, $globallinkto, 'host.php', 'PluginMonitoringHost');
     $this->showHeaderItem(__('Type'), 0, $num, $begin_display, $globallinkto, 'host.php', 'PluginMonitoringHost');
     $this->showHeaderItem(__('Host', 'monitoring'), 1, $num, $begin_display, $globallinkto, 'host.php', 'PluginMonitoringHost');
     $this->showHeaderItem(__('Host state'), 2, $num, $begin_display, $globallinkto, 'host.php', 'PluginMonitoringHost');
     if (isset($host_command_name)) {
         echo '<th>' . __('Host action', 'monitoring') . '</th>';
     }
     echo '<th>' . __('Host resources state', 'monitoring') . '</th>';
     echo '<th>' . __('IP address', 'monitoring') . '</th>';
     $this->showHeaderItem(__('Last check', 'monitoring'), 4, $num, $begin_display, $globallinkto, 'host.php', 'PluginMonitoringHost');
     $this->showHeaderItem(__('Result details', 'monitoring'), 5, $num, $begin_display, $globallinkto, 'host.php', 'PluginMonitoringHost');
     $this->showHeaderItem(__('Performance data', 'monitoring'), 6, $num, $begin_display, $globallinkto, 'host.php', 'PluginMonitoringHost');
     if (Session::haveRight("plugin_monitoring_acknowledge", READ) || Session::haveRight("plugin_monitoring_downtime", READ)) {
         $this->showHeaderItem(__('Maintenance', 'monitoring'), 7, $num, $begin_display, $globallinkto, 'host.php', 'PluginMonitoringHost');
     }
     echo "</tr>";
     foreach ($data['data']['rows'] as $row) {
         // Reduced array or not ?
         if ($_SESSION['plugin_monitoring_reduced_interface'] && $row[3]['displayname'] == 'UP') {
             continue;
         }
         if (isset($host_command_name)) {
             $row['host_command_name'] = $host_command_name;
             $row['host_command_command'] = $host_command_command;
         }
         // Get all host services except if state is ok or is already acknowledged ...
         $a_ret = PluginMonitoringHost::getServicesState($row['id'], "`glpi_plugin_monitoring_services`.`state` != 'OK'\n                                                         AND `glpi_plugin_monitoring_services`.`is_acknowledged` = '0'");
         $row['host_services_state'] = $a_ret[0];
         $row['host_services_state_list'] = $a_ret[1];
         // Get host first IP address
         $row['ip'] = __('Unknown IP address', 'monitoring');
         $ip = PluginMonitoringHostaddress::getIp($row[9]['displayname'], $row[1]['displayname'], '');
         if ($ip != '') {
             $row['ip'] = $ip;
         }
         echo "<tr class='tab_bg_3'>";
         $this->displayHostLine($row);
         echo "</tr>";
     }
     echo "</table>";
     echo "<br/>";
     Html::printPager($data['search']['start'], $data['data']['totalcount'], $data['search']['target'], $parameters, '', 0, $search_config_bottom);
 }
All Usage Examples Of Search::constructDatas