Code

Sort exported lists, too
[gosa.git] / gosa-core / include / class_listing.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 listing {
25   var $xmlData;
26   var $entries;
27   var $departments= array();
28   var $departmentBrowser= false;
29   var $departmentRootVisible= false;
30   var $multiSelect= false;
31   var $template;
32   var $headline;
33   var $module;
34   var $base;
35   var $sortDirection= null;
36   var $sortColumn= null;
37   var $sortAttribute;
38   var $sortType;
39   var $numColumns;
40   var $baseMode= false;
41   var $bases= array();
42   var $header= array();
43   var $colprops= array();
44   var $filters= array();
45   var $pid;
46   var $objectTypes= array();
47   var $objectTypeCount= array();
48   var $copyPasteHandler= null;
49   var $snapshotHandler= null;
50   var $exporter= array();
51   var $exportColumns= array();
52   var $useSpan= false;
53   var $height= 0;
56   function listing($filename)
57   {
58     global $config;
59     global $class_mapping;
61     // Initialize pid
62     $this->pid= preg_replace("/[^0-9]/", "", microtime(TRUE));
64     if (!$this->load($filename)) {
65       die("Cannot parse $filename!");
66     }
68     // Set base for filter
69     if ($this->baseMode) {
70       $this->base= session::global_get("CurrentMainBase");
71       if ($this->base == null) {
72         $this->base= $config->current['BASE'];
73       }
74       $this->refreshBasesList();
75     } else {
76       $this->base= $config->current['BASE'];
77     }
79     // Move footer information
80     $this->showFooter= ($config->get_cfg_value("listSummary") == "true");
82     // Register build in filters
83     $this->registerElementFilter("objectType", "listing::filterObjectType");
84     $this->registerElementFilter("departmentLink", "listing::filterDepartmentLink");
85     $this->registerElementFilter("link", "listing::filterLink");
86     $this->registerElementFilter("actions", "listing::filterActions");
88     // Load exporters
89     foreach($class_mapping as $class => $dummy) {
90       if (preg_match('/Exporter$/', $class)) {
91         $info= call_user_func(array($class, "getInfo"));
92         if ($info != null) {
93           $this->exporter= array_merge($this->exporter, $info);
94         }
95       }
96     }
97   }
100   function setCopyPasteHandler($handler)
101   {
102     $this->copyPasteHandler= &$handler;
103   }
106   function setHeight($height)
107   {
108     $this->height= $height;
109   }
112   function setSnapshotHandler($handler)
113   {
114     $this->snapshotHandler= &$handler;
115   }
118   function setFilter($filter)
119   {
120     $this->filter= &$filter;
121     if ($this->departmentBrowser){
122       $this->departments= $this->getDepartments();
123     }
124     $this->filter->setBase($this->base);
125   }
128   function registerElementFilter($name, $call)
129   {
130     if (!isset($this->filters[$name])) {
131       $this->filters[$name]= $call;
132       return true;
133     }
135     return false;
136   }
139   function load($filename)
140   {
141     $contents = file_get_contents($filename);
142     $this->xmlData= xml::xml2array($contents, 1);
144     if (!isset($this->xmlData['list'])) {
145       return false;
146     }
148     $this->xmlData= $this->xmlData["list"];
150     // Load some definition values
151     foreach (array("departmentBrowser", "departmentRootVisible", "multiSelect", "baseMode") as $token) {
152       if (isset($this->xmlData['definition'][$token]) &&
153           $this->xmlData['definition'][$token] == "true"){
154         $this->$token= true;
155       }
156     }
158     // Fill objectTypes from departments and xml definition
159     $types = departmentManagement::get_support_departments();
160     foreach ($types as $class => $data) {
161       $this->objectTypes[]= array("label" => $data['TITLE'],
162                                   "objectClass" => $data['OC'],
163                                   "image" => $data['IMG']);
164     }
165     $this->categories= array();
166     if (isset($this->xmlData['definition']['objectType'])) {
167       if(isset($this->xmlData['definition']['objectType']['label'])) {
168         $this->xmlData['definition']['objectType']= array($this->xmlData['definition']['objectType']);
169       }
170       foreach ($this->xmlData['definition']['objectType'] as $index => $otype) {
171         $this->objectTypes[]= $this->xmlData['definition']['objectType'][$index];
172         if (isset($this->xmlData['definition']['objectType'][$index]['category'])){
173           $this->categories[]= $this->xmlData['definition']['objectType'][$index]['category'];
174         }
175       }
176     }
178     // Parse layout per column
179     $this->colprops= $this->parseLayout($this->xmlData['table']['layout']);
181     // Prepare table headers
182     $this->renderHeader();
184     // Assign headline/module
185     $this->headline= _($this->xmlData['definition']['label']);
186     $this->module= $this->xmlData['definition']['module'];
187     if (!is_array($this->categories)){
188       $this->categories= array($this->categories);
189     }
191     // Evaluate columns to be exported
192     if (isset($this->xmlData['table']['column'])){
193       foreach ($this->xmlData['table']['column'] as $index => $config) {
194         if (isset($config['export']) && $config['export'] == "true"){
195           $this->exportColumns[]= $index;
196         }
197       }
198     }
200     return true;  
201   }
204   function renderHeader()
205   {
206     $this->header= array();
207     $this->plainHeader= array();
209     // Initialize sort?
210     $sortInit= false;
211     if (!$this->sortDirection) {
212       $this->sortColumn= 0;
213       if (isset($this->xmlData['definition']['defaultSortColumn'])){
214         $this->sortColumn= $this->xmlData['definition']['defaultSortColumn'];
215       } else {
216         $this->sortAttribute= "";
217       }
218       $this->sortDirection= array();
219       $sortInit= true;
220     }
222     if (isset($this->xmlData['table']['column'])){
223       foreach ($this->xmlData['table']['column'] as $index => $config) {
224         // Initialize everything to one direction
225         if ($sortInit) {
226           $this->sortDirection[$index]= false;
227         }
229         $sorter= "";
230         if ($index == $this->sortColumn && isset($config['sortAttribute']) &&
231             isset($config['sortType'])) {
232           $this->sortAttribute= $config['sortAttribute'];
233           $this->sortType= $config['sortType'];
234           $sorter= "&nbsp;<img border='0' title='".($this->sortDirection[$index]?_("Up"):_("Down"))."' src='images/lists/sort-".($this->sortDirection[$index]?"up":"down").".png' align='top'>";
235         }
236         $sortable= (isset($config['sortAttribute']));
238         $link= "href='?plug=".$_GET['plug']."&amp;PID=".$this->pid."&amp;act=SORT_$index'";
239         if (isset($config['label'])) {
240           if ($sortable) {
241             $this->header[$index]= "<td class='listheader' ".$this->colprops[$index]."><a $link>"._($config['label'])."$sorter</a></td>";
242           } else {
243             $this->header[$index]= "<td class='listheader' ".$this->colprops[$index].">"._($config['label'])."</td>";
244           }
245           $this->plainHeader[]= _($config['label']);
246         } else {
247           if ($sortable) {
248             $this->header[$index]= "<td class='listheader' ".$this->colprops[$index]."><a $link>&nbsp;$sorter</a></td>";
249           } else {
250             $this->header[$index]= "<td class='listheader' ".$this->colprops[$index].">&nbsp;</td>";
251           }
252           $this->plainHeader[]= "";
253         }
254       }
255     }
256   }
258   function render()
259   {
260     // Check for exeeded sizelimit
261     if (($message= check_sizelimit()) != ""){
262       return($message);
263     }
265     // Initialize list
266     $result= "<input type='hidden' value='$this->pid' name='PID'>\n";
267     $height= 450;
268     if ($this->height != 0) {
269       $result.= "<input type='hidden' value='$this->height' id='d_height'>\n";
270       $height= $this->height;
271     }
272     
273     $result.= "<div class='contentboxb' id='listing_container' style='border-top:1px solid #B0B0B0;'>\n";
274     $result.= "<table summary='$this->headline' style='width:600px;height:".$height."px;' cellspacing='0' id='t_scrolltable'>
275 <tr><td class='scrollhead'><table summary='' style='width:100%;' cellspacing='0' id='t_scrollhead'>\n";
276     $this->numColumns= count($this->colprops) + ($this->multiSelect?1:0);
278     // Build list header
279     $result.= "<tr>\n";
280     if ($this->multiSelect) {
281       $result.= "<td class='listheader' style='width:20px;'><input type='checkbox' id='select_all' name='select_all' title='"._("Select all")."' onClick='toggle_all_(\"listing_selected_[0-9]*$\",\"select_all\");' ></td>\n";
282     }
283     foreach ($this->header as $header) {
284       $result.= $header;
285     }
287     // Add 13px for scroller
288     $result.= "<td class='listheader' style='width:13px;border-right:0px;'>&nbsp;</td></table></td></tr>\n";
290     // New table for the real list contents
291     $result.= "<tr><td colspan='$this->numColumns' class='scrollbody'><div style='width:600px;height:".($height-20)."px;' id='d_scrollbody' class='scrollbody'><table summary='' style='height:100%;width:581px;' cellspacing='0' id='t_scrollbody'>\n";
293     // No results? Just take an empty colspanned row
294     if (count($this->entries) + count($this->departments) == 0) {
295       $result.= "<tr class='rowxp0'><td class='list1nohighlight' colspan='$this->numColumns' style='height:100%;border-right:0px;width:100%;'>&nbsp;</td></tr>";
296     }
298     // Line color alternation
299     $alt= 0;
300     $deps= 0;
302     // Draw department browser if configured and we're not in sub mode
303     $this->useSpan= false;
304     if ($this->departmentBrowser && $this->filter->scope != "sub") {
305       // Fill with department browser if configured this way
306       $departmentIterator= new departmentSortIterator($this->departments, $this->sortDirection[$this->sortColumn]);
307       foreach ($departmentIterator as $row => $entry){
308         $result.="<tr class='rowxp".($alt&1)."'>";
310         // Render multi select if needed
311         if ($this->multiSelect) {
312           $result.="<td style='text-align:center;width:20px;' class='list1'>&nbsp;</td>";
313         }
315         // Render defined department columns, fill the rest with some stuff
316         $rest= $this->numColumns - 1;
317         foreach ($this->xmlData['table']['department'] as $index => $config) {
318           $colspan= 1;
319           if (isset($config['span'])){
320             $colspan= $config['span'];
321             $this->useSpan= true;
322           }
323           $result.="<td colspan='$colspan' ".$this->colprops[$index]." class='list1'>".$this->renderCell($config['value'], $entry, $row)."</td>";
324           $rest-= $colspan;
325         }
327         // Fill remaining cols with nothing
328         $last= $this->numColumns - $rest;
329         for ($i= 0; $i<$rest; $i++){
330           $result.= "<td ".$this->colprops[$last+$i-1]." class='list1'>&nbsp;</td>";
331         }
332         $result.="</tr>";
334         $alt++;
335       }
336       $deps= $alt;
337     }
339     // Fill with contents, sort as configured
340     foreach ($this->entries as $row => $entry) {
341       $trow= "";
343       // Render multi select if needed
344       if ($this->multiSelect) {
345         $trow.="<td style='text-align:center;width:20px;' class='list0'><input type='checkbox' id='listing_selected_$row' name='listing_selected_$row'></td>\n";
346       }
348       foreach ($this->xmlData['table']['column'] as $index => $config) {
349         $renderedCell= $this->renderCell($config['value'], $entry, $row);
350         $trow.="<td ".$this->colprops[$index]." class='list0'>".$renderedCell."</td>\n";
352         // Save rendered column
353         $sort= preg_replace('/.*>([^<]+)<.*$/', '$1', $renderedCell);
354         $sort= preg_replace('/&nbsp;/', '', $sort);
355         if (preg_match('/</', $sort)){
356           $sort= "";
357         }
358         $this->entries[$row]["_sort$index"]= $sort;
359       }
361       // Save rendered entry
362       $this->entries[$row]['_rendered']= $trow;
363     }
365     // Complete list by sorting entries for _sort$index and appending them to the output
366     $entryIterator= new listingSortIterator($this->entries, $this->sortDirection[$this->sortColumn], "_sort".$this->sortColumn, $this->sortType);
367     foreach ($entryIterator as $row => $entry){
368       $alt++;
369       $result.="<tr class='rowxp".($alt&1)."'>\n";
370       $result.= $entry['_rendered'];
371       $result.="</tr>\n";
372     }
374     // Need to fill the list if it's not full (nobody knows why this is 22 ;-))
375     $emptyListStyle= (count($this->entries) + (($this->useSpan && count($this->entries))?$deps:0) == 0)?"border:0;":"";
376     if ((count($this->entries) + $deps) < 22) {
377       $result.= "<tr>";
378       for ($i= 0; $i<$this->numColumns; $i++) {
379         if ($i == 0) {
380           $result.= "<td class='list1nohighlight' style='$emptyListStyle height:100%;'>&nbsp;</td>";
381           continue;
382         }
383         if ($i != $this->numColumns-1) {
384           $result.= "<td class='list1nohighlight' style='$emptyListStyle'>&nbsp;</td>";
385         } else {
386           $result.= "<td class='list1nohighlight' style='border-right:1px solid #AAA;$emptyListStyle'>&nbsp;</td>";
387         }
388       }
389       $result.= "</tr>";
390     }
392     $result.= "</table></div></td></tr>";
394     // Add the footer if requested
395     if ($this->showFooter) {
396       $result.= "<tr><td class='scrollhead'><table summary='' style='width:100%' cellspacing='0' id='t_scrollfoot'><tr><td class='listfooter' style='border-bottom:0px;'>";
398       foreach ($this->objectTypes as $objectType) {
399         if (isset($this->objectTypeCount[$objectType['label']])) {
400           $label= _($objectType['label']);
401           $result.= "<img class='center' src='".$objectType['image']."' title='$label' alt='$label'>&nbsp;".$this->objectTypeCount[$objectType['label']]."&nbsp;&nbsp;&nbsp;&nbsp;";
402         }
403       }
405       $result.= "<td class='listfooter' style='width:13px;border-right:0px;'>&nbsp;</td></table></td></tr>";
406     }
408     $result.= "</table></div>";
410     $smarty= get_smarty();
411     $smarty->assign("FILTER", $this->filter->render());
412     $smarty->assign("SIZELIMIT", print_sizelimit_warning());
413     $smarty->assign("LIST", $result);
415     // Assign navigation elements
416     $nav= $this->renderNavigation();
417     foreach ($nav as $key => $html) {
418       $smarty->assign($key, $html);
419     }
421     // Assign action menu / base
422     $smarty->assign("ACTIONS", $this->renderActionMenu());
423     $smarty->assign("BASE", $this->renderBase());
425     // Assign separator
426     $smarty->assign("SEPARATOR", "<img src='images/lists/seperator.png' alt='-' align='middle' height='16' width='1' class='center'>");
428     // Assign summary
429     $smarty->assign("HEADLINE", $this->headline);
431     return ($smarty->fetch(get_template_path($this->xmlData['definition']['template'], true)));
432   }
435   function update()
436   {
437     global $config;
438     $ui= get_userinfo();
440     // Reset object counter
441     $this->objectTypeCount= array();
443     // Do not do anything if this is not our PID
444     if(isset($_REQUEST['PID']) && $_REQUEST['PID'] != $this->pid) {
445       return;
446     }
448     // Save base
449     if (isset($_POST['BASE']) && $this->baseMode) {
450       $base= validate($_POST['BASE']);
451       if (isset($this->bases[$base])) {
452         $this->base= $base;
453       }
454     }
456     // Override the base if we got a message from the browser navigation
457     if ($this->departmentBrowser && isset($_GET['act'])) {
458       if (preg_match('/^department_([0-9]+)$/', validate($_GET['act']), $match)){
459         if (isset($this->departments[$match[1]])){
460           $this->base= $this->departments[$match[1]]['dn'];
461         }
462       }
463     }
465     // Filter POST with "act" attributes -> posted from action menu
466     if (isset($_POST['exec_act']) && $_POST['act'] != '') {
467       if (preg_match('/^export.*$/', $_POST['act']) && isset($this->exporter[$_POST['act']])) {
468         $exporter= $this->exporter[$_POST['act']];
469         $userinfo= ", "._("created by")." ".$ui->cn." - ".strftime('%A, %d. %B %Y, %H:%M:%S');
470         $entryIterator= new listingSortIterator($this->entries, $this->sortDirection[$this->sortColumn], "_sort".$this->sortColumn, $this->sortType);
471         $sortedEntries= array();
472         foreach ($entryIterator as $entry){
473           $sortedEntries[]= $entry;
474         }
475         $instance= new $exporter['class']($this->headline.$userinfo, $this->plainHeader, $sortedEntries, $this->exportColumns);
476         $type= call_user_func(array($exporter['class'], "getInfo"));
477         $type= $type[$_POST['act']];
478         send_binary_content($instance->query(), $type['filename'], $type= $type['mime']);
479       }
480     }
482     // Filter GET with "act" attributes
483     if (isset($_GET['act'])) {
484       $key= validate($_GET['act']);
485       if (preg_match('/^SORT_([0-9]+)$/', $key, $match)) {
486         // Switch to new column or invert search order?
487         $column= $match[1];
488         if ($this->sortColumn != $column) {
489           $this->sortColumn= $column;
490         } else {
491           $this->sortDirection[$column]= !$this->sortDirection[$column];
492         }
494         // Allow header to update itself according to the new sort settings
495         $this->renderHeader();
496       }
497     }
499     // Override base if we got signals from the navigation elements
500     $action= "";
501     foreach ($_POST as $key => $value) {
502       if (preg_match('/^(ROOT|BACK|HOME)_x$/', $key, $match)) {
503         $action= $match[1];
504         break;
505       }
506     }
508     // Navigation handling
509     if ($action == 'ROOT') {
510       $deps= $ui->get_module_departments($this->module);
511       $this->base= $deps[0];
512     }
513     if ($action == 'BACK') {
514       $deps= $ui->get_module_departments($this->module);
515       $base= preg_replace("/^[^,]+,/", "", $this->base);
516       if(in_array_ics($base, $deps)){
517         $this->base= $base;
518       }
519     }
520     if ($action == 'HOME') {
521       $ui= get_userinfo();
522       $this->base= $this->filter->getObjectBase($ui->dn);
523     }
525     // Reload departments
526     if ($this->departmentBrowser){
527       $this->departments= $this->getDepartments();
528     }
530     // Update filter and refresh entries
531     $this->filter->setBase($this->base);
532     $this->entries= $this->filter->query();
533   }
536   function setBase($base)
537   {
538     $this->base= $base;
539   }
542   function getBase()
543   {
544     return $this->base;
545   }
548   function parseLayout($layout)
549   {
550     $result= array();
551     $layout= preg_replace("/^\|/", "", $layout);
552     $layout= preg_replace("/\|$/", "", $layout);
553     $cols= split("\|", $layout);
554     foreach ($cols as $index => $config) {
555       if ($config != "") {
556         $components= split(';', $config);
557         $config= "";
558         foreach ($components as $part) {
559           if (preg_match("/^r$/", $part)) {
560             $config.= "text-align:right;";
561             continue;
562           }
563           if (preg_match("/^l$/", $part)) {
564             $config.= "text-align:left;";
565             continue;
566           }
567           if (preg_match("/^c$/", $part)) {
568             $config.= "text-align:center;";
569             continue;
570           }
571           if (preg_match("/^[0-9]+(|px|%)$/", $part)) {
572             $config.= "width:$part;";
573             continue;
574           }
575         }
577         $result[$index]= " style='$config' ";
578       } else {
579         $result[$index]= null;
580       }
581     }
583     // Save number of columns for later use
584     $this->numColumns= count($cols);
586     return $result;
587   }
590   function renderCell($data, $config, $row)
591   {
592     // Replace flat attributes in data string
593     for ($i= 0; $i<$config['count']; $i++) {
594       $attr= $config[$i];
595       $value= "";
596       if (is_array($config[$attr])) {
597         $value= $config[$attr][0];
598       } else {
599         $value= $config[$attr];
600       }
601       $data= preg_replace("/%\{$attr\}/", $value, $data);
602     }
604     // Watch out for filters and prepare to execute them
605     $data= $this->processElementFilter($data, $config, $row);
607     // Replace all non replaced %{...} instances because they
608     // are non resolved attributes or filters
609     $data= preg_replace('/%{[^}]+}/', '&nbsp;', $data);
611     return $data;
612   }
615   function renderBase()
616   {
617     if (!$this->baseMode) {
618       return;
619     }
621     $result= "<select name='BASE' onChange='mainform.submit()' size='1'>";
622     $firstDN= null;
623     $found= false;
625     foreach ($this->bases as $key=>$value) {
626       // Keep first entry to fall back eventually
627       if(!$firstDN) {
628         $firstDN= $key;
629       }
631       // Prepare to render entry
632       $selected= "";
633       if ($key == $this->base) {
634         $selected= " selected";
635         $found= true;
636       }
637       $result.= "<option value='".$key."'$selected>".$value."</option>";
638     }
639     $result.= "</select>";
641     // Reset the currently used base to the first DN we found if there
642     // was no match.
643     if(!$found){
644       $this->base = $firstDN;
645     }
647     return $result;
648   }
651   function processElementFilter($data, $config, $row)
652   {
653     preg_match_all("/%\{filter:([^(]+)\((.*)\)\}/", $data, $matches, PREG_SET_ORDER);
655     foreach ($matches as $match) {
656       if (!isset($this->filters[$match[1]])) {
657         continue;
658       }
659       $cl= preg_replace('/::.*$/', '', $this->filters[$match[1]]);
660       $method= preg_replace('/^.*::/', '', $this->filters[$match[1]]);
662       // Prepare params for function call
663       $params= array();
664       preg_match_all('/"[^"]+"|[^,]+/', $match[2], $parts);
665       foreach ($parts[0] as $param) {
667         // Row is replaced by the row number
668         if ($param == "row") {
669           $params[]= $row;
670         }
672         // pid is replaced by the current PID
673         if ($param == "pid") {
674           $params[]= $this->pid;
675         }
677         // Fixie with "" is passed directly
678         if (preg_match('/^".*"$/', $param)){
679           $params[]= preg_replace('/"/', '', $param);
680         }
682         // LDAP variables get replaced by their objects
683         for ($i= 0; $i<$config['count']; $i++) {
684           if ($param == $config[$i]) {
685             $values= $config[$config[$i]];
686             if (is_array($values)){
687               unset($values['count']);
688             }
689             $params[]= $values;
690           }
691         }
693         // Move dn if needed
694         if ($param == "dn") {
695           $params[]= LDAP::fix($config["dn"]);
696         }
697       }
699       // Replace information
700       if ($cl == "listing") {
701         // Non static call - seems to result in errors
702         $data= @preg_replace('/'.preg_quote($match[0]).'/', call_user_func_array(array($this, "$method"), $params), $data);
703       } else {
704         // Static call
705         $data= preg_replace('/'.preg_quote($match[0]).'/', call_user_func_array(array($cl, $method), $params), $data);
706       }
707     }
709     return $data;
710   }
713   function getObjectType($types, $classes)
714   {
715     // Walk thru types and see if there's something matching
716     foreach ($types as $objectType) {
717       $ocs= $objectType['objectClass'];
718       if (!is_array($ocs)){
719         $ocs= array($ocs);
720       }
722       $found= true;
723       foreach ($ocs as $oc){
724         if (preg_match('/^!(.*)$/', $oc, $match)) {
725           $oc= $match[1];
726           if (in_array($oc, $classes)) {
727             $found= false;
728           }
729         } else {
730           if (!in_array($oc, $classes)) {
731             $found= false;
732           }
733         }
734       }
736       if ($found) {
737         return $objectType;
738       }
739     }
741     return null;
742   }
745   function filterObjectType($dn, $classes)
746   {
747     // Walk thru classes and return on first match
748     $result= "&nbsp;";
750     $objectType= $this->getObjectType($this->objectTypes, $classes);
751     if ($objectType) {
752       $result= "<img class='center' title='".LDAP::fix($dn)."' src='".$objectType["image"]."'>";
753       if (!isset($this->objectTypeCount[$objectType['label']])) {
754         $this->objectTypeCount[$objectType['label']]= 0;
755       }
756       $this->objectTypeCount[$objectType['label']]++;
757     }
758     return $result;
759   }
762   function filterActions($dn, $row, $classes)
763   {
764     // Do nothing if there's no menu defined
765     if (!isset($this->xmlData['actiontriggers']['action'])) {
766       return "&nbsp;";
767     }
769     // Go thru all actions
770     $result= "";
771     $actions= $this->xmlData['actiontriggers']['action'];
772     foreach($actions as $action) {
773       // Skip the entry completely if there's no permission to execute it
774       if (!$this->hasActionPermission($action, $dn)) {
775         continue;
776       }
778       // If there's an objectclass definition and we don't have it
779       // add an empty picture here.
780       if (isset($action['objectclass'])){
781         $objectclass= $action['objectclass'];
782         if (preg_match('/^!(.*)$/', $objectclass, $m)){
783           $objectclass= $m[1];
784           if(in_array($objectclass, $classes)) {
785             $result.= "<img src='images/empty.png' alt=' ' class='center' style='padding:1px'>";
786             continue;
787           }
788         } else {
789           if(!in_array($objectclass, $classes)) {
790             $result.= "<img src='images/empty.png' alt=' ' class='center' style='padding:1px'>";
791             continue;
792           }
793         }
794       }
796       // Render normal entries as usual
797       if ($action['type'] == "entry") {
798         $label= $this->processElementFilter($action['label'], $this->entries[$row], $row);
799         $image= $this->processElementFilter($action['image'], $this->entries[$row], $row);
800         $result.="<input class='center' type='image' src='$image' title='$label' ".
801                  "name='listing_".$action['name']."_$row' style='padding:1px'>";
802       }
804       // Handle special types
805       if ($action['type'] == "copypaste" || $action['type'] == "snapshot") {
807         $objectType= $this->getObjectType($this->objectTypes, $this->entries[$row]['objectClass']);
808         $category= $class= null;
809         if ($objectType) {
810           $category= $objectType['category'];
811           $class= $objectType['class'];
812         }
814         if ($action['type'] == "copypaste") {
815           $result.= $this->renderCopyPasteActions($row, $this->entries[$row]['dn'], $category, $class);
816         } else {
817           $result.= $this->renderSnapshotActions($row, $this->entries[$row]['dn'], $category, $class);
818         }
819       }
820     }
822     return $result;
823   }
826   function filterDepartmentLink($row, $dn, $description)
827   {
828     $attr= $this->departments[$row]['sort-attribute'];
829     $name= $this->departments[$row][$attr];
830     if (is_array($name)){
831       $name= $name[0];
832     }
833     $result= sprintf("%s [%s]", $name, $description[0]);
834     return("<a href='?plug=".$_GET['plug']."&amp;PID=$this->pid&amp;act=department_$row' title='$dn'>$result</a>");
835   }
838   function filterLink()
839   {
840     $result= "&nbsp;";
842     $row= func_get_arg(0);
843     $pid= $this->pid;
844     $dn= LDAP::fix(func_get_arg(1));
845     $params= array(func_get_arg(2));
847     // Collect sprintf params
848     for ($i = 3;$i < func_num_args();$i++) {
849       $val= func_get_arg($i);
850       if (is_array($val)){
851         $params[]= $val[0];
852         continue;
853       }
854       $params[]= $val;
855     }
857     $result= "&nbsp;";
858     $trans= call_user_func_array("sprintf", $params);
859     if ($trans != "") {
860       return("<a href='?plug=".$_GET['plug']."&amp;PID=$pid&amp;act=listing_edit_$row' title='$dn'>$trans</a>");
861     }
863     return $result;
864   }
867   function renderNavigation()
868   {
869     $result= array();
870     $enableBack = true;
871     $enableRoot = true;
872     $enableHome = true;
874     $ui = get_userinfo();
876     /* Check if base = first available base */
877     $deps = $ui->get_module_departments($this->module);
879     if(!count($deps) || $deps[0] == $this->filter->base){
880       $enableBack = false;
881       $enableRoot = false;
882     }
884     $listhead ="";
886     /* Check if we are in users home  department */
887     if(!count($deps) || $this->filter->base == $this->filter->getObjectBase($ui->dn)){
888       $enableHome = false;
889     }
891     /* Draw root button */
892     if($enableRoot){
893       $result["ROOT"]= "<input class='center' type='image' src='images/lists/root.png' align='middle' ".
894                        "title='"._("Go to root department")."' name='ROOT' alt='"._("Root")."'>";
895     }else{
896       $result["ROOT"]= "<img src='images/lists/root_grey.png' class='center' alt='"._("Root")."'>";
897     }
899     /* Draw back button */
900     if($enableBack){
901       $result["BACK"]= "<input class='center' type='image' align='middle' src='images/lists/back.png' ".
902                        "title='"._("Go up one department")."' alt='"._("Up")."' name='BACK'>";
903     }else{
904       $result["BACK"]= "<img src='images/lists/back_grey.png' class='center' alt='"._("Up")."'>";
905     }
907     /* Draw home button */
908     if($enableHome){
909       $result["HOME"]= "<input class='center' type='image' align='middle' src='images/lists/home.png' ".
910                        "title='"._("Go to users department")."' alt='"._("Home")."' name='HOME'>";
911     }else{
912       $result["HOME"]= "<img src='images/lists/home_grey.png' class='center' alt='"._("Home")."'>";
913     }
915     /* Draw reload button, this button is enabled everytime */
916     $result["RELOAD"]= "<input class='center' type='image' src='images/lists/reload.png' align='middle' ".
917                        "title='"._("Reload list")."' name='REFRESH' alt='"._("Submit")."'>";
919     return ($result);
920   }
923   function getAction()
924   {
925     // Do not do anything if this is not our PID, or there's even no PID available...
926     if(!isset($_REQUEST['PID']) || $_REQUEST['PID'] != $this->pid) {
927       return;
928     }
930     $result= array("targets" => array(), "action" => "");
932     // Filter GET with "act" attributes
933     if (isset($_GET['act'])) {
934       $key= validate($_GET['act']);
935       $target= preg_replace('/^listing_[a-zA-Z_]+_([0-9]+)$/', '$1', $key);
936       if (isset($this->entries[$target]['dn'])) {
937         $result['action']= preg_replace('/^listing_([a-zA-Z_]+)_[0-9]+$/', '$1', $key);
938         $result['targets'][]= $this->entries[$target]['dn'];
939       }
941       // Drop targets if empty
942       if (count($result['targets']) == 0) {
943         unset($result['targets']);
944       }
945       return $result;
946     }
948     // Filter POST with "listing_" attributes
949     foreach ($_POST as $key => $prop) {
951       // Capture selections
952       if (preg_match('/^listing_selected_[0-9]+$/', $key)) {
953         $target= preg_replace('/^listing_selected_([0-9]+)$/', '$1', $key);
954         if (isset($this->entries[$target]['dn'])) {
955           $result['targets'][]= $this->entries[$target]['dn'];
956         }
957         continue;
958       }
960       // Capture action with target - this is a one shot
961       if (preg_match('/^listing_[a-zA-Z_]+_[0-9]+(|_x)$/', $key)) {
962         $target= preg_replace('/^listing_[a-zA-Z_]+_([0-9]+)(|_x)$/', '$1', $key);
963         if (isset($this->entries[$target]['dn'])) {
964           $result['action']= preg_replace('/^listing_([a-zA-Z_]+)_[0-9]+(|_x)$/', '$1', $key);
965           $result['targets']= array($this->entries[$target]['dn']);
966         }
967         break;
968       }
970       // Capture action without target
971       if (preg_match('/^listing_[a-zA-Z_]+(|_x)$/', $key)) {
972         $result['action']= preg_replace('/^listing_([a-zA-Z_]+)(|_x)$/', '$1', $key);
973         continue;
974       }
975     }
977     // Filter POST with "act" attributes -> posted from action menu
978     if (isset($_POST['act']) && $_POST['act'] != '') {
979       if (!preg_match('/^export.*$/', $_POST['act'])){
980         $result['action']= validate($_POST['act']);
981       }
982     }
984     // Drop targets if empty
985     if (count($result['targets']) == 0) {
986       unset($result['targets']);
987     }
988     return $result;
989   }
992   function renderActionMenu()
993   {
994     // Don't send anything if the menu is not defined
995     if (!isset($this->xmlData['actionmenu']['action'])){
996       return "";
997     }
999     // Array?
1000     if (isset($this->xmlData['actionmenu']['action']['type'])){
1001       $this->xmlData['actionmenu']['action']= array($this->xmlData['actionmenu']['action']);
1002     }
1004     // Load shortcut
1005     $actions= &$this->xmlData['actionmenu']['action'];
1006     $result= "<input type='hidden' name='act' id='actionmenu' value=''><div style='display:none'><input type='submit' name='exec_act' id='exec_act' value=''></div>".
1007              "<ul class='level1' id='root'><li><a href='#'>Aktionen&nbsp;<img ".
1008              "border=0 class='center' src='images/lists/sort-down.png'></a>";
1010     // Build ul/li list
1011     $result.= $this->recurseActions($actions);
1013     return "<div id='pulldown'>".$result."</li></ul><div>";
1014   }
1017   function recurseActions($actions)
1018   {
1019     static $level= 2;
1020     $result= "<ul class='level$level'>";
1021     $separator= "";
1023     foreach ($actions as $action) {
1025       // Skip the entry completely if there's no permission to execute it
1026       if (!$this->hasActionPermission($action, $this->filter->base)) {
1027         continue;
1028       }
1030       // Fill image if set
1031       $img= "";
1032       if (isset($action['image'])){
1033         $img= "<img border='0' class='center' src='".$action['image']."'>&nbsp;";
1034       }
1036       if ($action['type'] == "separator"){
1037         $separator= " style='border-top:1px solid #AAA' ";
1038         continue;
1039       }
1041       // Dive into subs
1042       if ($action['type'] == "sub" && isset($action['action'])) {
1043         $level++;
1044         if (isset($action['label'])){
1045           $result.= "<li$separator><a href='#'>$img"._($action['label'])."&nbsp;<img border='0' src='images/forward-arrow.png'></a>";
1046         }
1047         $result.= $this->recurseActions($action['action'])."</li>";
1048         $level--;
1049         $separator= "";
1050         continue;
1051       }
1053       // Render entry elseways
1054       if (isset($action['label'])){
1055         $result.= "<li$separator><a href='#' onClick='document.getElementById(\"actionmenu\").value= \"".$action['name']."\";mainform.submit();'>$img"._($action['label'])."</a></li>";
1056       }
1058       // Check for special types
1059       switch ($action['type']) {
1060         case 'copypaste':
1061           $result.= $this->renderCopyPasteMenu($separator);
1062           break;
1064         case 'snapshot':
1065           $result.= $this->renderSnapshotMenu($separator);
1066           break;
1068         case 'exporter':
1069           $result.= $this->renderExporterMenu($separator);
1070           break;
1072         case 'daemon':
1073           $result.= $this->renderDaemonMenu($separator);
1074           break;
1075       }
1077       $separator= "";
1078     }
1080     $result.= "</ul>";
1081     return $result;
1082   }
1085   function hasActionPermission($action, $dn)
1086   {
1087     $ui= get_userinfo();
1089     if (isset($action['acl'])) {
1090       $acls= $action['acl'];
1091       if (!is_array($acls)) {
1092         $acls= array($acls);
1093       }
1095       // Every ACL has to pass
1096       foreach ($acls as $acl) {
1097         $module= $this->module;
1098         $aclList= array();
1100         // Split for category and plugins if needed
1101         // match for "[rw]" style entries
1102         if (preg_match('/^\[([rwcdm]+)\]$/', $acl, $match)){
1103           $aclList= array($match[1]);
1104         }
1106         // match for "users[rw]" style entries
1107         if (preg_match('/^([a-zA-Z0-9]+)\[([rwcdm]+)\]$/', $acl, $match)){
1108           $module= $match[1];
1109           $aclList= array($match[2]);
1110         }
1112         // match for "users/user[rw]" style entries
1113         if (preg_match('/^([a-zA-Z0-9]+\/[a-zA-Z0-9]+)\[([rwcdm]+)\]$/', $acl, $match)){
1114           $module= $match[1];
1115           $aclList= array($match[2]);
1116         }
1118         // match "users/user[userPassword:rw(,...)*]" style entries
1119         if (preg_match('/^([a-zA-Z0-9]+\/[a-zA-Z0-9]+)\[([a-zA-Z0-9]+:[rwcdm]+(,[a-zA-Z0-9]+:[rwcdm]+)*)\]$/', $acl, $match)){
1120           $module= $match[1];
1121           $aclList= split(',', $match[2]);
1122         }
1124         // Walk thru prepared ACL by using $module
1125         foreach($aclList as $sAcl) {
1126           $checkAcl= "";
1128           // Category or detailed permission?
1129           if (strpos('/', $module) === false) {
1130             if (preg_match('/([a-zA-Z0-9]+):([rwcdm]+)/', $sAcl, $m) ) {
1131               $checkAcl= $ui->get_permissions($dn, $module, $m[1]);
1132               $sAcl= $m[2];
1133             } else {
1134               $checkAcl= $ui->get_permissions($dn, $module, '0');
1135             }
1136           } else {
1137             $checkAcl= $ui->get_category_permissions($dn, $module);
1138           }
1140           // Split up remaining part of the acl and check if it we're
1141           // allowed to do something...
1142           $parts= str_split($sAcl);
1143           foreach ($parts as $part) {
1144             if (strpos($checkAcl, $part) === false){
1145               return false;
1146             }
1147           }
1149         }
1150       }
1151     }
1153     return true;
1154   }
1157   function refreshBasesList()
1158   {
1159     global $config;
1160     $ui= get_userinfo();
1162     // Do some array munching to get it user friendly
1163     $ids= $config->idepartments;
1164     $d= $ui->get_module_departments($this->module);
1165     $k_ids= array_keys($ids);
1166     $deps= array_intersect($d,$k_ids);
1168     // Fill internal bases list
1169     $this->bases= array();
1170     foreach($k_ids as $department){
1171       $this->bases[$department] = $ids[$department];
1172     }
1173   }
1176   function getDepartments()
1177   {
1178     $departments= array();
1179     $ui= get_userinfo();
1181     // Get list of supported department types
1182     $types = departmentManagement::get_support_departments();
1184     // Load departments allowed by ACL
1185     $validDepartments = $ui->get_module_departments($this->module);
1187     // Build filter and look in the LDAP for possible sub departments
1188     // of current base
1189     $filter= "(&(objectClass=gosaDepartment)(|";
1190     $attrs= array("description", "objectClass");
1191     foreach($types as $name => $data){
1192       $filter.= "(objectClass=".$data['OC'].")";
1193       $attrs[]= $data['ATTR'];
1194     }
1195     $filter.= "))";
1196     $res= get_list($filter, $this->module, $this->base, $attrs, GL_NONE);
1198     // Analyze list of departments
1199     foreach ($res as $department) {
1200       if (!in_array($department['dn'], $validDepartments)) {
1201         continue;
1202       }
1204       // Add the attribute where we use for sorting
1205       $oc= null;
1206       foreach(array_keys($types) as $type) {
1207         if (in_array($type, $department['objectClass'])) {
1208           $oc= $type;
1209           break;
1210         }
1211       }
1212       $department['sort-attribute']= $types[$oc]['ATTR'];
1214       // Move to the result list
1215       $departments[]= $department;
1216     }
1218     return $departments;
1219   }
1222   function renderCopyPasteMenu($separator, $copy= true, $cut= true)
1223   {
1224     // We can only provide information if we've got a copypaste handler
1225     // instance
1226     if(!(isset($this->copyPasteHandler) && is_object($this->copyPasteHandler))){
1227       return "";
1228     }
1230     // Presets
1231     $result= "";
1232     $read= $paste= false;
1233     $ui= get_userinfo();
1235     // Switch flags to on if there's at least one category which allows read/paste
1236     foreach($this->categories as $category){
1237       $read= $read || preg_match('/r/', $ui->get_category_permissions($this->base, $category));
1238       $paste= $paste || $ui->is_pasteable($this->base, $category) == 1;
1239     }
1242     // Draw entries that allow copy and cut
1243     if($read){
1245       // Copy entry
1246       if($copy){
1247         $result.= "<li$separator><a href='#' onClick='document.getElementById(\"actionmenu\").value= \"copy\";document.getElementById(\"exec_act\").click();'><img src='images/lists/copy.png' alt='' border='0' class='center'>&nbsp;"._("Copy")."</a></li>";
1248         $separator= "";
1249       }
1251       // Cut entry
1252       if($cut){
1253         $result.= "<li$separator><a href='#' onClick='document.getElementById(\"actionmenu\").value= \"cut\";document.getElementById(\"exec_act\").click();'><img src='images/lists/cut.png' alt='' border='0' class='center'>&nbsp;"._("Cut")."</a></li>";
1254         $separator= "";
1255       }
1256     }
1258     // Draw entries that allow pasting entries
1259     if($paste){
1260       if($this->copyPasteHandler->entries_queued()){
1261         $result.= "<li$separator><a href='#' onClick='document.getElementById(\"actionmenu\").value= \"paste\";document.getElementById(\"exec_act\").click();'><img src='images/lists/paste.png' alt='' border='0' class='center'>&nbsp;"._("Paste")."</a></li>";
1262       }else{
1263         $result.= "<li$separator><a href='#'><img src='images/lists/paste-grey.png' alt='' border='0' class='center'>&nbsp;"._("Paste")."</a></li>";
1264       }
1265     }
1266     
1267     return($result);
1268   }
1271   function renderCopyPasteActions($row, $dn, $category, $class, $copy= true, $cut= true)
1272   {
1273     // We can only provide information if we've got a copypaste handler
1274     // instance
1275     if(!(isset($this->copyPasteHandler) && is_object($this->copyPasteHandler))){
1276       return "";
1277     }
1279     // Presets
1280     $ui = get_userinfo();
1281     $result = "";
1283     // Render cut entries
1284     if($cut){
1285       if($ui->is_cutable($dn, $category, $class)){
1286         $result .= "<input class='center' type='image'
1287           src='images/lists/cut.png' alt='"._("Cut")."' name='listing_cut_$row' title='"._("Cut this entry")."' style='padding:1px'>";
1288       }else{
1289         $result.="<img src='images/empty.png' alt=' ' class='center' style='padding:1px'>";
1290       }
1291     }
1293     // Render copy entries
1294     if($copy){
1295       if($ui->is_copyable($dn, $category, $class)){
1296         $result.= "<input class='center' type='image'
1297           src='images/lists/copy.png' alt='"._("Copy")."' name='listing_copy_$row' title='"._("Copy this entry")."' style='padding:1px'>";
1298       }else{
1299         $result.="<img src='images/empty.png' alt=' ' class='center' style='padding:1px'>";
1300       }
1301     }
1303     return($result);
1304   }
1307   function renderSnapshotMenu($separator)
1308   {
1309     // We can only provide information if we've got a snapshot handler
1310     // instance
1311     if(!(isset($this->snapshotHandler) && is_object($this->snapshotHandler))){
1312       return "";
1313     }
1315     // Presets
1316     $result = "";
1317     $ui = get_userinfo();
1319     if($this->snapshotHandler->enabled() && $ui->allow_snapshot_restore($this->base, $this->module)){
1321       // Check if there is something to restore
1322       $restore= false;
1323       foreach($this->snapshotHandler->getSnapshotBases() as $base){
1324         $restore= $restore || count($this->snapshotHandler->getDeletedSnapshots($base)) > 0;
1325       }
1327       // Draw icons according to the restore flag
1328       if($restore){
1329         $result.= "<li$separator><a href='#' onClick='document.getElementById(\"actionmenu\").value= \"restore\";document.getElementById(\"exec_act\").click();'><img src='images/lists/restore.png' alt='' border='0' class='center'>&nbsp;"._("Restore snapshots")."</a></li>";
1330       }else{
1331         $result.= "<li$separator><a href='#'><img src='images/lists/restore_grey.png' alt='' border='0' class='center'>&nbsp;"._("Restore snapshots")."</a></li>";
1332       }
1333     }
1335     return($result);
1336   }
1339   function renderExporterMenu($separator)
1340   {
1341     // Presets
1342     $result = "";
1344     // Draw entries
1345     $result.= "<li$separator><a href='#'><img border='0' class='center' src='images/lists/export.png'>&nbsp;"._("Export list")."&nbsp;<img border='0' src='images/forward-arrow.png'></a><ul class='level3'>";
1347     // Export CVS as build in exporter
1348     foreach ($this->exporter as $action => $exporter) {
1349       $result.= "<li><a href='#' onClick='document.getElementById(\"actionmenu\").value= \"$action\";document.getElementById(\"exec_act\").click();'><img border='0' class='center' src='".$exporter['image']."'>&nbsp;".$exporter['label']."</a></li>";
1350     }
1352     // Finalize list
1353     $result.= "</ul></li>";
1355     return($result);
1356   }
1359   function renderSnapshotActions($row, $dn, $category, $class, $copy= true, $cut= true)
1360   {
1361     // We can only provide information if we've got a snapshot handler
1362     // instance
1363     if(!(isset($this->snapshotHandler) && is_object($this->snapshotHandler))){
1364       return "";
1365     }
1367     // Presets
1368     $result= "";
1369     $ui = get_userinfo();
1371     // Only act if enabled here
1372     if($this->snapshotHandler->enabled()){
1374       // Draw restore button
1375       if ($ui->allow_snapshot_restore($dn, $category)){
1377         // Do we have snapshots for this dn?
1378         if($this->snapshotHandler->hasSnapshots($dn)){
1379           $result.= "<input class='center' type='image' src='images/lists/restore.png' ".
1380                      "alt='"._("Restore snapshot")."' name='listing_restore_$row' title='".
1381                      _("Restore snapshot")."' style='padding:1px'>";
1382         } else {
1383           $result.= "<img src='images/lists/restore_grey.png' alt=' ' class='center' style='padding:1px'>";
1384         }
1385       }
1387       // Draw snapshot button
1388       if($ui->allow_snapshot_create($dn, $category)){
1389           $result.= "<input class='center' type='image' src='images/snapshot.png' ".
1390                      "alt='"._("Create snapshot")."' name='listing_snapshot_$row' title='".
1391                      _("Create a new snapshot from this object")."' style='padding:1px'>";
1392       }else{
1393           $result.= "<img src='images/empty.png' alt=' ' class='center' style='padding:1px'>";
1394       }
1395     }
1397     return($result);
1398   }
1401   function renderDaemonMenu($separator)
1402   {
1403     $result= "";
1405     // If there is a daemon registered, draw the menu entries
1406     if(class_available("DaemonEvent")){
1407       $events= DaemonEvent::get_event_types_by_category($this->categories);
1408       if(isset($events['BY_CLASS']) && count($events['BY_CLASS'])){
1409         foreach($events['BY_CLASS'] as $name => $event){
1410           $result.= "<li$separator><a href='#' onClick='document.getElementById(\"actionmenu\").value=\"$name\";document.getElementById(\"exec_act\").click();'>".$event['MenuImage']."&nbsp;".$event['s_Menu_Name']."</a></li>";
1411           $separator= "";
1412         }
1413       }
1414     }
1416     return $result;
1417   }
1421 ?>