1<?php
2
3/*
4   ------------------------------------------------------------------------
5   FusionInventory
6   Copyright (C) 2010-2016 by the FusionInventory Development Team.
7
8   http://www.fusioninventory.org/   http://forge.fusioninventory.org/
9   ------------------------------------------------------------------------
10
11   LICENSE
12
13   This file is part of FusionInventory project.
14
15   FusionInventory is free software: you can redistribute it and/or modify
16   it under the terms of the GNU Affero General Public License as published by
17   the Free Software Foundation, either version 3 of the License, or
18   (at your option) any later version.
19
20   FusionInventory is distributed in the hope that it will be useful,
21   but WITHOUT ANY WARRANTY; without even the implied warranty of
22   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23   GNU Affero General Public License for more details.
24
25   You should have received a copy of the GNU Affero General Public License
26   along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
27
28   ------------------------------------------------------------------------
29
30   @package   FusionInventory
31   @author    David Durieux
32   @co-author
33   @copyright Copyright (c) 2010-2016 FusionInventory team
34   @license   AGPL License 3.0 or (at your option) any later version
35              http://www.gnu.org/licenses/agpl-3.0-standalone.html
36   @link      http://www.fusioninventory.org/
37   @link      http://forge.fusioninventory.org/projects/fusioninventory-for-glpi/
38   @since     2010
39
40   ------------------------------------------------------------------------
41 */
42
43if (!defined('GLPI_ROOT')) {
44   die("Sorry. You can't access directly to this file");
45}
46
47/// FusionInventory Rules class
48class PluginFusioninventoryInventoryRuleImport extends Rule {
49
50   const PATTERN_IS_EMPTY              = 30;
51   const PATTERN_ENTITY_RESTRICT       = 202;
52   const RULE_ACTION_LINK              = 1;
53   const RULE_ACTION_DENIED            = 2;
54
55   const LINK_RESULT_DENIED            = 0;
56   const LINK_RESULT_CREATE            = 1;
57   const LINK_RESULT_LINK              = 2;
58
59   var $restrict_matching = Rule::AND_MATCHING;
60
61
62   // From Rule
63   static public $right = 'rule_import';
64   public $can_sort = TRUE;
65
66
67
68   function getTitle() {
69
70      return __('Rules for import and link computers');
71
72   }
73
74
75   function maxActionsCount() {
76      // Unlimited
77      return 1;
78   }
79
80
81   function getCriterias() {
82
83      $criterias = array ();
84      $criterias['entities_id']['table']     = 'glpi_entities';
85      $criterias['entities_id']['field']     = 'entities_id';
86      $criterias['entities_id']['name']      = __('Assets to import', 'fusioninventory').' : '.
87                           __('Destination of equipment entity', 'fusioninventory');
88
89      $criterias['entities_id']['linkfield'] = 'entities_id';
90      $criterias['entities_id']['type']      = 'dropdown';
91      $criterias['entities_id']['allow_condition'] = array(Rule::PATTERN_IS,
92                                                           Rule::PATTERN_IS_NOT,
93                                                           Rule::PATTERN_CONTAIN,
94                                                           Rule::PATTERN_NOT_CONTAIN,
95                                                           Rule::PATTERN_BEGIN,
96                                                           Rule::PATTERN_END,
97                                                           Rule::REGEX_MATCH,
98                                                           Rule::REGEX_NOT_MATCH);
99
100      $criterias['states_id']['table']           = 'glpi_states';
101      $criterias['states_id']['field']           = 'name';
102      $criterias['states_id']['name']            =
103                     __('Search GLPI equipment with the status', 'fusioninventory');
104
105      $criterias['states_id']['linkfield']       = 'state';
106      $criterias['states_id']['type']            = 'dropdown';
107      //Means that this criterion can only be used in a global search query
108      $criterias['states_id']['is_global']       = TRUE;
109      $criterias['states_id']['allow_condition'] = array(Rule::PATTERN_IS, Rule::PATTERN_IS_NOT);
110
111      $criterias['model']['name']  = __('Assets to import', 'fusioninventory').' : '.__('Model');
112
113
114      $criterias['mac']['name']    = __('Assets to import', 'fusioninventory').' : '.__('MAC');
115
116
117      $criterias['ip']['name']     = __('Assets to import', 'fusioninventory').' : '.__('IP');
118
119
120      $criterias['serial']['name'] = __('Assets to import', 'fusioninventory').' : '.
121                                       __('Serial number');
122
123
124//      $criterias['hdserial']['name']        = __('Assets to import', 'fusioninventory').' : '.
125//                   __('Hard disk serial number');
126
127//
128//      $criterias['partitionserial']['name'] = __('Assets to import', 'fusioninventory').' : '.
129//       __('Partition serial number');
130
131
132      $criterias['uuid']['name']  = __('Assets to import', 'fusioninventory').' : '.__('UUID');
133
134
135      $criterias['mskey']['name'] = __('Assets to import', 'fusioninventory').' : '.
136                                       __('Serial of the operating system');
137
138
139      $criterias['name']['name']  = __('Assets to import', 'fusioninventory').' : '.__('Name');
140
141
142      $criterias['tag']['name']   = __('Assets to import', 'fusioninventory').' : '.
143                                       __('FusionInventory tag', 'fusioninventory');
144
145
146      $criterias['osname']['name'] = __('Assets to import', 'fusioninventory').' : '.
147                                       __('Operating system');
148
149
150      $criterias['itemtype']['name'] = __('Assets to import', 'fusioninventory').' : '.
151                                          __('Item type');
152
153      $criterias['itemtype']['type']        = 'dropdown_itemtype';
154      $criterias['itemtype']['is_global']       = FALSE;
155      $criterias['itemtype']['allow_condition'] = array(Rule::PATTERN_IS, Rule::PATTERN_IS_NOT);
156
157      $criterias['domains_id']['table']           = 'glpi_domains';
158      $criterias['domains_id']['field']           = 'name';
159      $criterias['domains_id']['name']            =
160                     __('Assets to import', 'fusioninventory').' : '.
161                     __('Domain');
162      $criterias['domains_id']['linkfield']       = 'domain';
163      $criterias['domains_id']['type']            = 'dropdown';
164      //Means that this criterion can only be used in a global search query
165      $criterias['domains_id']['is_global']       = TRUE;
166//      $criterias['domains_id']['allow_condition'] = array(Rule::PATTERN_IS, Rule::PATTERN_IS_NOT);
167
168
169      $criterias['entityrestrict']['name']      = __('Restrict search in defined entity', 'fusioninventory');
170      $criterias['entityrestrict']['allow_condition'] = array(PluginFusioninventoryInventoryRuleImport::PATTERN_ENTITY_RESTRICT);
171
172      $criterias['oscomment']['name']      = __('Operating system').'/'.__('Comments');
173      $criterias['oscomment']['allow_condition'] = array(Rule::PATTERN_IS,
174                                                           Rule::PATTERN_IS_NOT,
175                                                           Rule::PATTERN_CONTAIN,
176                                                           Rule::PATTERN_NOT_CONTAIN,
177                                                           Rule::PATTERN_BEGIN,
178                                                           Rule::PATTERN_END,
179                                                           Rule::REGEX_MATCH,
180                                                           Rule::REGEX_NOT_MATCH);
181
182      return $criterias;
183   }
184
185
186
187   function getActions() {
188
189      $actions = array();
190      $actions['_fusion']['name']        = __('FusionInventory link', 'fusioninventory');
191      $actions['_fusion']['type']        = 'fusion_type';
192
193      $actions['_ignore_import']['name'] = __('To be unaware of import (with log)', 'fusioninventory');
194      $actions['_ignore_import']['type'] = 'yesonly';
195
196      return $actions;
197   }
198
199
200
201   static function getRuleActionValues() {
202
203      return array(self::RULE_ACTION_LINK   => __('Link', 'fusioninventory'),
204                   self::RULE_ACTION_DENIED => __('Import denied (no log)', 'fusioninventory'));
205   }
206
207
208
209   /**
210    * Add more action values specific to this type of rule
211    *
212    * @param value the value for this action
213    *
214    * @return the label's value or ''
215   **/
216   function displayAdditionRuleActionValue($value) {
217
218      $values = self::getRuleActionValues();
219      if (isset($values[$value])) {
220         return $values[$value];
221      }
222      return '';
223   }
224
225
226
227   function manageSpecificCriteriaValues($criteria, $name, $value) {
228
229      switch ($criteria['type']) {
230         case "state" :
231            $link_array = array("0" => __('No'),
232
233                                "1" => __('Yes')." : ".__('equal', 'fusioninventory'),
234
235                                "2" => __('Yes')." : ".__('empty', 'fusioninventory'));
236
237
238            Dropdown::showFromArray($name, $link_array, array('value' => $value));
239      }
240      return FALSE;
241   }
242
243
244
245   /**
246    * Add more criteria specific to this type of rule
247   **/
248   static function addMoreCriteria($criterion='') {
249
250      return array(Rule::PATTERN_FIND     => __('is already present in GLPI'),
251                   self::PATTERN_IS_EMPTY => __('is empty in GLPI'),
252                   self::PATTERN_ENTITY_RESTRICT => __('Yes'));
253
254   }
255
256
257
258   function getAdditionalCriteriaDisplayPattern($ID, $condition, $pattern) {
259
260      if ($condition == self::PATTERN_IS_EMPTY) {
261          return __('Yes');
262      }
263      if ($condition == self::PATTERN_ENTITY_RESTRICT) {
264          return __('Yes');
265      }
266      if ($condition==self::PATTERN_IS || $condition==self::PATTERN_IS_NOT) {
267         $crit = $this->getCriteria($ID);
268
269         if (isset($crit['type'])) {
270            switch ($crit['type']) {
271
272               case "dropdown_itemtype":
273                  $array = $this->getTypes();
274                  return $array[$pattern];
275                  break;
276
277            }
278         }
279      }
280      return FALSE;
281   }
282
283
284
285   function displayAdditionalRuleCondition($condition, $criteria, $name, $value, $test=FALSE) {
286
287      if ($test) {
288         return FALSE;
289      }
290
291      switch ($condition) {
292
293         case self::PATTERN_ENTITY_RESTRICT:
294            return TRUE;
295            break;
296
297         case Rule::PATTERN_EXISTS:
298         case Rule::PATTERN_DOES_NOT_EXISTS:
299         case Rule::PATTERN_FIND:
300         case PluginFusioninventoryInventoryRuleImport::PATTERN_IS_EMPTY:
301            Dropdown::showYesNo($name, 1, 0);
302            return TRUE;
303
304      }
305      return FALSE;
306   }
307
308
309
310   function displayAdditionalRuleAction(array $action, $value='') {
311
312      switch ($action['type']) {
313
314         case 'fusion_type':
315            Dropdown::showFromArray('value', self::getRuleActionValues());
316            break;
317
318         default:
319            break;
320
321      }
322      return TRUE;
323   }
324
325
326
327   function getCriteriaByID($critname) {
328      $criteria = array();
329      foreach ($this->criterias as $criterion) {
330         if ($critname == $criterion->fields['criteria']) {
331            $criteria[] = $criterion;
332         }
333      }
334      return $criteria;
335   }
336
337
338
339   function findWithGlobalCriteria($input) {
340      global $DB, $CFG_GLPI;
341
342      PluginFusioninventoryToolbox::logIfExtradebug(
343         "pluginFusioninventory-rules",
344         $input
345      );
346
347      $complex_criterias = array();
348      $sql_where         = '';
349      $sql_from          = '';
350      $sql_where_computer= '';
351      $sql_where_domain  = '';
352      $sql_where_model   = '';
353      $sql_from_computer = '';
354      $sql_from_domain   = '';
355      $sql_from_model    = '';
356      $continue          = TRUE;
357      $entityRestrict    = FALSE;
358      $global_criteria   = array('model',
359                                 'mac',
360                                 'ip',
361                                 'serial',
362                                 'hdserial',
363                                 'partitionserial',
364                                 'uuid',
365                                 'mskey',
366                                 'name',
367                                 'itemtype',
368                                 'domains_id',
369                                 'entityrestrict',
370                                 'oscomment');
371      $nb_crit_find = 0;
372      foreach ($global_criteria as $criterion) {
373         $criteria = $this->getCriteriaByID($criterion);
374         if (!empty($criteria)) {
375            foreach ($criteria as $crit) {
376               if (!isset($input[$criterion]) || $input[$criterion] == '') {
377                  $definition_criteria = $this->getCriteria($crit->fields['criteria']);
378                  if (isset($definition_criteria['is_global'])
379                          && $definition_criteria['is_global']) {
380                     $continue = FALSE;
381                  }
382               } else if ($crit->fields["condition"] == Rule::PATTERN_FIND) {
383                  $complex_criterias[] = $crit;
384                  $nb_crit_find++;
385               } else if ($crit->fields["condition"] == Rule::PATTERN_EXISTS) {
386                  if (!isset($input[$crit->fields['criteria']])
387                          OR empty($input[$crit->fields['criteria']])) {
388                     return FALSE;
389                  }
390               } else if($crit->fields["criteria"] == 'itemtype') {
391                  $complex_criterias[] = $crit;
392               } else if ($crit->fields["criteria"] == 'entityrestrict') {
393                  $entityRestrict = TRUE;
394               }
395            }
396         }
397      }
398
399      foreach ($this->getCriteriaByID('states_id') as $crit) {
400         $complex_criterias[] = $crit;
401      }
402
403      //If a value is missing, then there's a problem !
404      if (!$continue) {
405         return FALSE;
406      }
407
408      //No complex criteria
409      if ((empty($complex_criterias)) OR ($nb_crit_find == 0)) {
410         return TRUE;
411      }
412
413      //Build the request to check if the machine exists in GLPI
414      $where_entity = "";
415      if (isset($input['entities_id'])) {
416         if (is_array($input['entities_id'])) {
417            $where_entity .= implode($input['entities_id'], ', ');
418         } else {
419            $where_entity .= $input['entities_id'];
420         }
421      }
422
423      // Get all equipment type
424      $itemtype_global = 0;
425      foreach ($complex_criterias as $criteria) {
426         if ($criteria->fields['criteria'] == "itemtype") {
427            $itemtype_global++;
428         }
429      }
430
431      $itemtypeselected = array();
432      if (isset($input['itemtype'])
433              AND (is_array($input['itemtype']))
434              AND ($itemtype_global != "0")) {
435
436         $itemtypeselected = $input['itemtype'];
437      } else if (isset($input['itemtype'])
438              AND (!empty($input['itemtype']))
439              AND ($itemtype_global > 0)) {
440
441         $itemtypeselected[] = $input['itemtype'];
442      } else {
443         foreach($CFG_GLPI["state_types"] as $itemtype) {
444            if (class_exists($itemtype)) {
445               $itemtypeselected[] = $itemtype;
446            }
447         }
448         $itemtypeselected[] = "PluginFusioninventoryUnmanaged";
449      }
450
451      $sql_where = " `[typetable]`.`is_template` = '0' ";
452      $sql_from = "`[typetable]`";
453      $is_ip = FALSE;
454      $is_mac = FALSE;
455      foreach ($complex_criterias as $criteria) {
456         if ($criteria->fields['criteria'] == 'ip') {
457            $is_ip = TRUE;
458         } else if ($criteria->fields['criteria'] == 'mac') {
459            $is_mac = TRUE;
460         }
461      }
462      if ($is_ip) {
463         $sql_from .= " LEFT JOIN `glpi_networkports`
464                           ON (`[typetable]`.`id` = `glpi_networkports`.`items_id`
465                               AND `glpi_networkports`.`itemtype` = '[typename]')
466                        LEFT JOIN `glpi_networknames`
467                             ON `glpi_networknames`.`items_id`=`glpi_networkports`.`id`
468                                AND `glpi_networknames`.`itemtype`='NetworkPort'
469                        LEFT JOIN `glpi_ipaddresses`
470                             ON `glpi_ipaddresses`.`items_id`=`glpi_networknames`.`id`
471                                AND `glpi_ipaddresses`.`itemtype`='NetworkName'";
472      } else if ($is_mac) {
473         $sql_from .= " LEFT JOIN `glpi_networkports`
474                           ON (`[typetable]`.`id` = `glpi_networkports`.`items_id`
475                               AND `glpi_networkports`.`itemtype` = '[typename]')";
476      }
477
478      foreach ($complex_criterias as $criteria) {
479         switch ($criteria->fields['criteria']) {
480
481            case 'model':
482               $sql_from_model = " LEFT JOIN `glpi_[typenamefortable]models`
483                                 ON (`glpi_[typenamefortable]models`.`id` = ".
484                                     "`[typetable]`.`[typenamefortable]models_id`) ";
485               $sql_where_model = " AND `[typetable]`.`[typenamefortable]models_id` = '".
486                                    $input["model"]."'";
487               break;
488
489            case 'mac':
490               $sql_where_temp = " AND `glpi_networkports`.`mac` IN ('";
491               if (is_array($input['mac'])) {
492                  $sql_where_temp .= implode("', '", $input['mac']);
493               } else {
494                  $sql_where_temp .= $input['mac'];
495               }
496               $sql_where_temp .= "')";
497
498               $sql_where .= $sql_where_temp;
499               break;
500
501            case 'ip':
502               $sql_where .= " AND `glpi_ipaddresses`.`name` IN ('";
503               if (is_array($input['ip'])) {
504                  $sql_where .= implode("', '", $input['ip']);
505               } else {
506                  $sql_where .= $input['ip'];
507               }
508               $sql_where .= "')";
509               break;
510
511            case 'serial':
512               if (isset($input['itemtype'])
513                       AND $input['itemtype'] == 'Computer'
514                       AND isset($_SESSION["plugin_fusioninventory_manufacturerHP"])
515                       AND preg_match("/^[sS]/", $input['serial'])) {
516
517                  $serial2 = preg_replace("/^[sS]/", "", $input['serial']);
518                  $sql_where_temp = " AND (`[typetable]`.`serial`='".$input["serial"]."'
519                     OR `[typetable]`.`serial`='".$serial2."')";
520                  $_SESSION["plugin_fusioninventory_serialHP"] = $serial2;
521
522               } else {
523                  $sql_where_temp = " AND `[typetable]`.`serial`='".$input["serial"]."'";
524               }
525
526               $sql_where .= $sql_where_temp;
527               break;
528
529            case 'name':
530               if ($criteria->fields['condition'] == self::PATTERN_IS_EMPTY) {
531                  $sql_where_temp = " AND (`[typetable]`.`name`=''
532                                       OR `[typetable]`.`name` IS NULL) ";
533               } else {
534                  $sql_where_temp = " AND (`[typetable]`.`name`='".$input['name']."') ";
535               }
536               $sql_where .= $sql_where_temp;
537               break;
538
539            case 'hdserial':
540
541               break;
542
543            case 'partitionserial':
544
545               break;
546
547            case 'mskey':
548               $sql_where_computer  .= " AND `os_license_number`='".$input['mskey']."'";
549               break;
550
551            case 'states_id':
552               $condition = "";
553               if ($criteria->fields['condition'] == Rule::PATTERN_IS) {
554                  $condition = " IN ";
555               } else {
556                  $condition = " NOT IN ";
557               }
558               $sql_where .= " AND `[typetable]`.`states_id`
559                                 $condition ('".$criteria->fields['pattern']."')";
560               break;
561
562            case 'uuid':
563               $sql_where_computer .= ' AND `uuid`="'.$input['uuid'].'"';
564               break;
565
566            case 'domains_id':
567               $sql_from_domain .= " LEFT JOIN `glpi_domains`
568                                 ON `glpi_domains`.`id` = ".
569                                     "`[typetable]`.`domains_id` ";
570               $sql_where_domain .= " AND `glpi_domains`.`name` = '".
571                                    $input["domains_id"]."'";
572               break;
573         }
574      }
575
576      // Suivant le / les types, on cherche dans un ou plusieurs / tous les types
577      $found = 0;
578      PluginFusioninventoryToolbox::logIfExtradebug(
579         "pluginFusioninventory-rules",
580         "===============\n"
581      );
582
583      foreach ($itemtypeselected as $itemtype) {
584         $sql_from_temp = "";
585         $sql_where_temp = "";
586         $sql_from_temp = $sql_from;
587         $sql_where_temp = $sql_where;
588         if ($itemtype == "Computer") {
589            $sql_from_temp .= $sql_from_computer;
590            $sql_where_temp .= $sql_where_computer;
591            $sql_from_temp .= $sql_from_domain;
592            $sql_where_temp .= $sql_where_domain;
593         } else if ($itemtype == 'NetworkEquipment') {
594            $sql_from_temp .= $sql_from_domain;
595            $sql_where_temp .= $sql_where_domain;
596         } else if ($itemtype == 'Printer') {
597            $sql_from_temp .= $sql_from_domain;
598            $sql_where_temp .= $sql_where_domain;
599         } else if ($itemtype == 'PluginFusioninventoryUnmanaged') {
600            $sql_from_temp .= $sql_from_domain;
601            $sql_where_temp .= $sql_where_domain;
602         }
603
604         if ($itemtype != 'PluginFusioninventoryUnmanaged') {
605            $sql_from_temp .= $sql_from_model;
606            $sql_where_temp .= $sql_where_model;
607         }
608
609         if ($entityRestrict) {
610            if (isset($_SESSION['plugin_fusioninventory_entityrestrict'])) {
611               $sql_where_temp .= " AND `[typetable]`.`entities_id`='".
612                                       $_SESSION['plugin_fusioninventory_entityrestrict']."'";
613            } else {
614               $sql_where_temp .= " AND `[typetable]`.`entities_id`='0'";
615            }
616         }
617
618         $item = new $itemtype();
619         $sql_glpi = "SELECT `[typetable]`.`id`
620                      FROM $sql_from_temp
621                      WHERE $sql_where_temp
622                      GROUP BY `[typetable]`.`id`
623                      ORDER BY `[typetable]`.`is_deleted` ASC
624                      LIMIT 1";
625         if (strstr($sql_glpi, "`[typetable]`.`is_template` = '0'  AND")) {
626
627            if ($itemtype == "PluginFusioninventoryUnmanaged") {
628               $sql_glpi = str_replace("`[typetable]`.`is_template` = '0'  AND", "", $sql_glpi);
629            }
630            $sql_glpi = str_replace("[typetable]", $item->getTable(), $sql_glpi);
631            $sql_glpi = str_replace("[typename]", $itemtype, $sql_glpi);
632               $sql_glpi = str_replace("[typenamefortable]", strtolower($itemtype), $sql_glpi);
633
634            PluginFusioninventoryToolbox::logIfExtradebug(
635               "pluginFusioninventory-rules",
636               $sql_glpi."\n"
637            );
638            $result_glpi = $DB->query($sql_glpi);
639
640            if ($DB->numrows($result_glpi) > 0) {
641               while ($data=$DB->fetch_array($result_glpi)) {
642                  $found = 1;
643                  $this->criterias_results['found_equipment'][$itemtype][] = $data['id'];
644               }
645            }
646         }
647      }
648      if ($found == "1") {
649         return TRUE;
650      }
651      return FALSE;
652   }
653
654
655
656   /**
657    * Execute the actions as defined in the rule
658    *
659    * @param $output the fields to manipulate
660    * @param $params parameters
661    *
662    * @return the $output array modified
663   **/
664   function executeActions($output, $params) {
665      if (isset($params['class'])) {
666         $class = $params['class'];
667      } else if (isset($_SESSION['plugin_fusioninventory_classrulepassed'])) {
668         $classname = $_SESSION['plugin_fusioninventory_classrulepassed'];
669         $class = new $classname();
670      }
671
672      $pfRulematchedlog = new PluginFusioninventoryRulematchedlog();
673      $inputrulelog = array();
674      $inputrulelog['date'] = date('Y-m-d H:i:s');
675      $inputrulelog['rules_id'] = $this->fields['id'];
676      if (!isset($params['return'])) {
677         if (isset($_SESSION['plugin_fusioninventory_classrulepassed'])) {
678            $inputrulelog['method'] = $class->getMethod();
679         }
680         if (isset($_SESSION['plugin_fusioninventory_agents_id'])) {
681            $inputrulelog['plugin_fusioninventory_agents_id'] =
682                           $_SESSION['plugin_fusioninventory_agents_id'];
683         }
684      }
685      PluginFusioninventoryToolbox::logIfExtradebug(
686         "pluginFusioninventory-rules",
687         "execute action\n"
688      );
689
690      if (count($this->actions)) {
691         foreach ($this->actions as $action) {
692            if ($action->fields['field'] == '_fusion') {
693               PluginFusioninventoryToolbox::logIfExtradebug(
694                  "pluginFusioninventory-rules",
695                  "value".$action->fields["value"]."\n"
696               );
697
698               if ($action->fields["value"] == self::RULE_ACTION_LINK) {
699                  if (isset($this->criterias_results['found_equipment'])) {
700                     foreach ($this->criterias_results['found_equipment'] as $itemtype=>$datas) {
701                        $items_id = current($datas);
702                        $output['found_equipment'] = array($items_id, $itemtype);
703                        if (isset($_SESSION['plugin_fusioninventory_classrulepassed'])) {
704                           if (!isset($params['return'])) {
705                              $inputrulelog['items_id'] = $items_id;
706                              $inputrulelog['itemtype'] = $itemtype;
707                              $pfRulematchedlog->add($inputrulelog);
708                              $pfRulematchedlog->cleanOlddata($items_id, $itemtype);
709                              $class->rulepassed($items_id, $itemtype);
710                           }
711                           return $output;
712                        } else {
713                           $_SESSION['plugin_fusioninventory_rules_id'] = $this->fields['id'];
714                           $output['action'] = self::LINK_RESULT_LINK;
715                           return $output;
716                        }
717                     }
718                  } else {
719                     // Import into new equipment
720                     $itemtype_found = 0;
721                     if (count($this->criterias)) {
722                        foreach ($this->criterias as $criteria){
723                           if ($criteria->fields['criteria'] == 'itemtype') {
724                              $itemtype = $criteria->fields['pattern'];
725                              if (isset($_SESSION['plugin_fusioninventory_classrulepassed'])) {
726                                 if (!isset($params['return'])) {
727                                    $_SESSION['plugin_fusioninventory_rules_id'] =
728                                                   $this->fields['id'];
729                                    $class->rulepassed("0", $itemtype);
730                                 }
731                                 $output['found_equipment'] = array(0, $itemtype);
732                                 return $output;
733                              } else {
734                                 $_SESSION['plugin_fusioninventory_rules_id'] =
735                                         $this->fields['id'];
736                                 $output['action'] = self::LINK_RESULT_CREATE;
737                                 return $output;
738                              }
739                              $itemtype_found = 1;
740                           }
741                        }
742                     }
743                     if ($itemtype_found == "0") {
744                        if (isset($_SESSION['plugin_fusioninventory_classrulepassed'])) {
745                           if (!isset($params['return'])) {
746                              $_SESSION['plugin_fusioninventory_rules_id'] = $this->fields['id'];
747                              $class->rulepassed("0", "PluginFusioninventoryUnmanaged");
748                           }
749                           $output['found_equipment'] = array(0, "PluginFusioninventoryUnmanaged");
750                           return $output;
751                        } else {
752                           $_SESSION['plugin_fusioninventory_rules_id'] = $this->fields['id'];
753                           $output['action'] = self::LINK_RESULT_CREATE;
754                           return $output;
755                        }
756                     }
757                  }
758               } else if ($action->fields["value"] == self::RULE_ACTION_DENIED) {
759                  $_SESSION['plugin_fusioninventory_rules_id'] = $this->fields['id'];
760                  $output['action'] = self::LINK_RESULT_DENIED;
761                  return $output;
762               }
763            } else if ($action->fields['field'] == '_ignore_import') {
764               PluginFusioninventoryToolbox::logIfExtradebug(
765                  "pluginFusioninventory-rules",
766                  "value".$action->fields["value"]."\n"
767               );
768               $_SESSION['plugin_fusioninventory_rules_id'] = $this->fields['id'];
769               $output['action'] = self::LINK_RESULT_DENIED;
770               return $output;
771            } else {
772               // no import
773               $itemtype_found = 0;
774               if (count($this->criterias)) {
775                  foreach ($this->criterias as $criteria){
776                     if ($criteria->fields['criteria'] == 'itemtype') {
777                        $itemtype = $criteria->fields['pattern'];
778                        if (isset($_SESSION['plugin_fusioninventory_classrulepassed'])) {
779                           if (!isset($params['return'])) {
780                              $_SESSION['plugin_fusioninventory_rules_id'] = $this->fields['id'];
781                              $class->rulepassed("0", $itemtype);
782                           }
783                           $output['found_equipment'] = array(0, $itemtype);
784                           return $output;
785                        } else {
786                           $_SESSION['plugin_fusioninventory_rules_id'] = $this->fields['id'];
787                           $output['action'] = self::LINK_RESULT_CREATE;
788                           return $output;
789                        }
790                        $itemtype_found = 1;
791                     }
792                  }
793               }
794               if ($itemtype_found == "0") {
795                  if (isset($_SESSION['plugin_fusioninventory_classrulepassed'])) {
796                     if (!isset($params['return'])) {
797                        $_SESSION['plugin_fusioninventory_rules_id'] = $this->fields['id'];
798                        $class->rulepassed("0", "PluginFusioninventoryUnmanaged");
799                     }
800                     $output['found_equipment'] = array(0, 'PluginFusioninventoryUnmanaged');
801                     return $output;
802                  } else {
803                     $_SESSION['plugin_fusioninventory_rules_id'] = $this->fields['id'];
804                     $output['action'] = self::LINK_RESULT_CREATE;
805                     return $output;
806                  }
807               }
808            }
809         }
810      }
811      return $output;
812   }
813
814
815
816   function displayCriteriaSelectPattern($name, $ID, $condition, $value="", $test=FALSE) {
817
818      $crit    = $this->getCriteria($ID);
819      $display = FALSE;
820      $tested  = FALSE;
821
822      foreach ($this->criterias as $criteria) {
823         if ($criteria->fields['criteria'] == $name) {
824
825            if ($criteria->fields['condition'] == Rule::PATTERN_CONTAIN
826             || $criteria->fields['condition'] == Rule::PATTERN_NOT_CONTAIN
827             || $criteria->fields['condition'] == Rule::PATTERN_BEGIN
828             || $criteria->fields['condition'] == Rule::PATTERN_END
829             || $criteria->fields['condition'] == Rule::REGEX_MATCH
830             || $criteria->fields['condition'] == Rule::REGEX_NOT_MATCH) {
831
832               $rc = new $this->rulecriteriaclass();
833               Html::autocompletionTextField($rc, "pattern", array('name'  => $name,
834                                                       'value' => $value,
835                                                       'size'  => 70));
836               return;
837            }
838
839            if (($criteria->fields['condition'] == Rule::PATTERN_IS
840             || $criteria->fields['condition'] == Rule::PATTERN_IS_NOT)
841                    AND ($name != "itemtype" AND $name != 'states_id')) {
842
843               $rc = new $this->rulecriteriaclass();
844               Html::autocompletionTextField($rc, "pattern", array('name'  => $name,
845                                                       'value' => $value,
846                                                       'size'  => 70));
847               return;
848
849            }
850         }
851      }
852
853      if (isset($crit['type'])
854                 && ($test
855                     ||$condition == Rule::PATTERN_IS
856                     || $condition == Rule::PATTERN_IS_NOT)) {
857
858         switch ($crit['type']) {
859
860            case "yesonly":
861               Dropdown::showYesNo($name, $value, 0);
862               $display = TRUE;
863               break;
864
865            case "yesno":
866               Dropdown::showYesNo($name, $value);
867               $display = TRUE;
868               break;
869
870            case "dropdown":
871               Dropdown::show(getItemTypeForTable($crit['table']), array('name'  => $name,
872                                                                         'value' => $value));
873               $display = TRUE;
874               break;
875
876            case "dropdown_users":
877               User::dropdown(array('value'  => $value,
878                                    'name'   => $name,
879                                    'right'  => 'all'));
880               $display = TRUE;
881               break;
882
883            case "dropdown_itemtype":
884               $types = $this->getTypes();
885               ksort($types);
886               Dropdown::showItemTypes($name, array_keys($types),
887                                          array('value' => $value));
888               $display = TRUE;
889               break;
890
891         }
892         $tested = TRUE;
893      }
894      //Not a standard condition
895      if (!$tested) {
896        $display = $this->displayAdditionalRuleCondition($condition, $crit, $name, $value);
897      }
898
899      if (!$display) {
900         $rc = new $this->rulecriteriaclass();
901         Html::autocompletionTextField($rc, "pattern", array('name'  => $name,
902                                                       'value' => $value,
903                                                       'size'  => 70));
904      }
905   }
906
907
908
909   function getTypes() {
910      global $CFG_GLPI;
911
912      $types = array();
913      foreach($CFG_GLPI["state_types"] as $itemtype) {
914         if (class_exists($itemtype)) {
915            $item = new $itemtype();
916            $types[$itemtype] = $item->getTypeName();
917         }
918      }
919      $types["PluginFusioninventoryUnmanaged"] =
920                     PluginFusioninventoryUnmanaged::getTypeName();
921      $types[""] = __('No itemtype defined', 'fusioninventory');
922      return $types;
923   }
924
925
926
927   /**
928   * Function used to display type specific criterias during rule's preview
929   *
930   * @param $fields fields values
931   **/
932   function showSpecificCriteriasForPreview($fields) {
933
934      $entity_as_criteria = FALSE;
935      foreach ($this->criterias as $criteria) {
936         if ($criteria->fields['criteria'] == 'entities_id') {
937            $entity_as_criteria = TRUE;
938            break;
939         }
940      }
941      if (!$entity_as_criteria) {
942         echo "<input type='hidden' name='entities_id' value='".$_SESSION["glpiactive_entity"]."'>";
943      }
944   }
945
946
947
948   function preProcessPreviewResults($output) {
949
950      //If ticket is assign to an object, display this information first
951      if (isset($output["action"])) {
952         echo "<tr class='tab_bg_2'>";
953         echo "<td>".__('Action type')."</td>";
954         echo "<td>";
955
956         switch ($output["action"]) {
957
958            case self::LINK_RESULT_LINK:
959               echo __('Link');
960
961               break;
962
963            case self::LINK_RESULT_CREATE:
964               echo __('Device created', 'fusioninventory');
965
966               break;
967
968            case self::LINK_RESULT_DENIED:
969               echo __('Import denied', 'fusioninventory');
970
971               break;
972
973         }
974
975         echo "</td>";
976         echo "</tr>";
977         if ($output["action"] != self::LINK_RESULT_DENIED
978             && isset($output["found_equipment"])) {
979            echo "<tr class='tab_bg_2'>";
980            $className = $output["found_equipment"][1];
981            $class = new $className;
982            if ($class->getFromDB($output["found_equipment"][0])) {
983               echo "<td>".__('Link')."</td>";
984               echo "<td>".$class->getLink(TRUE)."</td>";
985            }
986            echo "</tr>";
987         }
988      }
989      return $output;
990   }
991}
992
993?>
994