Code

Requrie new schema for gosaAccount
[gosa.git] / gosa-core / include / class_filter.inc
1 <?php
2 /*
3  * This code is part of GOsa (http://www.gosa-project.org)
4  * Copyright (C) 2003-2008 GONICUS GmbH
5  *
6  * ID: $$Id$$
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
23 class filter {
25   var $xmlData;
26   var $elements= array();
27   var $elementValues= array();
28   var $alphabetElements= array();
29   var $autocompleter= array();
30   var $category= "";
31   var $objectStorage= array();
32   var $base= "";
33   var $scope= "";
34   var $query;
35   var $initial= false;
36   var $scopeMode= "auto";
37   var $alphabet= null;
38   var $converter= array();
39   var $pid;
42   function filter($filename)
43   {
44     global $config;
46     // Load eventually passed filename
47     if (!$this->load($filename)) {
48       die("Cannot parse $filename!");
49     }
51     $this->pid= preg_replace("/[^0-9]/", "", microtime(TRUE)); 
52   }
55   function load($filename)
56   {
57     $contents = file_get_contents($filename);
58     $this->xmlData= xml::xml2array($contents, 1);
60     if (!isset($this->xmlData['filterdef'])) {
61       return false;
62     }
64     $this->xmlData= $this->xmlData["filterdef"];
66     // Load filter
67     if (isset($this->xmlData['search'])) {
68       if (!isset($this->xmlData['search']['query'][0])){
69         $this->xmlData['search']['query']= array($this->xmlData['search']['query']);
70       }
72       // Move information
73       $entry= $this->xmlData['search'];
74       $this->scopeMode= $entry['scope'];
75       if ($entry['scope'] == "auto") {
76         $this->scope= "one";
77       } else {
78         $this->scope= $entry['scope'];
79       }
80       $this->query= $entry['query'];
81     } else {
82       return false;
83     }
85     // Transfer initial value
86     if (isset($this->xmlData['definition']['initial']) && $this->xmlData['definition']['initial'] == "true"){
87       $this->initial= true;
88     }
90     // Transfer category
91     if (isset($this->xmlData['definition']['category'])){
92       $this->category= $this->xmlData['definition']['category'];
93     }
95     // Generate formular data
96     if (isset($this->xmlData['element'])) {
97       if (!isset($this->xmlData['element'][0])){
98         $this->xmlData['element']= array($this->xmlData['element']);
99       }
100       foreach ($this->xmlData['element'] as $element) {
102         // Ignore elements without type
103         if (!isset($element['type']) || !isset($element['tag'])) {
104           next;
105         }
107         $tag= $element['tag'];
109         // Fix arrays
110         if (isset($element['value']) && !isset($element['value'][0])) {
111           $element['value']= array($element['value']);
112         }
114         // Store element for quick access
115         $this->elements[$tag] = $element;
117         // Preset elementValues with default values if exist
118         if (isset($element['default']) && !is_array($element['default'])) {
119           $this->elementValues[$tag] = $element['default'];
120         } else {
121           $this->elementValues[$tag] = "";
122         }
124         // Does this element react on alphabet links?
125         if (isset($element['alphabet']) && $element['alphabet'] == "true") {
126           $this->alphabetElements[]= $tag;
127         }
128       }
130       uasort($this->elements, 'strlenSort');
131       $this->elements= array_reverse($this->elements);
133     }
135     return true;  
136   }
139   function getTextfield($element)
140   {
141     $tag= $element['tag'];
142     $size= 30;
143     if (isset($element['size'])){
144       $size= $element['size'];
145     }
146     $maxlength= 30;
147     if (isset($element['maxlength'])){
148       $maxlength= $element['maxlength'];
149     }
150     $result= "<input class='filter_textfield' id='$tag' name='$tag' type='text' size='$size' maxlength='maxlength' value='".$this->elementValues[$tag]."'>";
151     if (isset($element['autocomplete'])) {
152       $frequency= "0.5";
153       $characters= "1";
154       if (isset($element['autocomplete']['frequency'])) {
155         $frequency= $element['autocomplete']['frequency'];
156       }
157       if (isset($element['autocomplete']['characters'])) {
158         $characters= $element['autocomplete']['characters'];
159       }
160       $result.= "<div id='autocomplete$tag' class='autocomplete'></div>".
161                 "<script type='text/javascript'>".
162                 "new Ajax.Autocompleter('$tag', 'autocomplete$tag', 'autocomplete.php', { minChars: $characters, frequency: $frequency });".
163                 "</script>";
165        $this->autocompleters[$tag]= $element['autocomplete'];
166     }
167     return $result;
168   }
171   function getCheckbox($element)
172   {
173     $tag= $element['tag'];
174     $checked= "";
175     if ($this->elementValues[$tag] == "true") {
176       $checked= " checked";
177     }
179     $result= "<input class='filter_checkbox' name='$tag' type='checkbox' onClick='document.mainform.submit();' value='true'$checked>";
180     return $result;
181   }
184   function getCombobox($element)
185   {
186     $result= "<select name='".$element['tag']."' size='1' onClick='document.mainform.submit();'>";
188     // Fill with presets
189     foreach ($element['value'] as $value) {
190       $selected= "";
191       if ($this->elementValues[$element['tag']] == $value['key']) {
192         $selected= " selected";
193       }
195       // Handle translations
196       $result.= "<option value='".$value['key']."'$selected>"._($value['label'])."</option>";
197     }
199     // Use autocompleter for additional data
200     if (isset($element['autocomplete'])) {
201       $list= $this->getCompletitionList($element['autocomplete'], $element['tag']);
202       foreach ($list as $value) {
203         $selected= "";
204         if ($this->elementValues[$element['tag']] == $value) {
205           $selected= " selected";
206         }
207         $result.= "<option value='$value'$selected>$value</option>";
208       }
209     }
211     $result.= "</select>";
213     return $result;
214   }
217   function getCurrentBase()
218   {
219     if (isset($this->search->base) && (string)$this->search->scope != "auto") {
220       return false;
221     }
223     return $this->base;
224   }
227   function getCurrentScope()
228   {
229     if (isset($this->search->scope) && (string)$this->search->scope != "auto") {
230       return (string)$this->search->scope;
231     }
233     return $this->scope;
234   }
237   function setConverter($field, $hook)
238   {
239     $this->converter[$field]= $hook;
240   }
243   function setObjectStorage($storage)
244   {
245     $this->objectStorage= $storage;    
246   }
249   function setBase($base)
250   {
251     $this->base= $base;
252   }
255   function setCurrentScope($scope)
256   {
257     $this->scope= $scope;
258   }
261   function renderAlphabet($columns= 10)
262   {
263     // Return pre-rendered alphabet if available
264     if ($this->alphabet) {
265       return ($this->alphabet);
266     }
268     $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
269     $alphabet= "";
270     $c= 0;
272     /* Fill cells with charaters */
273     for ($i= 0, $l= mb_strlen($characters, 'UTF8'); $i<$l; $i++){
274       if ($c == 0){
275         $alphabet.= "<tr>";
276       }
278       $ch = mb_substr($characters, $i, 1, "UTF8");
279       $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
280         validate($_GET['plug'])."&amp;filter=".$ch."\">&nbsp;".$ch."&nbsp;</a></td>";
282       if ($c++ == $columns){
283         $alphabet.= "</tr>";
284         $c= 0;
285       }
286     }
288     /* Fill remaining cells */
289     while ($c++ <= $columns){
290       $alphabet.= "<td>&nbsp;</td>";
291     }
293     /* Save alphabet */
294     $this->alphabet= "<table width='100%'>$alphabet</table>";
296     return ($this->alphabet);
297   }
300   function renderApply()
301   {
302     return ("<input type='submit' name='apply' value='"._("Apply filter")."'>");
303   }
306   function renderScope()
307   {
308     $checked= $this->scope == "sub"?" checked":"";
309     return "<input type='checkbox' name='SCOPE' value='1' onClick='document.mainform.submit();'$checked>&nbsp;"._("Search in subtrees");
310   }
313   function render()
314   {
315     $smarty= get_smarty();
316     $smarty->assign("ALPHABET", $this->renderAlphabet());
317     $smarty->assign("APPLY", $this->renderApply());
318     $smarty->assign("SCOPE", $this->renderScope());
320     // Load template and replace elementsHtml[]
321     foreach ($this->elements as $tag => $element) {
322       $htmlCode= "";
323       switch ($element['type']) {
324         case "textfield":
325           $htmlCode = $this->getTextfield($element);
326           break;
328         case "checkbox":
329           $htmlCode = $this->getCheckbox($element);
330           break;
332         case "combobox":
333           $htmlCode = $this->getCombobox($element);
334           break;
336         default:
337           die ("Unknown element type specified!");
338       }
339       $smarty->assign("$tag", $htmlCode);
340     }
342     // Load template
343     return ("<input type='hidden' name='FILTER_PID' value='".$this->pid."'>".$smarty->fetch(get_template_path($this->xmlData['definition']['template'], true)));
344   }
347   function query()
348   {
349     global $class_mapping;
350     $result= array();
352     // Return empty list if initial is not set
353     if (!$this->initial) {
354       $this->initial= true;
355       return $result;
356     }
358     // Go thru all queries and merge results
359     foreach ($this->query as $query) {
360       if (!isset($query['backend']) || !isset($query['filter']) || !isset($query['attribute'])) {
361         die("No backend specified in search config.");
362       }
364       // Is backend available?
365       $backend= "filter".$query['backend'];
366       if (!isset($class_mapping["$backend"])) {
367         die("Invalid backend specified in search config.");
368       }
370       // Load filter and attributes
371       $filter= $query['filter'];
372       $attributes= $query['attribute'];
374       // Generate final filter
375       foreach ($this->elements as $tag => $element) {
376         if (!isset($element['set']) || !isset($element['unset'])) {
377           continue;
378         }
380         // Handle converters if present
381         if (isset($this->converter[$tag])) {
382           preg_match('/([^:]+)::(.*)$/', $this->converter[$tag], $m);
383           $e_set= call_user_func(array($m[1], $m[2]), preg_replace('/\$/', $this->elementValues[$tag], is_array($element['set'])?"":$element['set']));
384           $e_unset= call_user_func(array($m[1], $m[2]), preg_replace('/\$/', $this->elementValues[$tag], is_array($element['unset'])?"":$element['unset']));
385         } else {
386           $e_set= is_array($element['set'])?"":$element['set'];
387           $e_unset= is_array($element['unset'])?"":$element['unset'];
388         }
390         if ($this->elementValues[$tag] == "") {
391           $e_unset= preg_replace('/\$/', normalizeLdap($this->elementValues[$tag]), $e_unset);
392           $filter= preg_replace("/\\$$tag/", $e_unset, $filter);
393         } else {
394           $e_set= preg_replace('/\$/', normalizeLdap($this->elementValues[$tag]), $e_set);
395           $filter= preg_replace("/\\$$tag/", $e_set, $filter);
396         }
397       }
399       $result= array_merge($result, call_user_func(array($backend, 'query'), $this->base, $this->scope, $filter, $attributes, $this->category, $this->objectStorage));
400     }
401     
402     return ($result);
403   }
406   function isValid()
407   {
408     foreach ($this->elements as $tag => $element) {
409       if (isset($element->regex)){
410         if (!preg_match('/'.(string)$element->regex.'/', $this->elementValues[$tag])){
411           return false;
412         }
413       }
414     }
415     return true;
416   }
419   function update()
420   {
422     /* React on alphabet links if needed */
423     if (isset($_GET['filter'])){
424       $s= mb_substr(validate($_GET['filter']), 0, 1, "UTF8")."*";
425       if ($s == "**"){
426         $s= "*";
427       }
428       foreach ($this->alphabetElements as $tag) {
429         $this->elementValues[$tag]= $s;
430       }
431     }
433     if (isset($_POST['FILTER_PID']) && $_POST['FILTER_PID'] == $this->pid) {
434       // Load post values and adapt filter, base and scope accordingly - but
435       // only if we didn't get a _GET
436       foreach ($this->elements as $tag => $element) {
437         if (isset($_POST[$tag])){
438           $this->elementValues[$tag]= validate($_POST[$tag]);
439         } else {
440           $this->elementValues[$tag]= "";
441         }
442       }
444       // Save scope if needed
445       if ($this->scopeMode == "auto") {
446         $this->scope= isset($_POST['SCOPE'])?"sub":"one";
447       }
448     }
450   }
453   function getCompletitionList($config, $tag, $value="*")
454   {
455     global $class_mapping;
456     $res= array();
458     // Is backend available?
459     $backend= "filter".$config['backend'];
460     if (!isset($class_mapping["$backend"])) {
461       die("Invalid backend specified in search config.");
462     }
464     // Load filter and attributes
465     $filter= $config['filter'];
466     $attributes= $config['attribute'];
467     if (!is_array($attributes)) {
468       $attributes= array($attributes);
469     }
471     // Make filter
472     $filter= preg_replace("/\\$$tag/", normalizeLDAP($value), $filter);
473     if (isset($config['base']) && isset($config['scope']) && isset($config['category'])) {
474       $result= call_user_func(array($backend, 'query'), $config['base'], $config['scope'], $filter, $attributes,
475                            $config["category"], $config["objectStorage"]);
476     } else {
477       $result= call_user_func(array($backend, 'query'), $this->base, $this->scope, $filter, $attributes,
478                            $this->category, $this->objectStorage);
479     }
481     foreach ($result as $entry) {
482       foreach ($attributes as $attribute) {
483         if (is_array($entry[$attribute])) {
484           for ($i= 0; $i<$entry[$attribute]['count']; $i++) {
485             if (mb_stristr($entry[$attribute][$i], $value)) {
486               $res[]= $entry[$attribute][$i];
487             }
488           }
489         } else {
490           $res[]= $entry[$attribute];
491         }
492       }
493     }
495     return $res;
496   }
499   function processAutocomplete()
500   {
501     global $class_mapping;
502     $result= array();
504     // Introduce maximum number of entries
505     $max= 25;
507     foreach ($this->autocompleters as $tag => $config) {
508       if(isset($_POST[$tag])){
509         $result= $this->getCompletitionList($config, $tag, $_POST[$tag]);
510         $result= array_unique($result);
511         asort($result);
513         echo '<ul>';
514         foreach ($result as $entry) {
515           echo '<li>'.$entry.'</li>';
516           if ($max-- == 0) {
517             break;
518           }
519         }
521         echo '</ul>';
522       }
523     }
524   }
527   function getObjectBase($dn)
528   {
529     global $config;
530     $base= "";
532     // Try every object storage
533     $storage= $this->objectStorage;
534     if (!is_array($storage)){
535       $storage= array($storage);
536     }
537     foreach ($storage as $location) {
538       $pattern= "/^[^,]+,".preg_quote($location, '/')."/i";
539       $base= preg_replace($pattern, '', $dn);
540     }
542     /* Set to base, if we're not on a correct subtree */
543     if (!isset($config->idepartments[$base])){
544       $base= $config->current['BASE'];
545     }
547     return $base;
548   }
553 // Sort elements for element length to allow proper replacing later on
554 function strlenSort($a, $b) {
555   if (strlen($a['tag']) == strlen($b['tag'])) {
556     return 0;
557   }
558   return (strlen($a['tag']) < strlen($b['tag']) ? -1 : 1);
559
561 ?>