makeTextSearch() static public méthode

Create SQL search condition
static public makeTextSearch ( $val, $not = false ) : search
$val string value to search
$not boolean is a negative search ? (false by default)
Résultat search string
Exemple #1
0
function plugin_mreporting_addWhere($link, $nott, $type, $ID, $val, $searchtype)
{
    $searchopt =& Search::getOptions($type);
    $table = $searchopt[$ID]["table"];
    $field = $searchopt[$ID]["field"];
    $SEARCH = Search::makeTextSearch($val, $nott);
    exit;
    switch ($table . "." . $field) {
        case "glpi_plugin_mreporting_configs.graphtype":
            return $link . " `{$table}`.`{$field}` = '{$val}' ";
    }
    return "";
}
    $recursive = $item->maybeRecursive();
    $where = getEntitiesRestrictRequest("WHERE", $_POST['table'], '', $entity, $recursive);
} else {
    $where = "WHERE 1";
}
if (isset($_POST['used']) && !empty($_POST['used'])) {
    $where .= " AND `id` NOT IN ('" . implode("','", $_POST['used']) . "') ";
}
if ($item->maybeDeleted()) {
    $where .= " AND `is_deleted` = '0' ";
}
if ($item->maybeTemplate()) {
    $where .= " AND `is_template` = '0' ";
}
if (strlen($_POST['searchText']) > 0) {
    $search = Search::makeTextSearch($_POST['searchText']);
    $where .= " AND (`name` " . $search . "\n                    OR `id` = '" . $_POST['searchText'] . "'";
    if (FieldExists($_POST['table'], "contact")) {
        $where .= " OR `contact` " . $search;
    }
    if (FieldExists($_POST['table'], "serial")) {
        $where .= " OR `serial` " . $search;
    }
    if (FieldExists($_POST['table'], "otherserial")) {
        $where .= " OR `otherserial` " . $search;
    }
    $where .= ")";
}
//If software or plugins : filter to display only the objects that are allowed to be visible in Helpdesk
if (in_array($_POST['itemtype'], $CFG_GLPI["helpdesk_visible_types"])) {
    $where .= " AND `is_helpdesk_visible` = '1' ";
Exemple #3
0
if (!isset($_POST['page'])) {
    $_POST['page'] = 1;
    $_POST['page_limit'] = $CFG_GLPI['dropdown_max'];
}
$start = intval(($_POST['page'] - 1) * $_POST['page_limit']);
$limit = intval($_POST['page_limit']);
$LIMIT = "LIMIT {$start},{$limit}";
$one_item = -1;
if (isset($_POST['_one_id'])) {
    $one_item = $_POST['_one_id'];
}
if ($one_item >= 0) {
    $where .= " AND `glpi_netpoints`.`id` = '{$one_item}'";
} else {
    if (strlen($_POST['searchText']) > 0) {
        $where = " WHERE (`glpi_netpoints`.`name` " . Search::makeTextSearch($_POST['searchText']) . "\n                        OR `glpi_locations`.`completename` " . Search::makeTextSearch($_POST['searchText']) . ")";
    } else {
        $where = " WHERE 1 ";
    }
}
if (!(isset($_POST["devtype"]) && $_POST["devtype"] != 'NetworkEquipment' && isset($_POST["locations_id"]) && $_POST["locations_id"] > 0)) {
    if (isset($_POST["entity_restrict"]) && $_POST["entity_restrict"] >= 0) {
        $where .= " AND `glpi_netpoints`.`entities_id` = '" . $_POST["entity_restrict"] . "'";
    } else {
        $where .= getEntitiesRestrictRequest(" AND ", "glpi_locations");
    }
}
$query = "SELECT `glpi_netpoints`.`comment` AS comment,\n                 `glpi_netpoints`.`id`,\n                 `glpi_netpoints`.`name` AS netpname,\n                 `glpi_locations`.`completename` AS loc\n          FROM `glpi_netpoints`\n          LEFT JOIN `glpi_locations` ON (`glpi_netpoints`.`locations_id` = `glpi_locations`.`id`) ";
if (isset($_POST["devtype"]) && !empty($_POST["devtype"])) {
    $query .= "LEFT JOIN `glpi_networkportethernets`\n                  ON (`glpi_netpoints`.`id` = `glpi_networkportethernets`.`netpoints_id`)\n              LEFT JOIN `glpi_networkports`\n                  ON (`glpi_networkports`.`id` = `glpi_networkportethernets`.`id`\n                      AND `glpi_networkports`.`instantiation_type` = 'NetworkPortEthernet'\n                      AND `glpi_networkports`.`itemtype`";
    if ($_POST["devtype"] == 'NetworkEquipment') {
Exemple #4
0
    $recursive = $item->maybeRecursive();
    $where = getEntitiesRestrictRequest("WHERE", $_GET['table'], '', $entity, $recursive);
} else {
    $where = "WHERE 1";
}
if (isset($_GET['used']) && !empty($_GET['used'])) {
    $where .= " AND `id` NOT IN ('" . implode("','", $_GET['used']) . "') ";
}
if ($item->maybeDeleted()) {
    $where .= " AND `is_deleted` = '0' ";
}
if ($item->maybeTemplate()) {
    $where .= " AND `is_template` = '0' ";
}
if (strlen($_GET['searchText']) > 0) {
    $search = Search::makeTextSearch($_GET['searchText']);
    $where .= " AND (`name` " . $search . "\n                    OR `id` = '" . $_GET['searchText'] . "'";
    if (FieldExists($_GET['table'], "contact")) {
        $where .= " OR `contact` " . $search;
    }
    if (FieldExists($_GET['table'], "serial")) {
        $where .= " OR `serial` " . $search;
    }
    if (FieldExists($_GET['table'], "otherserial")) {
        $where .= " OR `otherserial` " . $search;
    }
    $where .= ")";
}
//If software or plugins : filter to display only the objects that are allowed to be visible in Helpdesk
if (in_array($_GET['itemtype'], $CFG_GLPI["helpdesk_visible_types"])) {
    $where .= " AND `is_helpdesk_visible` = '1' ";
 /**
  * Generic Function to add where to a request
  *
  * @param $link link string
  * @param $nott is it a negative serach ?
  * @param $itemtype item type
  * @param $ID ID of the item to search
  * @param $searchtype searchtype used (equals or contains)
  * @param $val item num in the request
  * @param $meta is a meta search (meta=2 in search.class.php)
  *
  * @return select string
  **/
 static function addWhere($link, $nott, $itemtype, $ID, $searchtype, $val, $meta = 0)
 {
     $searchopt =& Search::getOptions($itemtype);
     $table = $searchopt[$ID]["table"];
     $field = $searchopt[$ID]["field"];
     $inittable = $table;
     $addtable = '';
     /*if ($table != getTableForItemType($itemtype)
           && $searchopt[$ID]["linkfield"] != getForeignKeyFieldForTable($table)) {
          $addtable = "_".$searchopt[$ID]["linkfield"];
          $table .= $addtable;
       }*/
     if (isset($searchopt[$ID]['joinparams'])) {
         $complexjoin = Search::computeComplexJoinID($searchopt[$ID]['joinparams']);
         if (!empty($complexjoin)) {
             $table .= "_" . $complexjoin;
         }
     }
     if ($meta && getTableForItemType($itemtype) != $table) {
         $table .= "_" . $itemtype;
     }
     // Hack to allow search by ID on every sub-table
     if (preg_match('/^\\$\\$\\$\\$([0-9]+)$/', $val, $regs)) {
         return $link . " (`{$table}`.`id` " . ($nott ? "<>" : "=") . $regs[1] . " " . ($regs[1] == 0 ? " OR `{$table}`.`id` IS NULL" : '') . ") ";
     }
     // Preparse value
     if (isset($searchopt[$ID]["datatype"])) {
         switch ($searchopt[$ID]["datatype"]) {
             case "datetime":
             case "date":
             case "date_delay":
                 $format_use = "Y-m-d";
                 if ($searchopt[$ID]["datatype"] == 'datetime') {
                     $format_use = "Y-m-d H:i:s";
                 }
                 // Parsing relative date
                 if ($val == 'NOW') {
                     $val = date($format_use);
                 }
                 if (preg_match("/^(-?)(\\d+)(\\w+)\$/", $val, $matches)) {
                     if (in_array($matches[3], array('YEAR', 'MONTH', 'WEEK', 'DAY', 'HOUR'))) {
                         $nb = intval($matches[2]);
                         if ($matches[1] == '-') {
                             $nb = -$nb;
                         }
                         // Use it to have a clean delay computation (MONTH / YEAR have not always the same duration)
                         $hour = date("H");
                         $minute = date("i");
                         $second = 0;
                         $month = date("n");
                         $day = date("j");
                         $year = date("Y");
                         switch ($matches[3]) {
                             case "YEAR":
                                 $year += $nb;
                                 break;
                             case "MONTH":
                                 $month += $nb;
                                 break;
                             case "WEEK":
                                 $day += 7 * $nb;
                                 break;
                             case "DAY":
                                 $day += $nb;
                                 break;
                             case "HOUR":
                                 $hour += $nb;
                                 break;
                         }
                         $val = date($format_use, mktime($hour, $minute, $second, $month, $day, $year));
                     }
                 }
                 break;
         }
     }
     switch ($searchtype) {
         case "contains":
             $SEARCH = Search::makeTextSearch($val, $nott);
             break;
         case "equals":
             if ($nott) {
                 $SEARCH = " <> '{$val}'";
             } else {
                 $SEARCH = " = '{$val}'";
             }
             break;
         case "notequals":
             if ($nott) {
                 $SEARCH = " = '{$val}'";
             } else {
                 $SEARCH = " <> '{$val}'";
             }
             break;
     }
     // Plugin can override core definition for its type
     if ($plug = isPluginItemType($itemtype)) {
         $function = 'plugin_' . $plug['plugin'] . '_addWhere';
         if (function_exists($function)) {
             $out = $function($link, $nott, $itemtype, $ID, $val);
             if (!empty($out)) {
                 return $out;
             }
         }
     }
     switch ($inittable . "." . $field) {
         //          case "glpi_users_validation.name" :
         case "glpi_users.name":
             if ($itemtype == 'User') {
                 // glpi_users case / not link table
                 if (in_array($searchtype, array('equals', 'notequals'))) {
                     return " {$link} `{$table}`.`id`" . $SEARCH;
                 }
                 return Search::makeTextCriteria("`{$table}`.`{$field}`", $val, $nott, $link);
             }
             if ($_SESSION["glpinames_format"] == FIRSTNAME_BEFORE) {
                 $name1 = 'firstname';
                 $name2 = 'realname';
             } else {
                 $name1 = 'realname';
                 $name2 = 'firstname';
             }
             if (in_array($searchtype, array('equals', 'notequals'))) {
                 return " {$link} (`{$table}`.`id`" . $SEARCH . ($val == 0 ? " OR `{$table}`.`id` IS NULL" : '') . ') ';
             }
             return $link . " (`{$table}`.`{$name1}` {$SEARCH}\n                            OR `{$table}`.`{$name2}` {$SEARCH}\n                            OR CONCAT(`{$table}`.`{$name1}`, ' ',\n                                      `{$table}`.`{$name2}`) {$SEARCH}" . Search::makeTextCriteria("`{$table}`.`{$field}`", $val, $nott, 'OR') . ") ";
         case "glpi_groups.name":
             $linkfield = "";
             if (in_array($searchtype, array('equals', 'notequals'))) {
                 return " {$link} (`{$table}`.`id`" . $SEARCH . ($val == 0 ? " OR `{$table}`.`id` IS NULL" : '') . ') ';
             }
             return Search::makeTextCriteria("`{$table}`.`{$field}`", $val, $nott, $link);
     }
     //// Default cases
     // Link with plugin tables
     if (preg_match("/^glpi_plugin_([a-z0-9]+)/", $inittable, $matches)) {
         if (count($matches) == 2) {
             $plug = $matches[1];
             $function = 'plugin_' . $plug . '_addWhere';
             if (function_exists($function)) {
                 $out = $function($link, $nott, $itemtype, $ID, $val);
                 if (!empty($out)) {
                     return $out;
                 }
             }
         }
     }
     $tocompute = "`{$table}`.`{$field}`";
     if (isset($searchopt[$ID]["computation"])) {
         $tocompute = $searchopt[$ID]["computation"];
         $tocompute = str_replace("TABLE", "`{$table}`", $tocompute);
     }
     // Preformat items
     if (isset($searchopt[$ID]["datatype"])) {
         switch ($searchopt[$ID]["datatype"]) {
             case "itemtypename":
                 if (in_array($searchtype, array('equals', 'notequals'))) {
                     return " {$link} (`{$table}`.`{$field}`" . $SEARCH . ') ';
                 }
             case "datetime":
             case "date":
             case "date_delay":
                 if ($searchopt[$ID]["datatype"] == 'datetime') {
                     // Specific search for datetime
                     if (in_array($searchtype, array('equals', 'notequals'))) {
                         $val = preg_replace("/:00\$/", '', $val);
                         $val = '^' . $val;
                         if ($searchtype == 'notequals') {
                             $nott = !$nott;
                         }
                         return Search::makeTextCriteria("`{$table}`.`{$field}`", $val, $nott, $link);
                     }
                 }
                 if ($searchtype == 'lessthan') {
                     $val = '<' . $val;
                 }
                 if ($searchtype == 'morethan') {
                     $val = '>' . $val;
                 }
                 if ($searchtype) {
                     $date_computation = $tocompute;
                 }
                 $search_unit = ' MONTH ';
                 if (isset($searchopt[$ID]['searchunit'])) {
                     $search_unit = $searchopt[$ID]['searchunit'];
                 }
                 if ($searchopt[$ID]["datatype"] == "date_delay") {
                     $delay_unit = ' MONTH ';
                     if (isset($searchopt[$ID]['delayunit'])) {
                         $delay_unit = $searchopt[$ID]['delayunit'];
                     }
                     $date_computation = "ADDDATE(`{$table}`." . $searchopt[$ID]["datafields"][1] . ",\n                                               INTERVAL `{$table}`." . $searchopt[$ID]["datafields"][2] . "\n                                               {$delay_unit})";
                 }
                 if (in_array($searchtype, array('equals', 'notequals'))) {
                     return " {$link} ({$date_computation} " . $SEARCH . ') ';
                 }
                 $search = array("/\\&lt;/", "/\\&gt;/");
                 $replace = array("<", ">");
                 $val = preg_replace($search, $replace, $val);
                 if (preg_match("/^\\s*([<>=]+)(.*)/", $val, $regs)) {
                     if (is_numeric($regs[2])) {
                         return $link . " {$date_computation} " . $regs[1] . "\n                            ADDDATE(NOW(), INTERVAL " . $regs[2] . " {$search_unit}) ";
                     }
                     // ELSE Reformat date if needed
                     $regs[2] = preg_replace('@(\\d{1,2})(-|/)(\\d{1,2})(-|/)(\\d{4})@', '\\5-\\3-\\1', $regs[2]);
                     if (preg_match('/[0-9]{2,4}-[0-9]{1,2}-[0-9]{1,2}/', $regs[2])) {
                         return $link . " {$date_computation} " . $regs[1] . " '" . $regs[2] . "'";
                     }
                     return "";
                 }
                 // ELSE standard search
                 // Date format modification if needed
                 $val = preg_replace('@(\\d{1,2})(-|/)(\\d{1,2})(-|/)(\\d{4})@', '\\5-\\3-\\1', $val);
                 return Search::makeTextCriteria($date_computation, $val, $nott, $link);
             case "right":
                 if ($val == 'NULL' || $val == 'null') {
                     return $link . " {$tocompute} IS " . ($nott ? 'NOT' : '') . " NULL ";
                 }
                 return $link . " {$tocompute} = '{$val}' ";
             case "bool":
                 if (!is_numeric($val)) {
                     if (strcasecmp($val, __('No')) == 0) {
                         $val = 0;
                     } else {
                         if (strcasecmp($val, __('Yes')) == 0) {
                             $val = 1;
                         }
                     }
                 }
                 // No break here : use number comparaison case
             // No break here : use number comparaison case
             case "number":
             case "decimal":
             case "timestamp":
                 $search = array("/\\&lt;/", "/\\&gt;/");
                 $replace = array("<", ">");
                 $val = preg_replace($search, $replace, $val);
                 if (preg_match("/([<>])([=]*)[[:space:]]*([0-9]+)/", $val, $regs)) {
                     if ($nott) {
                         if ($regs[1] == '<') {
                             $regs[1] = '>';
                         } else {
                             $regs[1] = '<';
                         }
                     }
                     $regs[1] .= $regs[2];
                     return $link . " ({$tocompute} " . $regs[1] . " " . $regs[3] . ") ";
                 }
                 if (is_numeric($val)) {
                     if (isset($searchopt[$ID]["width"])) {
                         $ADD = "";
                         if ($nott && $val != 'NULL' && $val != 'null') {
                             $ADD = " OR {$tocompute} IS NULL";
                         }
                         if ($nott) {
                             return $link . " ({$tocompute} < " . (intval($val) - $searchopt[$ID]["width"]) . "\n                                        OR {$tocompute} > " . (intval($val) + $searchopt[$ID]["width"]) . "\n                                        {$ADD}) ";
                         }
                         return $link . " (({$tocompute} >= " . (intval($val) - $searchopt[$ID]["width"]) . "\n                                      AND {$tocompute} <= " . (intval($val) + $searchopt[$ID]["width"]) . ")\n                                     {$ADD}) ";
                     }
                     if (!$nott) {
                         return " {$link} ({$tocompute} = " . intval($val) . ") ";
                     }
                     return " {$link} ({$tocompute} <> " . intval($val) . ") ";
                 }
                 break;
         }
     }
     // Default case
     if (in_array($searchtype, array('equals', 'notequals'))) {
         $out = " {$link} (`{$table}`.`id`" . $SEARCH;
         if ($searchtype == 'notequals') {
             $nott = !$nott;
         }
         // Add NULL if $val = 0 and not negative search
         if (!$nott && $val == 0) {
             $out .= " OR `{$table}`.`id` IS NULL";
         }
         $out .= ')';
         return $out;
     }
     return Search::makeTextCriteria($tocompute, $val, $nott, $link);
 }
Exemple #6
0
        if (isset($_GET["entity_restrict"]) && !($_GET["entity_restrict"] < 0)) {
            $where .= getEntitiesRestrictRequest("AND", $_GET['table'], "entities_id", $_GET["entity_restrict"], $multi);
            if (is_array($_GET["entity_restrict"]) && count($_GET["entity_restrict"]) > 1) {
                $multi = true;
            }
        } else {
            $where .= getEntitiesRestrictRequest("AND", $_GET['table'], '', '', $multi);
            if (count($_SESSION['glpiactiveentities']) > 1) {
                $multi = true;
            }
        }
    }
}
$field = "name";
if ($_GET['searchText'] != $CFG_GLPI["ajax_wildcard"]) {
    $where .= " AND {$field} " . Search::makeTextSearch($_GET['searchText']);
}
$query = "SELECT *\n          FROM `" . $_GET['table'] . "`\n          {$where} ";
if ($config->fields['use_view_all_object'] && $_GET["name"] != "type") {
    $query .= "ORDER BY `locations_id`";
} else {
    if ($multi) {
        $query .= " ORDER BY `entities_id`, {$field}\n                 {$LIMIT}";
    } else {
        $query .= " ORDER BY {$field}\n                 {$LIMIT}";
    }
}
$result = $DB->query($query);
$out = array();
$number = $DB->numrows($result);
if ($number != 0 && $_GET["locations_id"] == -1) {
*/
/** @file
* @brief
*/
if (strpos($_SERVER['PHP_SELF'], "dropdownSelectSoftwareLicense.php")) {
    $AJAX_INCLUDE = 1;
    include '../inc/includes.php';
    header("Content-Type: text/html; charset=UTF-8");
    Html::header_nocache();
}
Session::checkRight("software", "w");
// Make a select box
$rand = mt_rand();
$where = "";
if (strlen($_POST['searchText']) > 0 && $_POST['searchText'] != $CFG_GLPI["ajax_wildcard"]) {
    $where .= " AND `glpi_softwares`.`name` " . Search::makeTextSearch($_POST['searchText']) . " ";
}
$where .= getEntitiesRestrictRequest(' AND', 'glpi_softwarelicenses', 'entities_id', $_POST["entity_restrict"], true);
$query = "SELECT DISTINCT `glpi_softwares`.`id`,\n                          `glpi_softwares`.`name`\n          FROM `glpi_softwares`\n          INNER JOIN `glpi_softwarelicenses`\n               ON (`glpi_softwares`.`id` = `glpi_softwarelicenses`.`softwares_id`)\n          WHERE `glpi_softwares`.`is_deleted` = '0'\n                AND `glpi_softwares`.`is_template` = '0'\n                {$where}\n          ORDER BY `glpi_softwares`.`name`";
$result = $DB->query($query);
echo "<select name='softwares_id' id='item_type{$rand}'>\n";
echo "<option value='0'>" . Dropdown::EMPTY_VALUE . "</option>\n";
if ($DB->numrows($result)) {
    while ($data = $DB->fetch_assoc($result)) {
        $softwares_id = $data["id"];
        $output = $data["name"];
        echo "<option value='{$softwares_id}' title=\"" . Html::cleanInputText($output) . "\">" . Toolbox::substr($output, 0, $_SESSION["glpidropdown_chars_limit"]) . "</option>";
    }
}
echo "</select>\n";
$paramsselsoft = array('softwares_id' => '__VALUE__', 'entity_restrict' => $_POST['entity_restrict'], 'myname' => $_POST['myname']);
    $where .= getEntitiesRestrictRequest("AND", "glpi_plugin_domains_domains", '', '', true);
}
if (isset($_POST['used'])) {
    $where .= " AND `id` NOT IN (0";
    if (is_array($_POST['used'])) {
        $used = $_POST['used'];
    } else {
        $used = Toolbox::decodeArrayFromInput($_POST['used']);
    }
    foreach ($used as $val) {
        $where .= ",{$val}";
    }
    $where .= ") ";
}
if ($_POST['searchText'] != $CFG_GLPI["ajax_wildcard"]) {
    $where .= " AND `glpi_plugin_domains_domains`.`name` " . Search::makeTextSearch($_POST['searchText']);
}
$NBMAX = $CFG_GLPI["dropdown_max"];
$LIMIT = "LIMIT 0,{$NBMAX}";
if ($_POST['searchText'] == $CFG_GLPI["ajax_wildcard"]) {
    $LIMIT = "";
}
$query = "SELECT * \n\t\tFROM `glpi_plugin_domains_domains` \n\t\t{$where} \n\t\tORDER BY `entities_id`, `name` {$LIMIT}";
$result = $DB->query($query);
echo "<select name=\"" . $_POST['myname'] . "\">";
echo "<option value=\"0\">" . Dropdown::EMPTY_VALUE . "</option>";
if ($DB->numrows($result)) {
    $prev = -1;
    while ($data = $DB->fetch_array($result)) {
        if ($data["entities_id"] != $prev) {
            if ($prev >= 0) {
    $where .= getEntitiesRestrictRequest("AND", "glpi_plugin_certificates_certificates", '', '', true);
}
if (isset($_POST['used'])) {
    $where .= " AND id NOT IN (0";
    if (is_array($_POST['used'])) {
        $used = $_POST['used'];
    } else {
        $used = Toolbox::decodeArrayFromInput($_POST['used']);
    }
    foreach ($used as $val) {
        $where .= ",{$val}";
    }
    $where .= ") ";
}
if ($_POST['searchText'] != $CFG_GLPI["ajax_wildcard"]) {
    $where .= " AND `glpi_plugin_certificates_certificates`.`name` " . Search::makeTextSearch($_POST['searchText']);
}
$NBMAX = $CFG_GLPI["dropdown_max"];
$LIMIT = "LIMIT 0,{$NBMAX}";
if ($_POST['searchText'] == $CFG_GLPI["ajax_wildcard"]) {
    $LIMIT = "";
}
$query = "SELECT *\n\t\tFROM `glpi_plugin_certificates_certificates`\n\t\t{$where}\n\t\tORDER BY `entities_id`, `name` {$LIMIT}";
$result = $DB->query($query);
echo "<select name=\"" . $_POST['myname'] . "\">";
echo "<option value=\"0\">" . Dropdown::EMPTY_VALUE . "</option>";
if ($DB->numrows($result)) {
    $prev = -1;
    while ($data = $DB->fetch_array($result)) {
        if ($data["entities_id"] != $prev) {
            if ($prev >= 0) {
Exemple #10
0
 static function getSqlSearchResult($count = true, $entity_restrict = -1, $value = 0, $used = array(), $search = '')
 {
     global $DB, $CFG_GLPI;
     // No entity define : use active ones
     if ($entity_restrict < 0) {
         $entity_restrict = $_SESSION["glpiactiveentities"];
     }
     $joinprofile = false;
     $where = " `glpi_plugin_resources_resources`.`is_deleted` = '0'\n                  AND `glpi_plugin_resources_resources`.`is_leaving` = '0'\n                  AND `glpi_plugin_resources_resources`.`is_template` = '0' ";
     $where .= getEntitiesRestrictRequest('AND', 'glpi_plugin_resources_resources', '', $entity_restrict, true);
     if (is_numeric($value) && $value || count($used)) {
         $where .= " AND `glpi_plugin_resources_resources`.`id` NOT IN (0";
         if (is_numeric($value)) {
             $first = false;
             $where .= $value;
         } else {
             $first = true;
         }
         if (is_array($used)) {
             foreach ($used as $val) {
                 if ($first) {
                     $first = false;
                 } else {
                     $where .= ",";
                 }
                 $where .= $val;
             }
         }
         $where .= ")";
     }
     if ($count) {
         $query = "SELECT COUNT(DISTINCT `glpi_plugin_resources_resources`.`id` ) AS cpt\n                   FROM `glpi_plugin_resources_resources` ";
     } else {
         $query = "SELECT DISTINCT `glpi_plugin_resources_resources`.*,\n                          `glpi_users`.`registration_number`,\n                          `glpi_users`.`name` AS username\n                   FROM `glpi_plugin_resources_resources`\n                   LEFT JOIN `glpi_plugin_resources_resources_items`\n                      ON (`glpi_plugin_resources_resources_items`.`plugin_resources_resources_id`\n                          = `glpi_plugin_resources_resources`.`id`)\n                    LEFT JOIN `glpi_users`\n                      ON (`glpi_users`.`id` = `glpi_plugin_resources_resources_items`.`items_id`\n                            AND `glpi_plugin_resources_resources_items`.`itemtype` = 'User') ";
     }
     if ($count) {
         $query .= " WHERE {$where} ";
     } else {
         if (strlen($search) > 0 && $search != $CFG_GLPI["ajax_wildcard"]) {
             $where .= " AND (`glpi_plugin_resources_resources`.`name` " . Search::makeTextSearch($search) . "\n                             OR `glpi_plugin_resources_resources`.`firstname` " . Search::makeTextSearch($search) . "\n                             OR `glpi_users`.`registration_number` " . Search::makeTextSearch($search) . "\n                             OR `glpi_users`.`name` " . Search::makeTextSearch($search) . "\n                             OR CONCAT(`glpi_plugin_resources_resources`.`name`,' ',`glpi_plugin_resources_resources`.`firstname`,' ',`glpi_users`.`registration_number`,' ',`glpi_users`.`name`) " . Search::makeTextSearch($search) . ")";
         }
         $query .= " WHERE {$where} ";
         if ($_SESSION["glpinames_format"] == User::FIRSTNAME_BEFORE) {
             $query .= " ORDER BY `glpi_plugin_resources_resources`.`firstname`,\n                               `glpi_plugin_resources_resources`.`name` ";
         } else {
             $query .= " ORDER BY `glpi_plugin_resources_resources`.`firstname`,\n                               `glpi_plugin_resources_resources`.`name` ";
         }
         if ($search != $CFG_GLPI["ajax_wildcard"]) {
             $query .= " LIMIT 0," . $CFG_GLPI["dropdown_max"];
         }
     }
     return $DB->query($query);
 }
 if (strstr($link, '[DOMAIN]')) {
     // DOMAIN
     if (isset($item->fields['domains_id'])) {
         $shellExecute = "onClick=\"window.open('" . $CFG_GLPI["root_doc"] . "/plugins/shellcommands/front/shellcommand.exec.php?plugin_shellcommands_shellcommands_id=" . $shell_item->getName() . "&amp;value=" . Dropdown::getDropdownName("glpi_domains", $item->getField('domains_id')) . "' ,'mywindow', 'height=300, width=700, top=100, left=100, scrollbars=yes' )\"";
     }
 } else {
     if (strstr($link, '[IP]') || strstr($link, '[MAC]')) {
         // IP or MAC
         $ip = array();
         $mac = array();
         $resultSelectCommand[0] = Dropdown::EMPTY_VALUE;
         $ipCount = 0;
         $macCount = 0;
         if ($_POST['searchText'] != $CFG_GLPI["ajax_wildcard"]) {
             // if search text is called (ajax dropdown)
             $where = " AND `glpi_networkports`.`name` " . Search::makeTextSearch($_POST['searchText']);
         } else {
             $where = '';
         }
         // We search all ip and mac addresses
         $query2 = "SELECT `glpi_networkports`.*, `glpi_ipaddresses`.`name` as ip\n                     FROM `glpi_networkports`\n                     LEFT JOIN `glpi_networknames`\n                        ON (`glpi_networknames`.`items_id`=`glpi_networkports`.`id`)                            \n                     LEFT JOIN `glpi_ipaddresses`\n                        ON (`glpi_networknames`.`id`=`glpi_ipaddresses`.`items_id`) \n                     WHERE `glpi_networkports`.`items_id` = '" . $_POST['itemID'] . "' \n                     {$where} \n                     AND `glpi_networkports`.`itemtype` = '" . $item->getType() . "' \n                     ORDER BY `glpi_networkports`.`logical_number`";
         $result2 = $DB->query($query2);
         if ($DB->numrows($result2) > 0) {
             while ($data2 = $DB->fetch_array($result2)) {
                 if (!empty($data2["ip"]) && $data2["ip"] != '0.0.0.0') {
                     if (!empty($data2["name"])) {
                         $ip[$ipCount]['name'] = $data2["name"];
                     } else {
                         $ip[$ipCount]['name'] = '(' . __('Network port') . ' ' . $data2["id"] . ')';
                     }
                     $ip[$ipCount]['ip'] = $data2["ip"];
    }
}
if ($item->isEntityAssign()) {
    // allow opening ticket on recursive object (printer, software, ...)
    $where = getEntitiesRestrictRequest("WHERE", $table, '', $_SESSION['glpiactiveentities'], $item->maybeRecursive());
} else {
    $where = "WHERE 1";
}
if ($item->maybeDeleted()) {
    $where .= " AND `is_deleted` = '0' ";
}
if ($item->maybeTemplate()) {
    $where .= " AND `is_template` = '0' ";
}
if (strlen($_REQUEST['searchText']) > 0 && $_REQUEST['searchText'] != $CFG_GLPI["ajax_wildcard"]) {
    $search = Search::makeTextSearch($_REQUEST['searchText']);
    $where .= " AND (`name` " . $search . "\n                    OR `id` = '" . $_REQUEST['searchText'] . "'\n                    OR `serial` " . $search . "\n                    OR `otherserial` " . $search . ")";
}
//If software or plugins : filter to display only the objects that are allowed to be visible in Helpdesk
if (in_array($_REQUEST['itemtype'], $CFG_GLPI["helpdesk_visible_types"])) {
    $where .= " AND `is_helpdesk_visible` = '1' ";
}
if (isset($_REQUEST['current_item']) && $_REQUEST['current_item'] > 0) {
    $where .= " AND `id` != " . $_REQUEST['current_item'];
}
$NBMAX = $CFG_GLPI["dropdown_max"];
$LIMIT = "LIMIT 0,{$NBMAX}";
if ($_REQUEST['searchText'] == $CFG_GLPI["ajax_wildcard"]) {
    $LIMIT = "";
}
$query = "SELECT *\n          FROM {$table}\n          {$where}\n          ORDER BY `name`\n          {$LIMIT}";
    $where .= getEntitiesRestrictRequest("AND", "glpi_plugin_accounts_accounts", '', '', true);
}
if (isset($_POST['used'])) {
    $where .= " AND id NOT IN (0";
    if (is_array($_POST['used'])) {
        $used = $_POST['used'];
    } else {
        $used = Toolbox::decodeArrayFromInput($_POST['used']);
    }
    foreach ($used as $val) {
        $where .= ",{$val}";
    }
    $where .= ") ";
}
if ($_POST['searchText'] != $CFG_GLPI["ajax_wildcard"]) {
    $where .= " AND `glpi_plugin_accounts_accounts`.`name` " . Search::makeTextSearch($_POST['searchText']);
}
$NBMAX = $CFG_GLPI["dropdown_max"];
$LIMIT = "LIMIT 0,{$NBMAX}";
if ($_POST['searchText'] == $CFG_GLPI["ajax_wildcard"]) {
    $LIMIT = "";
}
$query = "SELECT *\nFROM `glpi_plugin_accounts_accounts`\n{$where}\nORDER BY `entities_id`, `name` {$LIMIT}";
$result = $DB->query($query);
echo "<select name=\"" . $_POST['myname'] . "\">";
echo "<option value=\"0\">" . Dropdown::EMPTY_VALUE . "</option>";
if ($DB->numrows($result)) {
    $prev = -1;
    while ($data = $DB->fetch_array($result)) {
        if ($data["entities_id"] != $prev) {
            if ($prev >= 0) {
Exemple #14
0
function plugin_resources_addWhere($link, $nott, $type, $ID, $val)
{
    $searchopt =& Search::getOptions($type);
    $table = $searchopt[$ID]["table"];
    $field = $searchopt[$ID]["field"];
    $SEARCH = Search::makeTextSearch($val, $nott);
    switch ($table . "." . $field) {
        case "glpi_plugin_resources_managers.name":
        case "glpi_plugin_resources_recipients_leaving.name":
        case "glpi_plugin_resources_recipients.name":
            $ADD = " OR `" . $table . "`.`firstname` LIKE '%" . $val . "%' OR `" . $table . "`.`realname` LIKE '%" . $val . "%' ";
            if ($nott && $val != "NULL") {
                $ADD = " OR `{$table}`.`{$field}` IS NULL";
            }
            return $link . " (`{$table}`.`{$field}` {$SEARCH} " . $ADD . " ) ";
            break;
    }
    return "";
}
Exemple #15
0
}
if (!defined('GLPI_ROOT')) {
    die("Can not acces directly to this file");
}
Session::checkLoginUser();
// Make a select box with preselected values
if (!isset($_POST["limit"])) {
    $_POST["limit"] = $_SESSION["glpidropdown_chars_limit"];
}
$NBMAX = $CFG_GLPI["dropdown_max"];
$LIMIT = "LIMIT 0,{$NBMAX}";
$sql = "SELECT `id`, `name`, `ranking`\n        FROM `glpi_rules`\n        WHERE `sub_type` = '" . $_POST["type"] . "'";
if ($_POST['searchText'] == $CFG_GLPI["ajax_wildcard"]) {
    $LIMIT = "";
} else {
    $sql .= " AND `name` " . Search::makeTextSearch($_POST['searchText']);
}
if (isset($_POST['entity_restrict']) && $_POST['entity_restrict'] != '') {
    $sql .= " AND `glpi_rules`.`entities_id` = '" . $_POST['entity_restrict'] . "'";
}
$sql .= " ORDER BY `ranking` ASC " . $LIMIT;
$result = $DB->query($sql);
echo "<select id='dropdown_" . $_POST["myname"] . $_POST["rand"] . "' name='" . $_POST['myname'] . "' size='1'>";
if (isset($_POST['searchText']) && $_POST['searchText'] != $CFG_GLPI["ajax_wildcard"] && $DB->numrows($result) == $NBMAX) {
    echo "<option value='0'>--" . __('Limited view') . "--</option>";
} else {
    echo "<option value='0'>" . Dropdown::EMPTY_VALUE . "</option>";
}
if ($DB->numrows($result)) {
    while ($data = $DB->fetch_assoc($result)) {
        $ID = $data['id'];
Exemple #16
0
    exit;
}
$item = new $_POST['itemtype']();
// Make a select box with preselected values
if (!isset($_POST["limit"])) {
    $_POST["limit"] = $CFG_GLPI["dropdown_chars_limit"];
}
$NBMAX = $CFG_GLPI["dropdown_max"];
$LIMIT = "LIMIT 0,{$NBMAX}";
if ($_POST['searchText'] == $CFG_GLPI["ajax_wildcard"]) {
    $LIMIT = "";
}
$where = "WHERE `id` <> '" . $_POST['value'] . "' ";
$field = "name";
if ($_POST['searchText'] != $CFG_GLPI["ajax_wildcard"]) {
    $where .= " AND `{$field}` " . Search::makeTextSearch($_POST['searchText']);
}
$query = "SELECT *\n          FROM `" . $_POST['table'] . "`\n          {$where}\n          ORDER BY `{$field}`\n          {$LIMIT}";
$result = $DB->query($query);
echo "<select id='dropdown_" . $_POST["myname"] . $_POST["rand"] . "' name=\"" . $_POST['myname'] . "\">";
if ($_POST['searchText'] != $CFG_GLPI["ajax_wildcard"] && $DB->numrows($result) == $NBMAX) {
    echo "<option value='0\\'>--" . __('Limited view') . "--</option>";
} else {
    echo "<option value='0'>" . Dropdown::EMPTY_VALUE . "</option>";
}
$number = $DB->numrows($result);
if ($number != 0) {
    echo "<option value=\"" . $_POST['itemtype'] . ";-1\">" . __('All types', 'archires') . "</option>";
}
$output = Dropdown::getDropdownName($_POST['table'], $_POST['value']);
if (!empty($output) && $output != "&nbsp;") {
    $where .= getEntitiesRestrictRequest("AND", "glpi_plugin_databases_databases", '', '', true);
}
if (isset($_POST['used'])) {
    $where .= " AND `id` NOT IN (0";
    if (is_array($_POST['used'])) {
        $used = $_POST['used'];
    } else {
        $used = Toolbox::decodeArrayFromInput($_POST['used']);
    }
    foreach ($used as $val) {
        $where .= ",{$val}";
    }
    $where .= ") ";
}
if ($_POST['searchText'] != $CFG_GLPI["ajax_wildcard"]) {
    $where .= " AND `glpi_plugin_databases_databases`.`name` " . Search::makeTextSearch($_POST['searchText']);
}
$NBMAX = $CFG_GLPI["dropdown_max"];
$LIMIT = "LIMIT 0,{$NBMAX}";
if ($_POST['searchText'] == $CFG_GLPI["ajax_wildcard"]) {
    $LIMIT = "";
}
$query = "SELECT * \n\t\tFROM `glpi_plugin_databases_databases` \n\t\t{$where} \n\t\tORDER BY `entities_id`, `name` {$LIMIT}";
$result = $DB->query($query);
echo "<select name=\"" . $_POST['myname'] . "\">";
echo "<option value=\"0\">" . Dropdown::EMPTY_VALUE . "</option>";
if ($DB->numrows($result)) {
    $prev = -1;
    while ($data = $DB->fetch_array($result)) {
        if ($data["entities_id"] != $prev) {
            if ($prev >= 0) {
Exemple #18
0
function plugin_projet_addWhere($link, $nott, $type, $ID, $val)
{
    $searchopt =& Search::getOptions($type);
    $table = $searchopt[$ID]["table"];
    $field = $searchopt[$ID]["field"];
    $SEARCH = Search::makeTextSearch($val, $nott);
    switch ($table . "." . $field) {
        case "glpi_plugin_projet_projets_projets.plugin_projet_projets_id_1":
            return $link . " ((`{$table}`.`plugin_projet_projets_id_2` = '{$val}')\n                            AND `glpi_plugin_projet_projets`.`id` <> '{$val}')";
            break;
        case "glpi_plugin_projet_tasks_tasks.plugin_projet_tasks_id_1":
            return $link . " ((`{$table}`.`plugin_projet_tasks_id_2` = '{$val}')\n                            AND `glpi_plugin_projet_tasks`.`id` <> '{$val}')";
            break;
    }
    return "";
}
Exemple #19
0
 /**
  * Return a collection of rows of the desired itemtype
  *
  * @param $itemtype     string    itemtype (class) of object
  * @param $params       array     with theses options :
  * - 'expand_dropdowns' (default: false): show dropdown's names instead of id. Optionnal
  * - 'get_hateoas'      (default: true): show relations of items in a links attribute. Optionnal
  * - 'only_id'          (default: false): keep only id in fields list. Optionnal
  * - 'range'            (default: 0-50): limit the list to start-end attributes
  * - 'sort'             (default: id): sort by the field.
  * - 'order'            (default: ASC): ASC(ending) or DESC(ending).
  * - 'searchText'       (default: NULL): array of filters to pass on the query (with key = field and value the search)
  * @param $totalcount   integer  output parameter who receive the total count of the query resulat.
  *                               As this function paginate results (with a mysql LIMIT),
  *                               we can have the full range. (default 0)
  *
  * @return     array collection of fields
  **/
 protected function getItems($itemtype, $params = array(), &$totalcount = 0)
 {
     global $DB;
     $this->initEndpoint();
     // default params
     $default = array('expand_dropdowns' => false, 'get_hateoas' => true, 'only_id' => false, 'range' => "0-" . $_SESSION['glpilist_limit'], 'sort' => "id", 'order' => "ASC", 'searchText' => NULL);
     $params = array_merge($default, $params);
     if (!$itemtype::canView()) {
         return $this->messageRightError();
     }
     $found = array();
     $item = new $itemtype();
     $item->getEmpty();
     $table = getTableForItemType($itemtype);
     // transform range parameter in start and limit variables
     if (isset($params['range']) > 0) {
         if (preg_match("/^[0-9]+-[0-9]+\$/", $params['range'])) {
             $range = explode("-", $params['range']);
             $params['start'] = $range[0];
             $params['list_limit'] = $range[1] - $range[0] + 1;
             $params['range'] = $range;
         } else {
             $this->returnError("range must be in format : [start-end] with integers");
         }
     } else {
         $params['range'] = array(0, $_SESSION['glpilist_limit']);
     }
     // check parameters
     if (isset($params['order']) && !in_array(strtoupper($params['order']), array('DESC', 'ASC'))) {
         $this->returnError("order must be DESC or ASC");
     }
     if (!isset($item->fields[$params['sort']])) {
         $this->returnError("sort param is not a field of {$table}");
     }
     //specific case for restriction
     $already_linked_table = array();
     $join = Search::addDefaultJoin($itemtype, $table, $already_linked_table);
     $where = Search::addDefaultWhere($itemtype);
     if ($where == '') {
         $where = "1=1 ";
     }
     // add filter for a parent itemtype
     if (isset($this->parameters['parent_itemtype']) && isset($this->parameters['parent_id'])) {
         // check parent itemtype
         if (!class_exists($this->parameters['parent_itemtype']) || !is_subclass_of($this->parameters['parent_itemtype'], 'CommonDBTM')) {
             $this->returnError(__("parent itemtype not found or not an instance of CommonDBTM"), 400, "ERROR_ITEMTYPE_NOT_FOUND_NOR_COMMONDBTM");
         }
         $fk_parent = getForeignKeyFieldForItemType($this->parameters['parent_itemtype']);
         $fk_child = getForeignKeyFieldForItemType($itemtype);
         // check parent rights
         $parent_item = new $this->parameters['parent_itemtype']();
         if (!$parent_item->getFromDB($this->parameters['parent_id'])) {
             return $this->messageNotfoundError();
         }
         if (!$parent_item->can($this->parameters['parent_id'], READ)) {
             return $this->messageRightError();
         }
         // filter with parents fields
         if (isset($item->fields[$fk_parent])) {
             $where .= " AND `{$table}`.`{$fk_parent}` = " . $this->parameters['parent_id'];
         } else {
             if (isset($item->fields['itemtype']) && isset($item->fields['items_id'])) {
                 $where .= " AND `{$table}`.`itemtype` = '" . $this->parameters['parent_itemtype'] . "'\n                       AND `{$table}`.`items_id` = " . $this->parameters['parent_id'];
             } else {
                 if (isset($parent_item->fields[$fk_child])) {
                     $parentTable = getTableForItemType($this->parameters['parent_itemtype']);
                     $join .= " LEFT JOIN `{$parentTable}` ON `{$parentTable}`.`{$fk_child}` = `{$table}`.`id` ";
                     $where .= " AND `{$parentTable}`.`id` = '" . $this->parameters['parent_id'] . "'";
                 } else {
                     if (isset($parent_item->fields['itemtype']) && isset($parent_item->fields['items_id'])) {
                         $parentTable = getTableForItemType($this->parameters['parent_itemtype']);
                         $join .= " LEFT JOIN `{$parentTable}` ON `itemtype`='{$itemtype}' AND `{$parentTable}`.`items_id` = `{$table}`.`id` ";
                         $where .= " AND `{$parentTable}`.`id` = '" . $this->parameters['parent_id'] . "'";
                     }
                 }
             }
         }
     }
     // filter by searchText parameter
     if (is_array($params['searchText'])) {
         if (array_keys($params['searchText']) == array('all')) {
             $labelfield = "name";
             if ($item instanceof CommonDevice) {
                 $labelfield = "designation";
             } else {
                 if ($item instanceof Item_Devices) {
                     $labelfield = "itemtype";
                 }
             }
             $search_value = $params['searchText']['all'];
             $params['searchText'][$labelfield] = $search_value;
             if (FieldExists($table, 'comment')) {
                 $params['searchText']['comment'] = $search_value;
             }
         }
         // make text search
         foreach ($params['searchText'] as $filter_field => $filter_value) {
             if (!empty($filter_value)) {
                 $search = Search::makeTextSearch($filter_value);
                 $where .= " AND (`{$table}`.`{$filter_field}` {$search}\n                               OR `{$table}`.`id` {$search})";
             }
         }
     }
     // filter with entity
     if ($item->isEntityAssign()) {
         $where .= " AND (" . getEntitiesRestrictRequest("", $itemtype::getTable(), '', $_SESSION['glpiactiveentities'], false, true);
         if ($item instanceof Bookmark) {
             $where .= " OR " . $itemtype::getTable() . ".entities_id = -1";
         }
         $where .= ")";
     }
     // build query
     $query = "SELECT SQL_CALC_FOUND_ROWS DISTINCT `{$table}`.id,  `{$table}`.*\n                FROM `{$table}`\n                {$join}\n                WHERE {$where}\n                ORDER BY " . $params['sort'] . " " . $params['order'] . "\n                LIMIT " . $params['start'] . ", " . $params['list_limit'];
     if ($result = $DB->query($query)) {
         while ($data = $DB->fetch_assoc($result)) {
             $found[] = $data;
         }
     }
     // get result full row counts
     $query_numtotalrow = "Select FOUND_ROWS()";
     $result_numtotalrow = $DB->query($query_numtotalrow);
     $data_numtotalrow = $DB->fetch_assoc($result_numtotalrow);
     $totalcount = $data_numtotalrow['FOUND_ROWS()'];
     if ($params['range'][0] > $totalcount) {
         $this->returnError("Provided range exceed total count of data: " . $totalcount, 400, "ERROR_RANGE_EXCEED_TOTAL");
     }
     foreach ($found as $key => &$fields) {
         // only keep id in field list
         if ($params['only_id']) {
             $fields = array('id' => $fields['id']);
         }
         // avioid disclosure of critical fields
         $item::unsetUndisclosedFields($fields);
         // expand dropdown (retrieve name of dropdowns) and get hateoas
         $fields = self::parseDropdowns($fields, $params);
         // get hateoas from children
         if ($params['get_hateoas']) {
             $hclasses = self::getHatoasClasses($itemtype);
             foreach ($hclasses as $hclass) {
                 $fields['links'][] = array('rel' => $hclass, 'href' => self::$api_url . "/{$itemtype}/" . $fields['id'] . "/{$hclass}/");
             }
         }
     }
     return array_values($found);
 }
$where = " WHERE (`glpi_plugin_appliances_appliances`.`plugin_appliances_appliancetypes_id`\n                  = '" . $_POST['type_appliances'] . "')\n                AND `glpi_plugin_appliances_appliances`.`is_deleted` = '0' ";
if (isset($_POST["entity_restrict"]) && $_POST["entity_restrict"] >= 0) {
    $where .= getEntitiesRestrictRequest("AND", "glpi_plugin_appliances_appliances", '', $_POST["entity_restrict"], true);
} else {
    $where .= getEntitiesRestrictRequest("AND", "glpi_plugin_appliances_appliances", '', '', true);
}
if (isset($_POST['used'])) {
    if (is_array($_POST['used'])) {
        $used = $_POST['used'];
    } else {
        $used = unserialize(stripslashes($_POST['used']));
    }
    $where .= " AND `id` NOT IN ('" . implode("','", $used) . "')";
}
if ($_POST['searchText'] != $CFG_GLPI["ajax_wildcard"]) {
    $where .= " AND `glpi_plugin_appliances_appliances`.`name` " . Search::makeTextSearch($_POST['searchText']);
}
$NBMAX = $CFG_GLPI["dropdown_max"];
$LIMIT = "LIMIT 0,{$NBMAX}";
if ($_POST['searchText'] == $CFG_GLPI["ajax_wildcard"]) {
    $LIMIT = "";
}
$query = "SELECT *\n          FROM `glpi_plugin_appliances_appliances` " . $where . "\n          ORDER BY `entities_id`, `name` " . $LIMIT;
$result = $DB->query($query);
echo "<select name='" . $_POST['myname'] . "'>";
echo "<option value='0'>" . Dropdown::EMPTY_VALUE . "</option>";
if ($DB->numrows($result)) {
    $prev = -1;
    while ($data = $DB->fetch_array($result)) {
        if ($data["entities_id"] != $prev) {
            if ($prev >= 0) {
}
// Make a select box
$table = getTableForItemType($_POST["itemtype"]);
if (!($item = getItemForItemtype($_POST['itemtype']))) {
    exit;
}
$datas = array();
$where = "";
if ($item->maybeDeleted()) {
    $where .= " AND `{$table}`.`is_deleted` = '0' ";
}
if ($item->maybeTemplate()) {
    $where .= " AND `{$table}`.`is_template` = '0' ";
}
if (isset($_POST['searchText']) && strlen($_POST['searchText']) > 0) {
    $where .= " AND (`{$table}`.`name` " . Search::makeTextSearch($_POST['searchText']) . "\n                    OR `{$table}`.`otherserial` " . Search::makeTextSearch($_POST['searchText']) . "\n                    OR `{$table}`.`serial` " . Search::makeTextSearch($_POST['searchText']) . " )";
}
$multi = $item->maybeRecursive();
if (isset($_POST["entity_restrict"]) && !($_POST["entity_restrict"] < 0)) {
    $where .= getEntitiesRestrictRequest(" AND ", $table, '', $_POST["entity_restrict"], $multi);
    if (is_array($_POST["entity_restrict"]) && count($_POST["entity_restrict"]) > 1) {
        $multi = true;
    }
} else {
    $where .= getEntitiesRestrictRequest(" AND ", $table, '', $_SESSION['glpiactiveentities'], $multi);
    if (count($_SESSION['glpiactiveentities']) > 1) {
        $multi = true;
    }
}
if (!isset($_POST['page'])) {
    $_POST['page'] = 1;
} else {
    $where .= getEntitiesRestrictRequest("AND", "glpi_plugin_connections_connections", '', '', true);
}
$used = array();
if (isset($_POST['used'])) {
    if (is_array($_POST['used'])) {
        $used = $_POST['used'];
    } else {
        $used = Toolbox::decodeArrayFromInput($_POST['used']);
    }
}
if (!empty($used)) {
    $where .= ' AND `id` NOT IN (' . implode(', ', $used) . ') ';
}
if ($_POST['searchText'] != $CFG_GLPI["ajax_wildcard"]) {
    $where .= " AND `glpi_plugin_connections_connections`.`name` " . Search::makeTextSearch($_POST['searchText']);
}
$NBMAX = $CFG_GLPI["dropdown_max"];
$LIMIT = "LIMIT 0,{$NBMAX}";
if ($_POST['searchText'] == $CFG_GLPI["ajax_wildcard"]) {
    $LIMIT = "";
}
$query = "SELECT *\n          FROM `glpi_plugin_connections_connections`\n          {$where}\n          ORDER BY `entities_id`, `name`\n          {$LIMIT}";
$result = $DB->query($query);
echo "<select name=\"" . $_POST['myname'] . "\">";
echo "<option value=\"0\">" . Dropdown::EMPTY_VALUE . "</option>";
if ($DB->numrows($result)) {
    $prev = -1;
    while ($data = $DB->fetch_array($result)) {
        if ($data["entities_id"] != $prev) {
            if ($prev >= 0) {
 /**
  * Build request for showList
  *
  * @since version 0.83
  *
  * @param $params array  (contains, knowbaseitemcategories_id, faq)
  * @param $type   string search type : browse / search (default search)
  *
  * @return String : SQL request
  **/
 static function getListRequest(array $params, $type = 'search')
 {
     global $DB;
     // Lists kb Items
     $where = "";
     $order = "";
     $score = "";
     $addselect = "";
     $join = self::addVisibilityJoins(true);
     switch ($type) {
         case 'myunpublished':
             break;
         case 'allmy':
             break;
         case 'allunpublished':
             break;
         default:
             // Build query
             if (Session::getLoginUserID() && $type != 'myunpublished') {
                 $where = self::addVisibilityRestrict();
             } else {
                 // Anonymous access
                 if (Session::isMultiEntitiesMode()) {
                     $where = " (`glpi_entities_knowbaseitems`.`entities_id` = '0'\n                              AND `glpi_entities_knowbaseitems`.`is_recursive` = '1')";
                 }
             }
             break;
     }
     if (empty($where)) {
         $where = '1 = 1';
     }
     if ($params['faq']) {
         // helpdesk
         $where .= " AND (`glpi_knowbaseitems`.`is_faq` = '1')";
     }
     // a search with $contains
     switch ($type) {
         case 'allmy':
             $where .= " AND `glpi_knowbaseitems`.`users_id` = '" . Session::getLoginUserID() . "'";
             break;
         case 'myunpublished':
             $where .= " AND `glpi_knowbaseitems`.`users_id` = '" . Session::getLoginUserID() . "'\n                        AND (`glpi_entities_knowbaseitems`.`entities_id` IS NULL\n                              AND `glpi_knowbaseitems_profiles`.`profiles_id` IS NULL\n                              AND `glpi_groups_knowbaseitems`.`groups_id` IS NULL\n                              AND `glpi_knowbaseitems_users`.`users_id` IS NULL)";
             break;
         case 'allunpublished':
             // Only published
             $where .= " AND (`glpi_entities_knowbaseitems`.`entities_id` IS NULL\n                              AND `glpi_knowbaseitems_profiles`.`profiles_id` IS NULL\n                              AND `glpi_groups_knowbaseitems`.`groups_id` IS NULL\n                              AND `glpi_knowbaseitems_users`.`users_id` IS NULL)";
             break;
         case 'search':
             if (strlen($params["contains"]) > 0) {
                 $search = Toolbox::unclean_cross_side_scripting_deep($params["contains"]);
                 $addscore = '';
                 if (KnowbaseItemTranslation::isKbTranslationActive()) {
                     $addscore = ",`glpi_knowbaseitemtranslations`.`name`,\n                                 `glpi_knowbaseitemtranslations`.`answer`";
                 }
                 $score = " ,MATCH(`glpi_knowbaseitems`.`name`, `glpi_knowbaseitems`.`answer` {$addscore})\n                           AGAINST('{$search}' IN BOOLEAN MODE) AS SCORE ";
                 $where_1 = $where . " AND MATCH(`glpi_knowbaseitems`.`name`,\n                                             `glpi_knowbaseitems`.`answer` {$addscore})\n                          AGAINST('{$search}' IN BOOLEAN MODE) ";
                 // Add visibility date
                 $where_1 .= " AND (`glpi_knowbaseitems`.`begin_date` IS NULL\n                                   OR `glpi_knowbaseitems`.`begin_date` < NOW())\n                             AND (`glpi_knowbaseitems`.`end_date` IS NULL\n                                  OR `glpi_knowbaseitems`.`end_date` > NOW()) ";
                 $order = "ORDER BY `SCORE` DESC";
                 // preliminar query to allow alternate search if no result with fulltext
                 $query_1 = "SELECT COUNT(`glpi_knowbaseitems`.`id`)\n                             FROM `glpi_knowbaseitems`\n                             {$join}\n                             WHERE {$where_1}";
                 $result_1 = $DB->query($query_1);
                 $numrows_1 = $DB->result($result_1, 0, 0);
                 if ($numrows_1 <= 0) {
                     // not result this fulltext try with alternate search
                     $search1 = array('/\\\\"/', "/\\+/", "/\\*/", "/~/", "/</", "/>/", "/\\(/", "/\\)/", "/\\-/");
                     $contains = preg_replace($search1, "", $params["contains"]);
                     $addwhere = '';
                     if (KnowbaseItemTranslation::isKbTranslationActive()) {
                         $addwhere = " OR `glpi_knowbaseitemtranslations`.`name` " . Search::makeTextSearch($contains) . "\n                                    OR `glpi_knowbaseitemtranslations`.`answer` " . Search::makeTextSearch($contains);
                     }
                     $where .= " AND (`glpi_knowbaseitems`.`name` " . Search::makeTextSearch($contains) . "\n                                 OR `glpi_knowbaseitems`.`answer` " . Search::makeTextSearch($contains) . "\n                                 {$addwhere})";
                 } else {
                     $where = $where_1;
                 }
             }
             break;
         case 'browse':
             $where .= " AND (`glpi_knowbaseitems`.`knowbaseitemcategories_id`\n                           = '" . $params["knowbaseitemcategories_id"] . "')";
             // Add visibility date
             $where .= " AND (`glpi_knowbaseitems`.`begin_date` IS NULL\n                             OR `glpi_knowbaseitems`.`begin_date` < NOW())\n                        AND (`glpi_knowbaseitems`.`end_date` IS NULL\n                             OR `glpi_knowbaseitems`.`end_date` > NOW()) ";
             $order = " ORDER BY `glpi_knowbaseitems`.`name` ASC";
             break;
     }
     if (KnowbaseItemTranslation::isKbTranslationActive()) {
         $join .= "LEFT JOIN `glpi_knowbaseitemtranslations`\n                     ON (`glpi_knowbaseitems`.`id` = `glpi_knowbaseitemtranslations`.`knowbaseitems_id`\n                         AND `glpi_knowbaseitemtranslations`.`language` = '" . $_SESSION['glpilanguage'] . "')";
         $addselect .= ", `glpi_knowbaseitemtranslations`.`name` AS transname,\n                          `glpi_knowbaseitemtranslations`.`answer` AS transanswer ";
     }
     $query = "SELECT DISTINCT `glpi_knowbaseitems`.*,\n                       `glpi_knowbaseitemcategories`.`completename` AS category\n                       {$addselect}\n                       {$score}\n                FROM `glpi_knowbaseitems`\n                {$join}\n                LEFT JOIN `glpi_knowbaseitemcategories`\n                     ON (`glpi_knowbaseitemcategories`.`id`\n                           = `glpi_knowbaseitems`.`knowbaseitemcategories_id`)\n                WHERE {$where}\n                {$order}";
     return $query;
 }
Exemple #24
0
function plugin_example_addHaving($link, $nott, $type, $ID, $val, $num)
{
    $searchopt =& Search::getOptions($type);
    $table = $searchopt[$ID]["table"];
    $field = $searchopt[$ID]["field"];
    $SEARCH = Search::makeTextSearch($val, $nott);
    // Example of standard Having clause but use it ONLY for specific Having
    // No need of the function if you do not have specific cases
    switch ($table . "." . $field) {
        case "glpi_plugin_example.serial":
            $ADD = "";
            if ($nott && $val != "NULL" || $val == '^$') {
                $ADD = " OR ITEM_{$num} IS NULL";
            }
            return " {$LINK} ( ITEM_" . $num . $SEARCH . " {$ADD} ) ";
    }
    return "";
}
*/
/** @file
* @brief
*/
if (strpos($_SERVER['PHP_SELF'], "dropdownSelectSoftware.php")) {
    $AJAX_INCLUDE = 1;
    include '../inc/includes.php';
    header("Content-Type: text/html; charset=UTF-8");
    Html::header_nocache();
}
Session::checkRight("software", "w");
// Make a select box
$rand = mt_rand();
$where = "";
if (strlen($_POST['searchText']) > 0 && $_POST['searchText'] != $CFG_GLPI["ajax_wildcard"]) {
    $where .= " AND `name` " . Search::makeTextSearch($_POST['searchText']) . " ";
}
$where .= getEntitiesRestrictRequest(' AND', 'glpi_softwares', 'entities_id', $_POST["entity_restrict"], true);
$query = "SELECT DISTINCT `glpi_softwares`.`id`,\n                          `glpi_softwares`.`name`\n          FROM `glpi_softwares`\n          WHERE `glpi_softwares`.`is_deleted` = '0'\n                AND `glpi_softwares`.`is_template` = '0'\n                {$where}\n          ORDER BY `glpi_softwares`.`name`";
$result = $DB->query($query);
echo "<select name='softwares_id' id='item_type{$rand}'>\n";
echo "<option value='0'>" . Dropdown::EMPTY_VALUE . "</option>\n";
if ($DB->numrows($result)) {
    while ($data = $DB->fetch_assoc($result)) {
        $softwares_id = $data["id"];
        $output = $data["name"];
        echo "<option value='{$softwares_id}' title=\"" . Html::cleanInputText($output) . "\">" . Toolbox::substr($output, 0, $_SESSION["glpidropdown_chars_limit"]) . "</option>";
    }
}
echo "</select>\n";
$paramsselsoft = array('softwares_id' => '__VALUE__', 'myname' => $_POST["myname"]);
Exemple #26
0
/**
 * @param $link
 * @param $nott
 * @param $type
 * @param $ID
 * @param $val
**/
function plugin_ocsinventoryng_addWhere($link, $nott, $type, $ID, $val)
{
    $searchopt =& Search::getOptions($type);
    $table = $searchopt[$ID]["table"];
    $field = $searchopt[$ID]["field"];
    $SEARCH = Search::makeTextSearch($val, $nott);
    switch ($table . "." . $field) {
        case "glpi_plugin_ocsinventoryng_details.action":
            return $link . " `{$table}`.`{$field}` = '{$val}' ";
    }
    return "";
}
Exemple #27
0
 /**
  * Execute the query to select box with all glpi users where select key = name
  *
  * Internaly used by showGroup_Users, dropdownUsers and ajax/getDropdownUsers.php
  *
  * @param $count                    true if execute an count(*) (true by default)
  * @param $right                    limit user who have specific right (default 'all')
  * @param $entity_restrict          Restrict to a defined entity (default -1)
  * @param $value                    default value (default 0)
  * @param $used             array   Already used items ID: not to display in dropdown
  * @param $search                   pattern (default '')
  * @param $start                    start LIMIT value (default 0)
  * @param $limit                    limit LIMIT value (default -1 no limit)
  *
  * @return mysql result set.
  **/
 static function getSqlSearchResult($count = true, $right = "all", $entity_restrict = -1, $value = 0, $used = array(), $search = '', $start = 0, $limit = -1)
 {
     global $DB, $CFG_GLPI;
     // No entity define : use active ones
     if ($entity_restrict < 0) {
         $entity_restrict = $_SESSION["glpiactiveentities"];
     }
     $joinprofile = false;
     $joinprofileright = false;
     switch ($right) {
         case "interface":
             $joinprofile = true;
             $where = " `glpi_profiles`.`interface` = 'central' " . getEntitiesRestrictRequest("AND", "glpi_profiles_users", '', $entity_restrict, 1);
             break;
         case "id":
             $where = " `glpi_users`.`id` = '" . Session::getLoginUserID() . "' ";
             break;
         case "delegate":
             $groups = self::getDelegateGroupsForUser($entity_restrict);
             $users = array();
             if (count($groups)) {
                 $query = "SELECT `glpi_users`.`id`\n                         FROM `glpi_groups_users`\n                         LEFT JOIN `glpi_users`\n                              ON (`glpi_users`.`id` = `glpi_groups_users`.`users_id`)\n                         WHERE `glpi_groups_users`.`groups_id` IN (" . implode(",", $groups) . ")\n                               AND `glpi_groups_users`.`users_id` <> '" . Session::getLoginUserID() . "'";
                 $result = $DB->query($query);
                 if ($DB->numrows($result)) {
                     while ($data = $DB->fetch_assoc($result)) {
                         $users[$data["id"]] = $data["id"];
                     }
                 }
             }
             // Add me to users list for central
             if ($_SESSION['glpiactiveprofile']['interface'] == 'central') {
                 $users[Session::getLoginUserID()] = Session::getLoginUserID();
             }
             if (count($users)) {
                 $where = " `glpi_users`.`id` IN (" . implode(",", $users) . ")";
             } else {
                 $where = '0';
             }
             break;
         case "groups":
             $groups = array();
             if (isset($_SESSION['glpigroups'])) {
                 $groups = $_SESSION['glpigroups'];
             }
             $users = array();
             if (count($groups)) {
                 $query = "SELECT `glpi_users`.`id`\n                         FROM `glpi_groups_users`\n                         LEFT JOIN `glpi_users`\n                              ON (`glpi_users`.`id` = `glpi_groups_users`.`users_id`)\n                         WHERE `glpi_groups_users`.`groups_id` IN (" . implode(",", $groups) . ")\n                               AND `glpi_groups_users`.`users_id` <> '" . Session::getLoginUserID() . "'";
                 $result = $DB->query($query);
                 if ($DB->numrows($result)) {
                     while ($data = $DB->fetch_assoc($result)) {
                         $users[$data["id"]] = $data["id"];
                     }
                 }
             }
             // Add me to users list for central
             if ($_SESSION['glpiactiveprofile']['interface'] == 'central') {
                 $users[Session::getLoginUserID()] = Session::getLoginUserID();
             }
             if (count($users)) {
                 $where = " `glpi_users`.`id` IN (" . implode(",", $users) . ")";
             } else {
                 $where = '0';
             }
             break;
         case "all":
             $where = " `glpi_users`.`id` > '0' " . getEntitiesRestrictRequest("AND", "glpi_profiles_users", '', $entity_restrict, 1);
             break;
         default:
             $joinprofile = true;
             $joinprofileright = true;
             if (!is_array($right)) {
                 $right = array($right);
             }
             $forcecentral = true;
             $where = array();
             foreach ($right as $r) {
                 switch ($r) {
                     case 'own_ticket':
                         $where[] = " (`glpi_profilerights`.`name` = 'ticket'\n                                  AND (`glpi_profilerights`.`rights` & " . Ticket::OWN . ") " . getEntitiesRestrictRequest("AND", "glpi_profiles_users", '', $entity_restrict, 1) . ") ";
                         break;
                     case 'create_ticket_validate':
                         $where[] = " (`glpi_profilerights`.`name` = 'ticketvalidation'\n                                  AND (`glpi_profilerights`.`rights` & " . TicketValidation::CREATEREQUEST . "\n                                       OR `glpi_profilerights`.`rights` & " . TicketValidation::CREATEDEMAND . ") " . getEntitiesRestrictRequest("AND", "glpi_profiles_users", '', $entity_restrict, 1) . ") ";
                         $forcecentral = false;
                         break;
                     case 'validate_request':
                         $where[] = " (`glpi_profilerights`.`name` = 'ticketvalidation'\n                                  AND (`glpi_profilerights`.`rights` & " . TicketValidation::VALIDATEREQUEST . ") " . getEntitiesRestrictRequest("AND", "glpi_profiles_users", '', $entity_restrict, 1) . ") ";
                         $forcecentral = false;
                         break;
                     case 'validate_incident':
                         $where[] = " (`glpi_profilerights`.`name` = 'ticketvalidation'\n                                  AND (`glpi_profilerights`.`rights` & " . TicketValidation::VALIDATEINCIDENT . ") " . getEntitiesRestrictRequest("AND", "glpi_profiles_users", '', $entity_restrict, 1) . ") ";
                         $forcecentral = false;
                         break;
                     case 'validate':
                         $where[] = " (`glpi_profilerights`.`name` = 'changevalidation'\n                                  AND (`glpi_profilerights`.`rights` & " . ChangeValidation::VALIDATE . ") " . getEntitiesRestrictRequest("AND", "glpi_profiles_users", '', $entity_restrict, 1) . ") ";
                         break;
                     case 'create_validate':
                         $where[] = " (`glpi_profilerights`.`name` = 'changevalidation'\n                                  AND (`glpi_profilerights`.`rights` & " . ChangeValidation::CREATE . ") " . getEntitiesRestrictRequest("AND", "glpi_profiles_users", '', $entity_restrict, 1) . ") ";
                         break;
                     case 'see_project':
                         $where[] = " (`glpi_profilerights`.`name` = 'project'\n                                  AND (`glpi_profilerights`.`rights` & " . Project::READMY . ") " . getEntitiesRestrictRequest("AND", "glpi_profiles_users", '', $entity_restrict, 1) . ") ";
                         break;
                     default:
                         // Check read or active for rights
                         $where[] = " (`glpi_profilerights`.`name` = '" . $r . "'\n                                  AND `glpi_profilerights`.`rights` & " . (READ | CREATE | UPDATE | DELETE | PURGE) . " " . getEntitiesRestrictRequest("AND", "glpi_profiles_users", '', $entity_restrict, 1) . ") ";
                 }
                 if (in_array($r, Profile::$helpdesk_rights)) {
                     $forcecentral = false;
                 }
             }
             $where = '(' . implode(' OR ', $where);
             if ($forcecentral) {
                 $where .= " AND `glpi_profiles`.`interface` = 'central' ";
             }
             $where .= ')';
     }
     $where .= " AND `glpi_users`.`is_deleted` = '0'\n                  AND `glpi_users`.`is_active` = '1'\n                  AND (`glpi_users`.`begin_date` IS NULL\n                       OR `glpi_users`.`begin_date` < NOW())\n                  AND (`glpi_users`.`end_date` IS NULL\n                       OR `glpi_users`.`end_date` > NOW())";
     if (is_numeric($value) && $value || count($used)) {
         $where .= " AND `glpi_users`.`id` NOT IN (";
         if (is_numeric($value)) {
             $first = false;
             $where .= $value;
         } else {
             $first = true;
         }
         foreach ($used as $val) {
             if ($first) {
                 $first = false;
             } else {
                 $where .= ",";
             }
             $where .= $val;
         }
         $where .= ")";
     }
     if ($count) {
         $query = "SELECT COUNT(DISTINCT `glpi_users`.`id` ) AS CPT\n                   FROM `glpi_users` ";
     } else {
         $query = "SELECT DISTINCT `glpi_users`.*\n                   FROM `glpi_users` ";
     }
     $query .= " LEFT JOIN `glpi_useremails`\n                     ON (`glpi_users`.`id` = `glpi_useremails`.`users_id`)\n                  LEFT JOIN `glpi_profiles_users`\n                     ON (`glpi_users`.`id` = `glpi_profiles_users`.`users_id`)";
     if ($joinprofile) {
         $query .= " LEFT JOIN `glpi_profiles`\n                        ON (`glpi_profiles`.`id` = `glpi_profiles_users`.`profiles_id`)";
         if ($joinprofileright) {
             $query .= " LEFT JOIN `glpi_profilerights`\n                           ON (`glpi_profiles`.`id` = `glpi_profilerights`.`profiles_id`)";
         }
     }
     if ($count) {
         $query .= " WHERE {$where} ";
     } else {
         if (strlen($search) > 0) {
             $where .= " AND (`glpi_users`.`name` " . Search::makeTextSearch($search) . "\n                             OR `glpi_users`.`realname` " . Search::makeTextSearch($search) . "\n                             OR `glpi_users`.`firstname` " . Search::makeTextSearch($search) . "\n                             OR `glpi_users`.`phone` " . Search::makeTextSearch($search) . "\n                             OR `glpi_useremails`.`email` " . Search::makeTextSearch($search) . "\n                             OR CONCAT(`glpi_users`.`realname`,' ',`glpi_users`.`firstname`) " . Search::makeTextSearch($search) . ")";
         }
         $query .= " WHERE {$where} ";
         if ($_SESSION["glpinames_format"] == self::FIRSTNAME_BEFORE) {
             $query .= " ORDER BY `glpi_users`.`firstname`,\n                               `glpi_users`.`realname`,\n                               `glpi_users`.`name` ";
         } else {
             $query .= " ORDER BY `glpi_users`.`realname`,\n                               `glpi_users`.`firstname`,\n                               `glpi_users`.`name` ";
         }
         if ($limit > 0) {
             $query .= " LIMIT {$start},{$limit}";
         }
     }
     return $DB->query($query);
 }
    $where .= getEntitiesRestrictRequest("AND", "glpi_plugin_routetables_routetables", '', '', false);
}
if (isset($_POST['used'])) {
    $where .= " AND `id` NOT IN (0";
    if (is_array($_POST['used'])) {
        $used = $_POST['used'];
    } else {
        $used = Toolbox::decodeArrayFromInput($_POST['used']);
    }
    foreach ($used as $val) {
        $where .= ",{$val}";
    }
    $where .= ") ";
}
if ($_POST['searchText'] != $CFG_GLPI["ajax_wildcard"]) {
    $where .= " AND `glpi_plugin_routetables_routetables`.`destination` " . Search::makeTextSearch($_POST['searchText']);
}
$NBMAX = $CFG_GLPI["dropdown_max"];
$LIMIT = "LIMIT 0,{$NBMAX}";
if ($_POST['searchText'] == $CFG_GLPI["ajax_wildcard"]) {
    $LIMIT = "";
}
$query = "SELECT * \n\t\tFROM `glpi_plugin_routetables_routetables` \n\t\t{$where} \n\t\tORDER BY `entities_id`, `name` {$LIMIT}";
$result = $DB->query($query);
echo "<select name=\"" . $_POST['myname'] . "\">";
echo "<option value=\"0\">" . Dropdown::EMPTY_VALUE . "</option>";
if ($DB->numrows($result)) {
    $prev = -1;
    while ($data = $DB->fetch_array($result)) {
        if ($data["entities_id"] != $prev) {
            if ($prev >= 0) {
Exemple #29
0
 /**
  * Execute the query to select box with all glpi users where select key = name
  *
  * Internaly used by showGroup_Users, dropdownUsers and ajax/dropdownUsers.php
  *
  * @param $count                    true if execute an count(*) (true by default)
  * @param $right                    limit user who have specific right (default 'all')
  * @param $entity_restrict          Restrict to a defined entity (default -1)
  * @param $value                    default value (default 0)
  * @param $used             array   Already used items ID: not to display in dropdown
  * @param $search                   pattern (default '')
  *
  * @return mysql result set.
  **/
 static function getSqlSearchResult($count = true, $right = "all", $entity_restrict = -1, $value = 0, $used = array(), $search = '')
 {
     global $DB, $CFG_GLPI;
     // No entity define : use active ones
     if ($entity_restrict < 0) {
         $entity_restrict = $_SESSION["glpiactiveentities"];
     }
     $joinprofile = false;
     switch ($right) {
         case "interface":
             $joinprofile = true;
             $where = " `glpi_profiles`.`interface` = 'central' " . getEntitiesRestrictRequest("AND", "glpi_profiles_users", '', $entity_restrict, 1);
             break;
         case "id":
             $where = " `glpi_users`.`id` = '" . Session::getLoginUserID() . "' ";
             break;
         case "delegate":
             $groups = self::getDelegateGroupsForUser($entity_restrict);
             $users = array();
             if (count($groups)) {
                 $query = "SELECT `glpi_users`.`id`\n                         FROM `glpi_groups_users`\n                         LEFT JOIN `glpi_users`\n                              ON (`glpi_users`.`id` = `glpi_groups_users`.`users_id`)\n                         WHERE `glpi_groups_users`.`groups_id` IN ('" . implode("','", $groups) . "')\n                               AND `glpi_groups_users`.`users_id` <> '" . Session::getLoginUserID() . "'";
                 $result = $DB->query($query);
                 if ($DB->numrows($result)) {
                     while ($data = $DB->fetch_assoc($result)) {
                         $users[$data["id"]] = $data["id"];
                     }
                 }
             }
             // Add me to users list for central
             if ($_SESSION['glpiactiveprofile']['interface'] == 'central') {
                 $users[Session::getLoginUserID()] = Session::getLoginUserID();
             }
             if (count($users)) {
                 $where = " `glpi_users`.`id` IN ('" . implode("','", $users) . "')";
             } else {
                 $where = '0';
             }
             break;
         case "all":
             $where = " `glpi_users`.`id` > '1' " . getEntitiesRestrictRequest("AND", "glpi_profiles_users", '', $entity_restrict, 1);
             break;
         default:
             $joinprofile = true;
             if (!is_array($right)) {
                 $right = array($right);
             }
             $forcecentral = true;
             $where = array();
             foreach ($right as $r) {
                 // Check read or active for rights
                 $where[] = " (`glpi_profiles`.`" . $r . "` IN ('1', 'r', 'w') " . getEntitiesRestrictRequest("AND", "glpi_profiles_users", '', $entity_restrict, 1) . ") ";
                 if (in_array($r, Profile::$helpdesk_rights)) {
                     $forcecentral = false;
                 }
             }
             $where = '(' . implode(' OR ', $where);
             if ($forcecentral) {
                 $where .= " AND `glpi_profiles`.`interface` = 'central' ";
             }
             $where .= ')';
     }
     $where .= " AND `glpi_users`.`is_deleted` = '0'\n                  AND `glpi_users`.`is_active` = '1' ";
     if (is_numeric($value) && $value || count($used)) {
         $where .= " AND `glpi_users`.`id` NOT IN (";
         if (is_numeric($value)) {
             $first = false;
             $where .= $value;
         } else {
             $first = true;
         }
         foreach ($used as $val) {
             if ($first) {
                 $first = false;
             } else {
                 $where .= ",";
             }
             $where .= $val;
         }
         $where .= ")";
     }
     if ($count) {
         $query = "SELECT COUNT(DISTINCT `glpi_users`.`id` ) AS CPT\n                   FROM `glpi_users` ";
     } else {
         $query = "SELECT DISTINCT `glpi_users`.*\n                   FROM `glpi_users` ";
     }
     $query .= " LEFT JOIN `glpi_useremails`\n                     ON (`glpi_users`.`id` = `glpi_useremails`.`users_id`)\n                  LEFT JOIN `glpi_profiles_users`\n                     ON (`glpi_users`.`id` = `glpi_profiles_users`.`users_id`)";
     if ($joinprofile) {
         $query .= " LEFT JOIN `glpi_profiles`\n                        ON (`glpi_profiles`.`id` = `glpi_profiles_users`.`profiles_id`) ";
     }
     if ($count) {
         $query .= " WHERE {$where} ";
     } else {
         if (strlen($search) > 0 && $search != $CFG_GLPI["ajax_wildcard"]) {
             $where .= " AND (`glpi_users`.`name` " . Search::makeTextSearch($search) . "\n                             OR `glpi_users`.`realname` " . Search::makeTextSearch($search) . "\n                             OR `glpi_users`.`firstname` " . Search::makeTextSearch($search) . "\n                             OR `glpi_users`.`phone` " . Search::makeTextSearch($search) . "\n                             OR `glpi_useremails`.`email` " . Search::makeTextSearch($search) . "\n                             OR CONCAT(`glpi_users`.`realname`,' ',`glpi_users`.`firstname`) " . Search::makeTextSearch($search) . ")";
         }
         $query .= " WHERE {$where} ";
         if ($_SESSION["glpinames_format"] == self::FIRSTNAME_BEFORE) {
             $query .= " ORDER BY `glpi_users`.`firstname`,\n                               `glpi_users`.`realname`,\n                               `glpi_users`.`name` ";
         } else {
             $query .= " ORDER BY `glpi_users`.`realname`,\n                               `glpi_users`.`firstname`,\n                               `glpi_users`.`name` ";
         }
         if ($search != $CFG_GLPI["ajax_wildcard"]) {
             $query .= " LIMIT 0," . $CFG_GLPI["dropdown_max"];
         }
     }
     return $DB->query($query);
 }
}
$where = " WHERE " . $field_isdel;
//echo $tabletype;
if (!class_exists($tabletype)) {
    $datatable = "";
} else {
    $objeto = new $tabletype();
    $datatable = $objeto->getTable();
}
if (isset($_POST["entity_restrict"]) && $_POST["entity_restrict"] >= 0) {
    $where .= getEntitiesRestrictRequest("AND", $datatable, '', $_POST["entity_restrict"], false);
} else {
    $where .= getEntitiesRestrictRequest("AND", $datatable, '', '', false);
}
if ($_POST['searchText'] != $CFG_GLPI["ajax_wildcard"]) {
    $where .= " AND {$datatable}.name " . Search::makeTextSearch($_POST['searchText']);
}
$NBMAX = $CFG_GLPI["dropdown_max"];
$LIMIT = "LIMIT 0,{$NBMAX}";
if ($_POST['searchText'] == $CFG_GLPI["ajax_wildcard"]) {
    $LIMIT = "";
}
$leftjoin = '';
if ($_POST['myname'] == 'childID') {
    // Insure that the device does not already have a parent
    $leftjoin = " LEFT JOIN glpi_plugin_relation_relations AS pc " . "ON {$datatable}.id = pc.items_id ";
}
//$query = "SELECT $datatable.id, name, entities_id FROM $datatable "."$where ORDER BY entities_id, name $LIMIT";
$query = "SELECT id, name, entities_id FROM glpi_computers";
//echo $query;
$result = $DB->query($query);