Code

Ingore first listing if configured this way. Just load list once...
[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();
54   function listing($filename)
55   {
56     global $config;
57     global $class_mapping;
59     // Initialize pid
60     $this->pid= preg_replace("/[^0-9]/", "", microtime(TRUE));
62     if (!$this->load($filename)) {
63       die("Cannot parse $filename!");
64     }
66     // Set base for filter
67     $this->base= session::global_get("CurrentMainBase");
68     if ($this->base == null) {
69       $this->base= $config->current['BASE'];
70     }
71     $this->refreshBasesList();
73     // Move footer information
74     $this->showFooter= ($config->get_cfg_value("listSummary") == "true");
76     // Register build in filters
77     $this->registerElementFilter("objectType", "listing::filterObjectType");
78     $this->registerElementFilter("departmentLink", "listing::filterDepartmentLink");
79     $this->registerElementFilter("link", "listing::filterLink");
80     $this->registerElementFilter("actions", "listing::filterActions");
82     // Load exporters
83     foreach($class_mapping as $class => $dummy) {
84       if (preg_match('/Exporter$/', $class)) {
85         $info= call_user_func(array($class, "getInfo"));
86         if ($info != null) {
87           $this->exporter= array_merge($this->exporter, $info);
88         }
89       }
90     }
91   }
94   function setCopyPasteHandler($handler)
95   {
96     $this->copyPasteHandler= &$handler;
97   }
100   function setSnapshotHandler($handler)
101   {
102     $this->snapshotHandler= &$handler;
103   }
106   function setFilter($filter)
107   {
108     $this->filter= &$filter;
109     if ($this->departmentBrowser){
110       $this->departments= $this->getDepartments();
111     }
112     $this->filter->setBase($this->base);
113   }
116   function registerElementFilter($name, $call)
117   {
118     if (!isset($this->filters[$name])) {
119       $this->filters[$name]= $call;
120       return true;
121     }
123     return false;
124   }
127   function load($filename)
128   {
129     $contents = file_get_contents($filename);
130     $this->xmlData= xml::xml2array($contents, 1);
132     if (!isset($this->xmlData['list'])) {
133       return false;
134     }
136     $this->xmlData= $this->xmlData["list"];
138     // Load some definition values
139     foreach (array("departmentBrowser", "departmentRootVisible", "multiSelect", "baseMode") as $token) {
140       if (isset($this->xmlData['definition'][$token]) &&
141           $this->xmlData['definition'][$token] == "true"){
142         $this->$token= true;
143       }
144     }
146     // Fill objectTypes from departments and xml definition
147     $types = departmentManagement::get_support_departments();
148     foreach ($types as $class => $data) {
149       $this->objectTypes[]= array("label" => $data['TITLE'],
150                                   "objectClass" => $data['OC'],
151                                   "image" => $data['IMG']);
152     }
153     $this->categories= array();
154     if (isset($this->xmlData['definition']['objectType'])) {
155       if(isset($this->xmlData['definition']['objectType']['label'])) {
156         $this->xmlData['definition']['objectType']= array($this->xmlData['definition']['objectType']);
157       }
158       foreach ($this->xmlData['definition']['objectType'] as $index => $otype) {
159         $this->objectTypes[]= $this->xmlData['definition']['objectType'][$index];
160         if (isset($this->xmlData['definition']['objectType'][$index]['category'])){
161           $this->categories[]= $this->xmlData['definition']['objectType'][$index]['category'];
162         }
163       }
164     }
166     // Parse layout per column
167     $this->colprops= $this->parseLayout($this->xmlData['table']['layout']);
169     // Prepare table headers
170     $this->renderHeader();
172     // Assign headline/module
173     $this->headline= _($this->xmlData['definition']['label']);
174     $this->module= $this->xmlData['definition']['module'];
175     if (!is_array($this->categories)){
176       $this->categories= array($this->categories);
177     }
179     // Evaluate columns to be exported
180     if (isset($this->xmlData['table']['column'])){
181       foreach ($this->xmlData['table']['column'] as $index => $config) {
182         if (isset($config['export']) && $config['export'] == "true"){
183           $this->exportColumns[]= $index;
184         }
185       }
186     }
188     return true;  
189   }
192   function renderHeader()
193   {
194     $this->header= array();
195     $this->plainHeader= array();
197     // Initialize sort?
198     $sortInit= false;
199     if (!$this->sortDirection) {
200       $this->sortColumn= 0;
201       if (isset($this->xmlData['definition']['defaultSortColumn'])){
202         $this->sortColumn= $this->xmlData['definition']['defaultSortColumn'];
203       } else {
204         $this->sortAttribute= "";
205       }
206       $this->sortDirection= array();
207       $sortInit= true;
208     }
210     if (isset($this->xmlData['table']['column'])){
211       foreach ($this->xmlData['table']['column'] as $index => $config) {
212         // Initialize everything to one direction
213         if ($sortInit) {
214           $this->sortDirection[$index]= false;
215         }
217         $sorter= "";
218         if ($index == $this->sortColumn && isset($config['sortAttribute']) &&
219             isset($config['sortType'])) {
220           $this->sortAttribute= $config['sortAttribute'];
221           $this->sortType= $config['sortType'];
222           $sorter= "&nbsp;<img border='0' title='".($this->sortDirection[$index]?_("Up"):_("Down"))."' src='images/lists/sort-".($this->sortDirection[$index]?"up":"down").".png' align='top'>";
223         }
224         $sortable= (isset($config['sortAttribute']));
226         $link= "href='?plug=".$_GET['plug']."&amp;PID=".$this->pid."&amp;act=SORT_$index'";
227         if (isset($config['label'])) {
228           if ($sortable) {
229             $this->header[$index]= "<td class='listheader' ".$this->colprops[$index]."><a $link>"._($config['label'])."$sorter</a></td>";
230           } else {
231             $this->header[$index]= "<td class='listheader' ".$this->colprops[$index].">"._($config['label'])."</td>";
232           }
233           $this->plainHeader[]= _($config['label']);
234         } else {
235           if ($sortable) {
236             $this->header[$index]= "<td class='listheader' ".$this->colprops[$index]."><a $link>&nbsp;$sorter</a></td>";
237           } else {
238             $this->header[$index]= "<td class='listheader' ".$this->colprops[$index].">&nbsp;</td>";
239           }
240           $this->plainHeader[]= "";
241         }
242       }
243     }
244   }
246   function render()
247   {
248     // Check for exeeded sizelimit
249     if (($message= check_sizelimit()) != ""){
250       return($message);
251     }
253     // Initialize list
254     $result= "<input type='hidden' value='$this->pid' name='PID'>\n";
255     $result.= "<div class='contentboxb' id='listing_container' style='border-top:1px solid #B0B0B0;'>\n";
256     $result.= "<table summary='$this->headline' style='width:600px;height:450px;' cellspacing='0' id='t_scrolltable'>
257 <tr><td class='scrollhead'><table summary='' style='width:100%;' cellspacing='0' id='t_scrollhead'>\n";
258     $this->numColumns= count($this->colprops) + ($this->multiSelect?1:0);
260     // Build list header
261     $result.= "<tr>\n";
262     if ($this->multiSelect) {
263       $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";
264     }
265     foreach ($this->header as $header) {
266       $result.= $header;
267     }
269     // Add 13px for scroller
270     $result.= "<td class='listheader' style='width:13px;border-right:0px;'>&nbsp;</td></table></td></tr>\n";
272     // New table for the real list contents
273     $result.= "<tr><td colspan='$this->numColumns' class='scrollbody'><div style='width:600px;height:430px;' id='d_scrollbody' class='scrollbody'><table summary='' style='height:100%;width:581px;' cellspacing='0' id='t_scrollbody'>\n";
275     // No results? Just take an empty colspanned row
276     if (count($this->entries) + count($this->departments) == 0) {
277       $result.= "<tr class='rowxp0'><td class='list1nohighlight' colspan='$this->numColumns' style='height:100%;border-right:0px;width:100%;'>&nbsp;</td></tr>";
278     }
280     // Line color alternation
281     $alt= 0;
282     $deps= 0;
284     // Draw department browser if configured and we're not in sub mode
285     if ($this->departmentBrowser && $this->filter->scope != "sub") {
286       // Fill with department browser if configured this way
287       $departmentIterator= new departmentSortIterator($this->departments, $this->sortDirection[$this->sortColumn]);
288       foreach ($departmentIterator as $row => $entry){
289         $result.="<tr class='rowxp".($alt&1)."'>";
291         // Render multi select if needed
292         if ($this->multiSelect) {
293           $result.="<td style='text-align:center;width:20px;' class='list1'>&nbsp;</td>";
294         }
296         // Render defined department columns, fill the rest with some stuff
297         $rest= $this->numColumns - 1;
298         foreach ($this->xmlData['table']['department'] as $index => $config) {
299           $colspan= 1;
300           if (isset($config['span'])){
301             $colspan= $config['span'];
302           }
303           $result.="<td colspan='$colspan' ".$this->colprops[$index]." class='list1'>".$this->renderCell($config['value'], $entry, $row)."</td>";
304           $rest-= $colspan;
305         }
307         // Fill remaining cols with nothing
308         $last= $this->numColumns - $rest;
309         for ($i= 0; $i<$rest; $i++){
310           $result.= "<td ".$this->colprops[$last+$i-1]." class='list1'>&nbsp;</td>";
311         }
312         $result.="</tr>";
314         $alt++;
315       }
316       $deps= $alt;
317     }
319     // Fill with contents, sort as configured
320     foreach ($this->entries as $row => $entry) {
321       $trow= "";
323       // Render multi select if needed
324       if ($this->multiSelect) {
325         $trow.="<td style='text-align:center;width:20px;' class='list0'><input type='checkbox' id='listing_selected_$row' name='listing_selected_$row'></td>\n";
326       }
328       foreach ($this->xmlData['table']['column'] as $index => $config) {
329         $renderedCell= $this->renderCell($config['value'], $entry, $row);
330         $trow.="<td ".$this->colprops[$index]." class='list0'>".$renderedCell."</td>\n";
332         // Save rendered column
333         $sort= preg_replace('/.*>([^<]+)<.*$/', '$1', $renderedCell);
334         $sort= preg_replace('/&nbsp;/', '', $sort);
335         if (preg_match('/</', $sort)){
336           $sort= "";
337         }
338         $this->entries[$row]["_sort$index"]= $sort;
339       }
341       // Save rendered entry
342       $this->entries[$row]['_rendered']= $trow;
343     }
345     // Complete list by sorting entries for _sort$index and appending them to the output
346     $entryIterator= new listingSortIterator($this->entries, $this->sortDirection[$this->sortColumn], "_sort".$this->sortColumn, $this->sortType);
347     foreach ($entryIterator as $row => $entry){
348       $alt++;
349       $result.="<tr class='rowxp".($alt&1)."'>\n";
350       $result.= $entry['_rendered'];
351       $result.="</tr>\n";
352     }
354     // Need to fill the list if it's not full (nobody knows why this is 22 ;-))
355     $emptyListStyle= (count($this->entries) + $deps == 0)?"border:0;":"";
356     if ((count($this->entries) + $deps) < 22) {
357       $result.= "<tr>";
358       for ($i= 0; $i<$this->numColumns; $i++) {
359         if ($i == 0) {
360           $result.= "<td class='list1nohighlight' style='$emptyListStyle height:100%;'>&nbsp;</td>";
361           continue;
362         }
363         if ($i != $this->numColumns-1) {
364           $result.= "<td class='list1nohighlight' style='$emptyListStyle'>&nbsp;</td>";
365         } else {
366           $result.= "<td class='list1nohighlight' style='border-right:1px solid #AAA;$emptyListStyle'>&nbsp;</td>";
367         }
368       }
369       $result.= "</tr>";
370     }
372     $result.= "</table></div></td></tr>";
374     // Add the footer if requested
375     if ($this->showFooter) {
376       $result.= "<tr><td class='scrollhead'><table summary='' style='width:100%' cellspacing='0' id='t_scrollfoot'><tr><td class='listfooter' style='border-bottom:0px;'>";
378       foreach ($this->objectTypes as $objectType) {
379         if (isset($this->objectTypeCount[$objectType['label']])) {
380           $label= _($objectType['label']);
381           $result.= "<img class='center' src='".$objectType['image']."' title='$label' alt='$label'>&nbsp;".$this->objectTypeCount[$objectType['label']]."&nbsp;&nbsp;&nbsp;&nbsp;";
382         }
383       }
385       $result.= "<td class='listfooter' style='width:13px;border-right:0px;'>&nbsp;</td></table></td></tr>";
386     }
388     $result.= "</table></div>";
390     $smarty= get_smarty();
391     $smarty->assign("FILTER", $this->filter->render());
392     $smarty->assign("SIZELIMIT", print_sizelimit_warning());
393     $smarty->assign("LIST", $result);
395     // Assign navigation elements
396     $nav= $this->renderNavigation();
397     foreach ($nav as $key => $html) {
398       $smarty->assign($key, $html);
399     }
401     // Assign action menu / base
402     $smarty->assign("ACTIONS", $this->renderActionMenu());
403     $smarty->assign("BASE", $this->renderBase());
405     // Assign separator
406     $smarty->assign("SEPARATOR", "<img src='images/lists/seperator.png' alt='-' align='middle' height='16' width='1' class='center'>");
408     // Assign summary
409     $smarty->assign("HEADLINE", $this->headline);
411     return ($smarty->fetch(get_template_path($this->xmlData['definition']['template'], true)));
412   }
415   function update()
416   {
417     global $config;
418     $ui= get_userinfo();
420     // Reset object counter
421     $this->objectTypeCount= array();
423     // Do not do anything if this is not our PID
424     if(isset($_REQUEST['PID']) && $_REQUEST['PID'] != $this->pid) {
425       return;
426     }
428     // Save base
429     if (isset($_POST['BASE']) && $this->baseMode == true) {
430       $base= validate($_POST['BASE']);
431       if (isset($this->bases[$base])) {
432         $this->base= $base;
433       }
434     }
436     // Override the base if we got a message from the browser navigation
437     if ($this->departmentBrowser && isset($_GET['act'])) {
438       if (preg_match('/^department_([0-9]+)$/', validate($_GET['act']), $match)){
439         if (isset($this->departments[$match[1]])){
440           $this->base= $this->departments[$match[1]]['dn'];
441         }
442       }
443     }
445     // Filter POST with "act" attributes -> posted from action menu
446     if (isset($_POST['exec_act']) && $_POST['act'] != '') {
447       if (preg_match('/^export.*$/', $_POST['act']) && isset($this->exporter[$_POST['act']])) {
448         $exporter= $this->exporter[$_POST['act']];
449         $userinfo= ", "._("created by")." ".$ui->cn." - ".strftime('%A, %d. %B %Y, %H:%M:%S');
450         $instance= new $exporter['class']($this->headline.$userinfo, $this->plainHeader, $this->entries, $this->exportColumns);
451         $type= call_user_func(array($exporter['class'], "getInfo"));
452         $type= $type[$_POST['act']];
453         send_binary_content($instance->query(), $type['filename'], $type= $type['mime']);
454       }
455     }
457     // Filter GET with "act" attributes
458     if (isset($_GET['act'])) {
459       $key= validate($_GET['act']);
460       if (preg_match('/^SORT_([0-9]+)$/', $key, $match)) {
461         // Switch to new column or invert search order?
462         $column= $match[1];
463         if ($this->sortColumn != $column) {
464           $this->sortColumn= $column;
465         } else {
466           $this->sortDirection[$column]= !$this->sortDirection[$column];
467         }
469         // Allow header to update itself according to the new sort settings
470         $this->renderHeader();
471       }
472     }
474     // Override base if we got signals from the navigation elements
475     $action= "";
476     foreach ($_POST as $key => $value) {
477       if (preg_match('/^(ROOT|BACK|HOME)_x$/', $key, $match)) {
478         $action= $match[1];
479         break;
480       }
481     }
483     // Navigation handling
484     if ($action == 'ROOT') {
485       $deps= $ui->get_module_departments($this->module);
486       $this->base= $deps[0];
487     }
488     if ($action == 'BACK') {
489       $deps= $ui->get_module_departments($this->module);
490       $base= preg_replace("/^[^,]+,/", "", $this->base);
491       if(in_array_ics($base, $deps)){
492         $this->base= $base;
493       }
494     }
495     if ($action == 'HOME') {
496       $ui= get_userinfo();
497       $this->base= get_base_from_people($ui->dn);
498     }
500     // Reload departments
501     if ($this->departmentBrowser){
502       $this->departments= $this->getDepartments();
503     }
505     // Update filter and refresh entries
506     $this->filter->setBase($this->base);
507     $this->entries= $this->filter->query();
508   }
511   function setBase($base)
512   {
513     $this->base= $base;
514   }
517   function getBase()
518   {
519     return $this->base;
520   }
523   function parseLayout($layout)
524   {
525     $result= array();
526     $layout= preg_replace("/^\|/", "", $layout);
527     $layout= preg_replace("/\|$/", "", $layout);
528     $cols= split("\|", $layout);
529     foreach ($cols as $index => $config) {
530       if ($config != "") {
531         $components= split(';', $config);
532         $config= "";
533         foreach ($components as $part) {
534           if (preg_match("/^r$/", $part)) {
535             $config.= "text-align:right;";
536             continue;
537           }
538           if (preg_match("/^l$/", $part)) {
539             $config.= "text-align:left;";
540             continue;
541           }
542           if (preg_match("/^c$/", $part)) {
543             $config.= "text-align:center;";
544             continue;
545           }
546           if (preg_match("/^[0-9]+(|px|%)$/", $part)) {
547             $config.= "width:$part;";
548             continue;
549           }
550         }
552         $result[$index]= " style='$config' ";
553       } else {
554         $result[$index]= null;
555       }
556     }
558     // Save number of columns for later use
559     $this->numColumns= count($cols);
561     return $result;
562   }
565   function renderCell($data, $config, $row)
566   {
567     // Replace flat attributes in data string
568     for ($i= 0; $i<$config['count']; $i++) {
569       $attr= $config[$i];
570       $value= "";
571       if (is_array($config[$attr])) {
572         $value= $config[$attr][0];
573       } else {
574         $value= $config[$attr];
575       }
576       $data= preg_replace("/%\{$attr\}/", $value, $data);
577     }
579     // Watch out for filters and prepare to execute them
580     $data= $this->processElementFilter($data, $config, $row);
582     // Replace all non replaced %{...} instances because they
583     // are non resolved attributes or filters
584     $data= preg_replace('/%{[^}]+}/', '&nbsp;', $data);
586     return $data;
587   }
590   function renderBase()
591   {
592     $result= "<select name='BASE' onChange='mainform.submit()' size='1'>";
593     $firstDN= null;
594     $found= false;
596     foreach ($this->bases as $key=>$value) {
597       // Keep first entry to fall back eventually
598       if(!$firstDN) {
599         $firstDN= $key;
600       }
602       // Prepare to render entry
603       $selected= "";
604       if ($key == $this->base) {
605         $selected= " selected";
606         $found= true;
607       }
608       $result.= "<option value='".$key."'$selected>".$value."</option>";
609     }
610     $result.= "</select>";
612     // Reset the currently used base to the first DN we found if there
613     // was no match.
614     if(!$found){
615       $this->base = $firstDN;
616     }
618     return $result;
619   }
622   function processElementFilter($data, $config, $row)
623   {
624     preg_match_all("/%\{filter:([^(]+)\((.*)\)\}/", $data, $matches, PREG_SET_ORDER);
626     foreach ($matches as $match) {
627       if (!isset($this->filters[$match[1]])) {
628         continue;
629       }
630       $cl= preg_replace('/::.*$/', '', $this->filters[$match[1]]);
631       $method= preg_replace('/^.*::/', '', $this->filters[$match[1]]);
633       // Prepare params for function call
634       $params= array();
635       preg_match_all('/"[^"]+"|[^,]+/', $match[2], $parts);
636       foreach ($parts[0] as $param) {
638         // Row is replaced by the row number
639         if ($param == "row") {
640           $params[]= $row;
641         }
643         // pid is replaced by the current PID
644         if ($param == "pid") {
645           $params[]= $this->pid;
646         }
648         // Fixie with "" is passed directly
649         if (preg_match('/^".*"$/', $param)){
650           $params[]= preg_replace('/"/', '', $param);
651         }
653         // LDAP variables get replaced by their objects
654         for ($i= 0; $i<$config['count']; $i++) {
655           if ($param == $config[$i]) {
656             $values= $config[$config[$i]];
657             if (is_array($values)){
658               unset($values['count']);
659             }
660             $params[]= $values;
661           }
662         }
664         // Move dn if needed
665         if ($param == "dn") {
666           $params[]= LDAP::fix($config["dn"]);
667         }
668       }
670       // Replace information
671       if ($cl == "listing") {
672         // Non static call - seems to result in errors
673         $data= @preg_replace('/'.preg_quote($match[0]).'/', call_user_func_array(array($this, "$method"), $params), $data);
674       } else {
675         // Static call
676         $data= preg_replace('/'.preg_quote($match[0]).'/', call_user_func_array(array($cl, $method), $params), $data);
677       }
678     }
680     return $data;
681   }
684   function getObjectType($types, $classes)
685   {
686     // Walk thru types and see if there's something matching
687     foreach ($types as $objectType) {
688       $ocs= $objectType['objectClass'];
689       if (!is_array($ocs)){
690         $ocs= array($ocs);
691       }
693       $found= true;
694       foreach ($ocs as $oc){
695         if (preg_match('/^!(.*)$/', $oc, $match)) {
696           $oc= $match[1];
697           if (in_array($oc, $classes)) {
698             $found= false;
699           }
700         } else {
701           if (!in_array($oc, $classes)) {
702             $found= false;
703           }
704         }
705       }
707       if ($found) {
708         return $objectType;
709       }
710     }
712     return null;
713   }
716   function filterObjectType($dn, $classes)
717   {
718     // Walk thru classes and return on first match
719     $result= "&nbsp;";
721     $objectType= $this->getObjectType($this->objectTypes, $classes);
722     if ($objectType) {
723       $result= "<img class='center' title='".LDAP::fix($dn)."' src='".$objectType["image"]."'>";
724       if (!isset($this->objectTypeCount[$objectType['label']])) {
725         $this->objectTypeCount[$objectType['label']]= 0;
726       }
727       $this->objectTypeCount[$objectType['label']]++;
728     }
729     return $result;
730   }
733   function filterActions($dn, $row, $classes)
734   {
735     // Do nothing if there's no menu defined
736     if (!isset($this->xmlData['actiontriggers']['action'])) {
737       return "&nbsp;";
738     }
740     // Go thru all actions
741     $result= "";
742     $actions= $this->xmlData['actiontriggers']['action'];
743     foreach($actions as $action) {
744       // Skip the entry completely if there's no permission to execute it
745       if (!$this->hasActionPermission($action, $dn)) {
746         continue;
747       }
749       // If there's an objectclass definition and we don't have it
750       // add an empty picture here.
751       if (isset($action['objectclass'])){
752         $objectclass= $action['objectclass'];
753         if (preg_match('/^!(.*)$/', $objectclass, $m)){
754           $objectclass= $m[1];
755           if(in_array($objectclass, $classes)) {
756             $result.= "<img src='images/empty.png' alt=' ' class='center' style='padding:1px'>";
757             continue;
758           }
759         } else {
760           if(!in_array($objectclass, $classes)) {
761             $result.= "<img src='images/empty.png' alt=' ' class='center' style='padding:1px'>";
762             continue;
763           }
764         }
765       }
767       // Render normal entries as usual
768       if ($action['type'] == "entry") {
769         $label= $this->processElementFilter($action['label'], $this->entries[$row], $row);
770         $image= $this->processElementFilter($action['image'], $this->entries[$row], $row);
771         $result.="<input class='center' type='image' src='$image' title='$label' ".
772                  "name='listing_".$action['name']."_$row' style='padding:1px'>";
773       }
775       // Handle special types
776       if ($action['type'] == "copypaste" || $action['type'] == "snapshot") {
778         $objectType= $this->getObjectType($this->objectTypes, $this->entries[$row]['objectClass']);
779         $category= $class= null;
780         if ($objectType) {
781           $category= $objectType['category'];
782           $class= $objectType['class'];
783         }
785         if ($action['type'] == "copypaste") {
786           $result.= $this->renderCopyPasteActions($row, $this->entries[$row]['dn'], $category, $class);
787         } else {
788           $result.= $this->renderSnapshotActions($row, $this->entries[$row]['dn'], $category, $class);
789         }
790       }
791     }
793     return $result;
794   }
797   function filterDepartmentLink($row, $dn, $description)
798   {
799     $attr= $this->departments[$row]['sort-attribute'];
800     $name= $this->departments[$row][$attr];
801     if (is_array($name)){
802       $name= $name[0];
803     }
804     $result= sprintf("%s [%s]", $name, $description[0]);
805     return("<a href='?plug=".$_GET['plug']."&amp;PID=$this->pid&amp;act=department_$row' title='$dn'>$result</a>");
806   }
809   function filterLink()
810   {
811     $result= "&nbsp;";
813     $row= func_get_arg(0);
814     $pid= $this->pid;
815     $dn= LDAP::fix(func_get_arg(1));
816     $params= array(func_get_arg(2));
818     // Collect sprintf params
819     for ($i = 3;$i < func_num_args();$i++) {
820       $val= func_get_arg($i);
821       if (is_array($val)){
822         $params[]= $val[0];
823         continue;
824       }
825       $params[]= $val;
826     }
828     $result= "&nbsp;";
829     $trans= call_user_func_array("sprintf", $params);
830     if ($trans != "") {
831       return("<a href='?plug=".$_GET['plug']."&amp;PID=$pid&amp;act=listing_edit_$row' title='$dn'>$trans</a>");
832     }
834     return $result;
835   }
838   function renderNavigation()
839   {
840     $result= array();
841     $enableBack = true;
842     $enableRoot = true;
843     $enableHome = true;
845     $ui = get_userinfo();
847     /* Check if base = first available base */
848     $deps = $ui->get_module_departments($this->module);
850     if(!count($deps) || $deps[0] == $this->filter->base){
851       $enableBack = false;
852       $enableRoot = false;
853     }
855     $listhead ="";
857     /* Check if we are in users home  department */
858     if(!count($deps) ||$this->filter->base == get_base_from_people($ui->dn)){
859       $enableHome = false;
860     }
862     /* Draw root button */
863     if($enableRoot){
864       $result["ROOT"]= "<input class='center' type='image' src='images/lists/root.png' align='middle' ".
865                        "title='"._("Go to root department")."' name='ROOT' alt='"._("Root")."'>";
866     }else{
867       $result["ROOT"]= "<img src='images/lists/root_grey.png' class='center' alt='"._("Root")."'>";
868     }
870     /* Draw back button */
871     if($enableBack){
872       $result["BACK"]= "<input class='center' type='image' align='middle' src='images/lists/back.png' ".
873                        "title='"._("Go up one department")."' alt='"._("Up")."' name='BACK'>";
874     }else{
875       $result["BACK"]= "<img src='images/lists/back_grey.png' class='center' alt='"._("Up")."'>";
876     }
878     /* Draw home button */
879     if($enableHome){
880       $result["HOME"]= "<input class='center' type='image' align='middle' src='images/lists/home.png' ".
881                        "title='"._("Go to users department")."' alt='"._("Home")."' name='HOME'>";
882     }else{
883       $result["HOME"]= "<img src='images/lists/home_grey.png' class='center' alt='"._("Home")."'>";
884     }
886     /* Draw reload button, this button is enabled everytime */
887     $result["RELOAD"]= "<input class='center' type='image' src='images/lists/reload.png' align='middle' ".
888                        "title='"._("Reload list")."' name='REFRESH' alt='"._("Submit")."'>";
890     return ($result);
891   }
894   function getAction()
895   {
896     // Do not do anything if this is not our PID
897     if(isset($_REQUEST['PID']) && $_REQUEST['PID'] != $this->pid) {
898       return;
899     }
901     $result= array("targets" => array(), "action" => "");
903     // Filter GET with "act" attributes
904     if (isset($_GET['act'])) {
905       $key= validate($_GET['act']);
906       $target= preg_replace('/^listing_[a-zA-Z_]+_([0-9]+)$/', '$1', $key);
907       if (isset($this->entries[$target]['dn'])) {
908         $result['action']= preg_replace('/^listing_([a-zA-Z_]+)_[0-9]+$/', '$1', $key);
909         $result['targets'][]= $this->entries[$target]['dn'];
910       }
912       // Drop targets if empty
913       if (count($result['targets']) == 0) {
914         unset($result['targets']);
915       }
916       return $result;
917     }
919     // Filter POST with "listing_" attributes
920     foreach ($_POST as $key => $prop) {
922       // Capture selections
923       if (preg_match('/^listing_selected_[0-9]+$/', $key)) {
924         $target= preg_replace('/^listing_selected_([0-9]+)$/', '$1', $key);
925         if (isset($this->entries[$target]['dn'])) {
926           $result['targets'][]= $this->entries[$target]['dn'];
927         }
928         continue;
929       }
931       // Capture action with target - this is a one shot
932       if (preg_match('/^listing_[a-zA-Z_]+_[0-9]+(|_x)$/', $key)) {
933         $target= preg_replace('/^listing_[a-zA-Z_]+_([0-9]+)(|_x)$/', '$1', $key);
934         if (isset($this->entries[$target]['dn'])) {
935           $result['action']= preg_replace('/^listing_([a-zA-Z_]+)_[0-9]+(|_x)$/', '$1', $key);
936           $result['targets']= array($this->entries[$target]['dn']);
937         }
938         break;
939       }
941       // Capture action without target
942       if (preg_match('/^listing_[a-zA-Z_]+(|_x)$/', $key)) {
943         $result['action']= preg_replace('/^listing_([a-zA-Z_]+)(|_x)$/', '$1', $key);
944         continue;
945       }
946     }
948     // Filter POST with "act" attributes -> posted from action menu
949     if (isset($_POST['act']) && $_POST['act'] != '') {
950       if (!preg_match('/^export.*$/', $_POST['act'])){
951         $result['action']= validate($_POST['act']);
952       }
953     }
955     // Drop targets if empty
956     if (count($result['targets']) == 0) {
957       unset($result['targets']);
958     }
959     return $result;
960   }
963   function renderActionMenu()
964   {
965     // Don't send anything if the menu is not defined
966     if (!isset($this->xmlData['actionmenu']['action'])){
967       return "";
968     }
970     // Load shortcut
971     $actions= &$this->xmlData['actionmenu']['action'];
972     $result= "<input type='hidden' name='act' id='actionmenu' value=''><div style='display:none'><input type='submit' name='exec_act' id='exec_act' value=''></div>".
973              "<ul class='level1' id='root'><li><a href='#'>Aktionen&nbsp;<img ".
974              "border=0 class='center' src='images/lists/sort-down.png'></a>";
976     // Build ul/li list
977     $result.= $this->recurseActions($actions);
979     return "<div id='pulldown'>".$result."</li></ul><div>";
980   }
983   function recurseActions($actions)
984   {
985     static $level= 2;
986     $result= "<ul class='level$level'>";
987     $separator= "";
989     foreach ($actions as $action) {
991       // Skip the entry completely if there's no permission to execute it
992       if (!$this->hasActionPermission($action, $this->filter->base)) {
993         continue;
994       }
996       // Fill image if set
997       $img= "";
998       if (isset($action['image'])){
999         $img= "<img border='0' class='center' src='".$action['image']."'>&nbsp;";
1000       }
1002       if ($action['type'] == "separator"){
1003         $separator= " style='border-top:1px solid #AAA' ";
1004         continue;
1005       }
1007       // Dive into subs
1008       if ($action['type'] == "sub" && isset($action['action'])) {
1009         $level++;
1010         if (isset($action['label'])){
1011           $result.= "<li$separator><a href='#'>$img"._($action['label'])."&nbsp;<img border='0' src='images/forward-arrow.png'></a>";
1012         }
1013         $result.= $this->recurseActions($action['action'])."</li>";
1014         $level--;
1015         $separator= "";
1016         continue;
1017       }
1019       // Render entry elseways
1020       if (isset($action['label'])){
1021         $result.= "<li$separator><a href='#' onClick='document.getElementById(\"actionmenu\").value= \"".$action['name']."\";mainform.submit();'>$img"._($action['label'])."</a></li>";
1022       }
1024       // Check for special types
1025       switch ($action['type']) {
1026         case 'copypaste':
1027           $result.= $this->renderCopyPasteMenu($separator);
1028           break;
1030         case 'snapshot':
1031           $result.= $this->renderSnapshotMenu($separator);
1032           break;
1034         case 'exporter':
1035           $result.= $this->renderExporterMenu($separator);
1036           break;
1038         case 'daemon':
1039           $result.= $this->renderDaemonMenu($separator);
1040           break;
1041       }
1043       $separator= "";
1044     }
1046     $result.= "</ul>";
1047     return $result;
1048   }
1051   function hasActionPermission($action, $dn)
1052   {
1053     $ui= get_userinfo();
1055     if (isset($action['acl'])) {
1056       $acls= $action['acl'];
1057       if (!is_array($acls)) {
1058         $acls= array($acls);
1059       }
1061       // Every ACL has to pass
1062       foreach ($acls as $acl) {
1063         $module= $this->module;
1064         $aclList= array();
1066         // Split for category and plugins if needed
1067         // match for "[rw]" style entries
1068         if (preg_match('/^\[([rwcdm]+)\]$/', $acl, $match)){
1069           $aclList= array($match[1]);
1070         }
1072         // match for "users[rw]" style entries
1073         if (preg_match('/^([a-zA-Z0-9]+)\[([rwcdm]+)\]$/', $acl, $match)){
1074           $module= $match[1];
1075           $aclList= array($match[2]);
1076         }
1078         // match for "users/user[rw]" style entries
1079         if (preg_match('/^([a-zA-Z0-9]+\/[a-zA-Z0-9]+)\[([rwcdm]+)\]$/', $acl, $match)){
1080           $module= $match[1];
1081           $aclList= array($match[2]);
1082         }
1084         // match "users/user[userPassword:rw(,...)*]" style entries
1085         if (preg_match('/^([a-zA-Z0-9]+\/[a-zA-Z0-9]+)\[([a-zA-Z0-9]+:[rwcdm]+(,[a-zA-Z0-9]+:[rwcdm]+)*)\]$/', $acl, $match)){
1086           $module= $match[1];
1087           $aclList= split(',', $match[2]);
1088         }
1090         // Walk thru prepared ACL by using $module
1091         foreach($aclList as $sAcl) {
1092           $checkAcl= "";
1094           // Category or detailed permission?
1095           if (strpos('/', $module) === false) {
1096             if (preg_match('/([a-zA-Z0-9]+):([rwcdm]+)/', $sAcl, $m) ) {
1097               $checkAcl= $ui->get_permissions($dn, $module, $m[1]);
1098               $sAcl= $m[2];
1099             } else {
1100               $checkAcl= $ui->get_permissions($dn, $module, '0');
1101             }
1102           } else {
1103             $checkAcl= $ui->get_category_permissions($dn, $module);
1104           }
1106           // Split up remaining part of the acl and check if it we're
1107           // allowed to do something...
1108           $parts= str_split($sAcl);
1109           foreach ($parts as $part) {
1110             if (strpos($checkAcl, $part) === false){
1111               return false;
1112             }
1113           }
1115         }
1116       }
1117     }
1119     return true;
1120   }
1123   function refreshBasesList()
1124   {
1125     global $config;
1126     $ui= get_userinfo();
1128     // Do some array munching to get it user friendly
1129     $ids= $config->idepartments;
1130     $d= $ui->get_module_departments($this->module);
1131     $k_ids= array_keys($ids);
1132     $deps= array_intersect($d,$k_ids);
1134     // Fill internal bases list
1135     $this->bases= array();
1136     foreach($k_ids as $department){
1137       $this->bases[$department] = $ids[$department];
1138     }
1139   }
1142   function getDepartments()
1143   {
1144     $departments= array();
1145     $ui= get_userinfo();
1147     // Get list of supported department types
1148     $types = departmentManagement::get_support_departments();
1150     // Load departments allowed by ACL
1151     $validDepartments = $ui->get_module_departments($this->module);
1153     // Build filter and look in the LDAP for possible sub departments
1154     // of current base
1155     $filter= "(&(objectClass=gosaDepartment)(|";
1156     $attrs= array("description", "objectClass");
1157     foreach($types as $name => $data){
1158       $filter.= "(objectClass=".$data['OC'].")";
1159       $attrs[]= $data['ATTR'];
1160     }
1161     $filter.= "))";
1162     $res= get_list($filter, $this->module, $this->base, $attrs, GL_NONE | GL_SIZELIMIT);
1164     // Analyze list of departments
1165     foreach ($res as $department) {
1166       if (!in_array($department['dn'], $validDepartments)) {
1167         continue;
1168       }
1170       // Add the attribute where we use for sorting
1171       $oc= null;
1172       foreach(array_keys($types) as $type) {
1173         if (in_array($type, $department['objectClass'])) {
1174           $oc= $type;
1175           break;
1176         }
1177       }
1178       $department['sort-attribute']= $types[$oc]['ATTR'];
1180       // Move to the result list
1181       $departments[]= $department;
1182     }
1184     return $departments;
1185   }
1188   function renderCopyPasteMenu($separator, $copy= true, $cut= true)
1189   {
1190     // We can only provide information if we've got a copypaste handler
1191     // instance
1192     if(!(isset($this->copyPasteHandler) && is_object($this->copyPasteHandler))){
1193       return "";
1194     }
1196     // Presets
1197     $result= "";
1198     $read= $paste= false;
1199     $ui= get_userinfo();
1201     // Switch flags to on if there's at least one category which allows read/paste
1202     foreach($this->categories as $category){
1203       $read= $read || preg_match('/r/', $ui->get_category_permissions($this->base, $category));
1204       $paste= $paste || $ui->is_pasteable($this->base, $category) == 1;
1205     }
1208     // Draw entries that allow copy and cut
1209     if($read){
1211       // Copy entry
1212       if($copy){
1213         $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>";
1214         $separator= "";
1215       }
1217       // Cut entry
1218       if($cut){
1219         $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>";
1220         $separator= "";
1221       }
1222     }
1224     // Draw entries that allow pasting entries
1225     if($paste){
1226       if($this->copyPasteHandler->entries_queued()){
1227         $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>";
1228       }else{
1229         $result.= "<li$separator><a href='#'><img src='images/lists/paste-grey.png' alt='' border='0' class='center'>&nbsp;"._("Paste")."</a></li>";
1230       }
1231     }
1232     
1233     return($result);
1234   }
1237   function renderCopyPasteActions($row, $dn, $category, $class, $copy= true, $cut= true)
1238   {
1239     // We can only provide information if we've got a copypaste handler
1240     // instance
1241     if(!(isset($this->copyPasteHandler) && is_object($this->copyPasteHandler))){
1242       return "";
1243     }
1245     // Presets
1246     $ui = get_userinfo();
1247     $result = "";
1249     // Render cut entries
1250     if($cut){
1251       if($ui->is_cutable($dn, $category, $class)){
1252         $result .= "<input class='center' type='image'
1253           src='images/lists/cut.png' alt='"._("Cut")."' name='listing_cut_$row' title='"._("Cut this entry")."' style='padding:1px'>";
1254       }else{
1255         $result.="<img src='images/empty.png' alt=' ' class='center' style='padding:1px'>";
1256       }
1257     }
1259     // Render copy entries
1260     if($copy){
1261       if($ui->is_copyable($dn, $category, $class)){
1262         $result.= "<input class='center' type='image'
1263           src='images/lists/copy.png' alt='"._("Copy")."' name='listing_copy_$row' title='"._("Copy this entry")."' style='padding:1px'>";
1264       }else{
1265         $result.="<img src='images/empty.png' alt=' ' class='center' style='padding:1px'>";
1266       }
1267     }
1269     return($result);
1270   }
1273   function renderSnapshotMenu($separator)
1274   {
1275     // We can only provide information if we've got a snapshot handler
1276     // instance
1277     if(!(isset($this->snapshotHandler) && is_object($this->snapshotHandler))){
1278       return "";
1279     }
1281     // Presets
1282     $result = "";
1283     $ui = get_userinfo();
1285     if($this->snapshotHandler->enabled() && $ui->allow_snapshot_restore($this->base, $this->module)){
1287       // Check if there is something to restore
1288       $restore= false;
1289       foreach($this->snapshotHandler->getSnapshotBases() as $base){
1290         $restore= $restore || count($this->snapshotHandler->getDeletedSnapshots($base)) > 0;
1291       }
1293       // Draw icons according to the restore flag
1294       if($restore){
1295         $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>";
1296       }else{
1297         $result.= "<li$separator><a href='#'><img src='images/lists/restore_grey.png' alt='' border='0' class='center'>&nbsp;"._("Restore snapshots")."</a></li>";
1298       }
1299     }
1301     return($result);
1302   }
1305   function renderExporterMenu($separator)
1306   {
1307     // Presets
1308     $result = "";
1310     // Draw entries
1311     $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'>";
1313     // Export CVS as build in exporter
1314     foreach ($this->exporter as $action => $exporter) {
1315       $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>";
1316     }
1318     // Finalize list
1319     $result.= "</ul></li>";
1321     return($result);
1322   }
1325   function renderSnapshotActions($row, $dn, $category, $class, $copy= true, $cut= true)
1326   {
1327     // We can only provide information if we've got a snapshot handler
1328     // instance
1329     if(!(isset($this->snapshotHandler) && is_object($this->snapshotHandler))){
1330       return "";
1331     }
1333     // Presets
1334     $result= "";
1335     $ui = get_userinfo();
1337     // Only act if enabled here
1338     if($this->snapshotHandler->enabled()){
1340       // Draw restore button
1341       if ($ui->allow_snapshot_restore($dn, $category)){
1343         // Do we have snapshots for this dn?
1344         if($this->snapshotHandler->hasSnapshots($dn)){
1345           $result.= "<input class='center' type='image' src='images/lists/restore.png' ".
1346                      "alt='"._("Restore snapshot")."' name='listing_restore_$row' title='".
1347                      _("Restore snapshot")."' style='padding:1px'>";
1348         } else {
1349           $result.= "<img src='images/lists/restore_grey.png' alt=' ' class='center' style='padding:1px'>";
1350         }
1351       }
1353       // Draw snapshot button
1354       if($ui->allow_snapshot_create($dn, $category)){
1355           $result.= "<input class='center' type='image' src='images/snapshot.png' ".
1356                      "alt='"._("Create snapshot")."' name='listing_snapshot_$row' title='".
1357                      _("Create a new snapshot from this object")."' style='padding:1px'>";
1358       }else{
1359           $result.= "<img src='images/empty.png' alt=' ' class='center' style='padding:1px'>";
1360       }
1361     }
1363     return($result);
1364   }
1367   function renderDaemonMenu($separator)
1368   {
1369     $result= "";
1371     // If there is a daemon registered, draw the menu entries
1372     if(class_available("DaemonEvent")){
1373       $events= DaemonEvent::get_event_types_by_category($this->categories);
1374       if(isset($events['BY_CLASS']) && count($events['BY_CLASS'])){
1375         foreach($events['BY_CLASS'] as $name => $event){
1376           $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>";
1377           $separator= "";
1378         }
1379       }
1380     }
1382     return $result;
1383   }
1387 ?>