Code

Quirks for list display
[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;
55   function listing($filename)
56   {
57     global $config;
58     global $class_mapping;
60     // Initialize pid
61     $this->pid= preg_replace("/[^0-9]/", "", microtime(TRUE));
63     if (!$this->load($filename)) {
64       die("Cannot parse $filename!");
65     }
67     // Set base for filter
68     if ($this->baseMode) {
69       $this->base= session::global_get("CurrentMainBase");
70       if ($this->base == null) {
71         $this->base= $config->current['BASE'];
72       }
73       $this->refreshBasesList();
74     } else {
75       $this->base= $config->current['BASE'];
76     }
78     // Move footer information
79     $this->showFooter= ($config->get_cfg_value("listSummary") == "true");
81     // Register build in filters
82     $this->registerElementFilter("objectType", "listing::filterObjectType");
83     $this->registerElementFilter("departmentLink", "listing::filterDepartmentLink");
84     $this->registerElementFilter("link", "listing::filterLink");
85     $this->registerElementFilter("actions", "listing::filterActions");
87     // Load exporters
88     foreach($class_mapping as $class => $dummy) {
89       if (preg_match('/Exporter$/', $class)) {
90         $info= call_user_func(array($class, "getInfo"));
91         if ($info != null) {
92           $this->exporter= array_merge($this->exporter, $info);
93         }
94       }
95     }
96   }
99   function setCopyPasteHandler($handler)
100   {
101     $this->copyPasteHandler= &$handler;
102   }
105   function setSnapshotHandler($handler)
106   {
107     $this->snapshotHandler= &$handler;
108   }
111   function setFilter($filter)
112   {
113     $this->filter= &$filter;
114     if ($this->departmentBrowser){
115       $this->departments= $this->getDepartments();
116     }
117     $this->filter->setBase($this->base);
118   }
121   function registerElementFilter($name, $call)
122   {
123     if (!isset($this->filters[$name])) {
124       $this->filters[$name]= $call;
125       return true;
126     }
128     return false;
129   }
132   function load($filename)
133   {
134     $contents = file_get_contents($filename);
135     $this->xmlData= xml::xml2array($contents, 1);
137     if (!isset($this->xmlData['list'])) {
138       return false;
139     }
141     $this->xmlData= $this->xmlData["list"];
143     // Load some definition values
144     foreach (array("departmentBrowser", "departmentRootVisible", "multiSelect", "baseMode") as $token) {
145       if (isset($this->xmlData['definition'][$token]) &&
146           $this->xmlData['definition'][$token] == "true"){
147         $this->$token= true;
148       }
149     }
151     // Fill objectTypes from departments and xml definition
152     $types = departmentManagement::get_support_departments();
153     foreach ($types as $class => $data) {
154       $this->objectTypes[]= array("label" => $data['TITLE'],
155                                   "objectClass" => $data['OC'],
156                                   "image" => $data['IMG']);
157     }
158     $this->categories= array();
159     if (isset($this->xmlData['definition']['objectType'])) {
160       if(isset($this->xmlData['definition']['objectType']['label'])) {
161         $this->xmlData['definition']['objectType']= array($this->xmlData['definition']['objectType']);
162       }
163       foreach ($this->xmlData['definition']['objectType'] as $index => $otype) {
164         $this->objectTypes[]= $this->xmlData['definition']['objectType'][$index];
165         if (isset($this->xmlData['definition']['objectType'][$index]['category'])){
166           $this->categories[]= $this->xmlData['definition']['objectType'][$index]['category'];
167         }
168       }
169     }
171     // Parse layout per column
172     $this->colprops= $this->parseLayout($this->xmlData['table']['layout']);
174     // Prepare table headers
175     $this->renderHeader();
177     // Assign headline/module
178     $this->headline= _($this->xmlData['definition']['label']);
179     $this->module= $this->xmlData['definition']['module'];
180     if (!is_array($this->categories)){
181       $this->categories= array($this->categories);
182     }
184     // Evaluate columns to be exported
185     if (isset($this->xmlData['table']['column'])){
186       foreach ($this->xmlData['table']['column'] as $index => $config) {
187         if (isset($config['export']) && $config['export'] == "true"){
188           $this->exportColumns[]= $index;
189         }
190       }
191     }
193     return true;  
194   }
197   function renderHeader()
198   {
199     $this->header= array();
200     $this->plainHeader= array();
202     // Initialize sort?
203     $sortInit= false;
204     if (!$this->sortDirection) {
205       $this->sortColumn= 0;
206       if (isset($this->xmlData['definition']['defaultSortColumn'])){
207         $this->sortColumn= $this->xmlData['definition']['defaultSortColumn'];
208       } else {
209         $this->sortAttribute= "";
210       }
211       $this->sortDirection= array();
212       $sortInit= true;
213     }
215     if (isset($this->xmlData['table']['column'])){
216       foreach ($this->xmlData['table']['column'] as $index => $config) {
217         // Initialize everything to one direction
218         if ($sortInit) {
219           $this->sortDirection[$index]= false;
220         }
222         $sorter= "";
223         if ($index == $this->sortColumn && isset($config['sortAttribute']) &&
224             isset($config['sortType'])) {
225           $this->sortAttribute= $config['sortAttribute'];
226           $this->sortType= $config['sortType'];
227           $sorter= "&nbsp;<img border='0' title='".($this->sortDirection[$index]?_("Up"):_("Down"))."' src='images/lists/sort-".($this->sortDirection[$index]?"up":"down").".png' align='top'>";
228         }
229         $sortable= (isset($config['sortAttribute']));
231         $link= "href='?plug=".$_GET['plug']."&amp;PID=".$this->pid."&amp;act=SORT_$index'";
232         if (isset($config['label'])) {
233           if ($sortable) {
234             $this->header[$index]= "<td class='listheader' ".$this->colprops[$index]."><a $link>"._($config['label'])."$sorter</a></td>";
235           } else {
236             $this->header[$index]= "<td class='listheader' ".$this->colprops[$index].">"._($config['label'])."</td>";
237           }
238           $this->plainHeader[]= _($config['label']);
239         } else {
240           if ($sortable) {
241             $this->header[$index]= "<td class='listheader' ".$this->colprops[$index]."><a $link>&nbsp;$sorter</a></td>";
242           } else {
243             $this->header[$index]= "<td class='listheader' ".$this->colprops[$index].">&nbsp;</td>";
244           }
245           $this->plainHeader[]= "";
246         }
247       }
248     }
249   }
251   function render()
252   {
253     // Check for exeeded sizelimit
254     if (($message= check_sizelimit()) != ""){
255       return($message);
256     }
258     // Initialize list
259     $result= "<input type='hidden' value='$this->pid' name='PID'>\n";
260     $result.= "<div class='contentboxb' id='listing_container' style='border-top:1px solid #B0B0B0;'>\n";
261     $result.= "<table summary='$this->headline' style='width:600px;height:450px;' cellspacing='0' id='t_scrolltable'>
262 <tr><td class='scrollhead'><table summary='' style='width:100%;' cellspacing='0' id='t_scrollhead'>\n";
263     $this->numColumns= count($this->colprops) + ($this->multiSelect?1:0);
265     // Build list header
266     $result.= "<tr>\n";
267     if ($this->multiSelect) {
268       $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";
269     }
270     foreach ($this->header as $header) {
271       $result.= $header;
272     }
274     // Add 13px for scroller
275     $result.= "<td class='listheader' style='width:13px;border-right:0px;'>&nbsp;</td></table></td></tr>\n";
277     // New table for the real list contents
278     $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";
280     // No results? Just take an empty colspanned row
281     if (count($this->entries) + count($this->departments) == 0) {
282       $result.= "<tr class='rowxp0'><td class='list1nohighlight' colspan='$this->numColumns' style='height:100%;border-right:0px;width:100%;'>&nbsp;</td></tr>";
283     }
285     // Line color alternation
286     $alt= 0;
287     $deps= 0;
289     // Draw department browser if configured and we're not in sub mode
290     $this->useSpan= false;
291     if ($this->departmentBrowser && $this->filter->scope != "sub") {
292       // Fill with department browser if configured this way
293       $departmentIterator= new departmentSortIterator($this->departments, $this->sortDirection[$this->sortColumn]);
294       foreach ($departmentIterator as $row => $entry){
295         $result.="<tr class='rowxp".($alt&1)."'>";
297         // Render multi select if needed
298         if ($this->multiSelect) {
299           $result.="<td style='text-align:center;width:20px;' class='list1'>&nbsp;</td>";
300         }
302         // Render defined department columns, fill the rest with some stuff
303         $rest= $this->numColumns - 1;
304         foreach ($this->xmlData['table']['department'] as $index => $config) {
305           $colspan= 1;
306           if (isset($config['span'])){
307             $colspan= $config['span'];
308             $this->useSpan= true;
309           }
310           $result.="<td colspan='$colspan' ".$this->colprops[$index]." class='list1'>".$this->renderCell($config['value'], $entry, $row)."</td>";
311           $rest-= $colspan;
312         }
314         // Fill remaining cols with nothing
315         $last= $this->numColumns - $rest;
316         for ($i= 0; $i<$rest; $i++){
317           $result.= "<td ".$this->colprops[$last+$i-1]." class='list1'>&nbsp;</td>";
318         }
319         $result.="</tr>";
321         $alt++;
322       }
323       $deps= $alt;
324     }
326     // Fill with contents, sort as configured
327     foreach ($this->entries as $row => $entry) {
328       $trow= "";
330       // Render multi select if needed
331       if ($this->multiSelect) {
332         $trow.="<td style='text-align:center;width:20px;' class='list0'><input type='checkbox' id='listing_selected_$row' name='listing_selected_$row'></td>\n";
333       }
335       foreach ($this->xmlData['table']['column'] as $index => $config) {
336         $renderedCell= $this->renderCell($config['value'], $entry, $row);
337         $trow.="<td ".$this->colprops[$index]." class='list0'>".$renderedCell."</td>\n";
339         // Save rendered column
340         $sort= preg_replace('/.*>([^<]+)<.*$/', '$1', $renderedCell);
341         $sort= preg_replace('/&nbsp;/', '', $sort);
342         if (preg_match('/</', $sort)){
343           $sort= "";
344         }
345         $this->entries[$row]["_sort$index"]= $sort;
346       }
348       // Save rendered entry
349       $this->entries[$row]['_rendered']= $trow;
350     }
352     // Complete list by sorting entries for _sort$index and appending them to the output
353     $entryIterator= new listingSortIterator($this->entries, $this->sortDirection[$this->sortColumn], "_sort".$this->sortColumn, $this->sortType);
354     foreach ($entryIterator as $row => $entry){
355       $alt++;
356       $result.="<tr class='rowxp".($alt&1)."'>\n";
357       $result.= $entry['_rendered'];
358       $result.="</tr>\n";
359     }
361     // Need to fill the list if it's not full (nobody knows why this is 22 ;-))
362     $emptyListStyle= (count($this->entries) + (($this->useSpan && count($this->entries))?$deps:0) == 0)?"border:0;":"";
363     if ((count($this->entries) + $deps) < 22) {
364       $result.= "<tr>";
365       for ($i= 0; $i<$this->numColumns; $i++) {
366         if ($i == 0) {
367           $result.= "<td class='list1nohighlight' style='$emptyListStyle height:100%;'>&nbsp;</td>";
368           continue;
369         }
370         if ($i != $this->numColumns-1) {
371           $result.= "<td class='list1nohighlight' style='$emptyListStyle'>&nbsp;</td>";
372         } else {
373           $result.= "<td class='list1nohighlight' style='border-right:1px solid #AAA;$emptyListStyle'>&nbsp;</td>";
374         }
375       }
376       $result.= "</tr>";
377     }
379     $result.= "</table></div></td></tr>";
381     // Add the footer if requested
382     if ($this->showFooter) {
383       $result.= "<tr><td class='scrollhead'><table summary='' style='width:100%' cellspacing='0' id='t_scrollfoot'><tr><td class='listfooter' style='border-bottom:0px;'>";
385       foreach ($this->objectTypes as $objectType) {
386         if (isset($this->objectTypeCount[$objectType['label']])) {
387           $label= _($objectType['label']);
388           $result.= "<img class='center' src='".$objectType['image']."' title='$label' alt='$label'>&nbsp;".$this->objectTypeCount[$objectType['label']]."&nbsp;&nbsp;&nbsp;&nbsp;";
389         }
390       }
392       $result.= "<td class='listfooter' style='width:13px;border-right:0px;'>&nbsp;</td></table></td></tr>";
393     }
395     $result.= "</table></div>";
397     $smarty= get_smarty();
398     $smarty->assign("FILTER", $this->filter->render());
399     $smarty->assign("SIZELIMIT", print_sizelimit_warning());
400     $smarty->assign("LIST", $result);
402     // Assign navigation elements
403     $nav= $this->renderNavigation();
404     foreach ($nav as $key => $html) {
405       $smarty->assign($key, $html);
406     }
408     // Assign action menu / base
409     $smarty->assign("ACTIONS", $this->renderActionMenu());
410     $smarty->assign("BASE", $this->renderBase());
412     // Assign separator
413     $smarty->assign("SEPARATOR", "<img src='images/lists/seperator.png' alt='-' align='middle' height='16' width='1' class='center'>");
415     // Assign summary
416     $smarty->assign("HEADLINE", $this->headline);
418     return ($smarty->fetch(get_template_path($this->xmlData['definition']['template'], true)));
419   }
422   function update()
423   {
424     global $config;
425     $ui= get_userinfo();
427     // Reset object counter
428     $this->objectTypeCount= array();
430     // Do not do anything if this is not our PID
431     if(isset($_REQUEST['PID']) && $_REQUEST['PID'] != $this->pid) {
432       return;
433     }
435     // Save base
436     if (isset($_POST['BASE']) && $this->baseMode) {
437       $base= validate($_POST['BASE']);
438       if (isset($this->bases[$base])) {
439         $this->base= $base;
440       }
441     }
443     // Override the base if we got a message from the browser navigation
444     if ($this->departmentBrowser && isset($_GET['act'])) {
445       if (preg_match('/^department_([0-9]+)$/', validate($_GET['act']), $match)){
446         if (isset($this->departments[$match[1]])){
447           $this->base= $this->departments[$match[1]]['dn'];
448         }
449       }
450     }
452     // Filter POST with "act" attributes -> posted from action menu
453     if (isset($_POST['exec_act']) && $_POST['act'] != '') {
454       if (preg_match('/^export.*$/', $_POST['act']) && isset($this->exporter[$_POST['act']])) {
455         $exporter= $this->exporter[$_POST['act']];
456         $userinfo= ", "._("created by")." ".$ui->cn." - ".strftime('%A, %d. %B %Y, %H:%M:%S');
457         $instance= new $exporter['class']($this->headline.$userinfo, $this->plainHeader, $this->entries, $this->exportColumns);
458         $type= call_user_func(array($exporter['class'], "getInfo"));
459         $type= $type[$_POST['act']];
460         send_binary_content($instance->query(), $type['filename'], $type= $type['mime']);
461       }
462     }
464     // Filter GET with "act" attributes
465     if (isset($_GET['act'])) {
466       $key= validate($_GET['act']);
467       if (preg_match('/^SORT_([0-9]+)$/', $key, $match)) {
468         // Switch to new column or invert search order?
469         $column= $match[1];
470         if ($this->sortColumn != $column) {
471           $this->sortColumn= $column;
472         } else {
473           $this->sortDirection[$column]= !$this->sortDirection[$column];
474         }
476         // Allow header to update itself according to the new sort settings
477         $this->renderHeader();
478       }
479     }
481     // Override base if we got signals from the navigation elements
482     $action= "";
483     foreach ($_POST as $key => $value) {
484       if (preg_match('/^(ROOT|BACK|HOME)_x$/', $key, $match)) {
485         $action= $match[1];
486         break;
487       }
488     }
490     // Navigation handling
491     if ($action == 'ROOT') {
492       $deps= $ui->get_module_departments($this->module);
493       $this->base= $deps[0];
494     }
495     if ($action == 'BACK') {
496       $deps= $ui->get_module_departments($this->module);
497       $base= preg_replace("/^[^,]+,/", "", $this->base);
498       if(in_array_ics($base, $deps)){
499         $this->base= $base;
500       }
501     }
502     if ($action == 'HOME') {
503       $ui= get_userinfo();
504       $this->base= get_base_from_people($ui->dn);
505     }
507     // Reload departments
508     if ($this->departmentBrowser){
509       $this->departments= $this->getDepartments();
510     }
512     // Update filter and refresh entries
513     $this->filter->setBase($this->base);
514     $this->entries= $this->filter->query();
515   }
518   function setBase($base)
519   {
520     $this->base= $base;
521   }
524   function getBase()
525   {
526     return $this->base;
527   }
530   function parseLayout($layout)
531   {
532     $result= array();
533     $layout= preg_replace("/^\|/", "", $layout);
534     $layout= preg_replace("/\|$/", "", $layout);
535     $cols= split("\|", $layout);
536     foreach ($cols as $index => $config) {
537       if ($config != "") {
538         $components= split(';', $config);
539         $config= "";
540         foreach ($components as $part) {
541           if (preg_match("/^r$/", $part)) {
542             $config.= "text-align:right;";
543             continue;
544           }
545           if (preg_match("/^l$/", $part)) {
546             $config.= "text-align:left;";
547             continue;
548           }
549           if (preg_match("/^c$/", $part)) {
550             $config.= "text-align:center;";
551             continue;
552           }
553           if (preg_match("/^[0-9]+(|px|%)$/", $part)) {
554             $config.= "width:$part;";
555             continue;
556           }
557         }
559         $result[$index]= " style='$config' ";
560       } else {
561         $result[$index]= null;
562       }
563     }
565     // Save number of columns for later use
566     $this->numColumns= count($cols);
568     return $result;
569   }
572   function renderCell($data, $config, $row)
573   {
574     // Replace flat attributes in data string
575     for ($i= 0; $i<$config['count']; $i++) {
576       $attr= $config[$i];
577       $value= "";
578       if (is_array($config[$attr])) {
579         $value= $config[$attr][0];
580       } else {
581         $value= $config[$attr];
582       }
583       $data= preg_replace("/%\{$attr\}/", $value, $data);
584     }
586     // Watch out for filters and prepare to execute them
587     $data= $this->processElementFilter($data, $config, $row);
589     // Replace all non replaced %{...} instances because they
590     // are non resolved attributes or filters
591     $data= preg_replace('/%{[^}]+}/', '&nbsp;', $data);
593     return $data;
594   }
597   function renderBase()
598   {
599     if (!$this->baseMode) {
600       return;
601     }
603     $result= "<select name='BASE' onChange='mainform.submit()' size='1'>";
604     $firstDN= null;
605     $found= false;
607     foreach ($this->bases as $key=>$value) {
608       // Keep first entry to fall back eventually
609       if(!$firstDN) {
610         $firstDN= $key;
611       }
613       // Prepare to render entry
614       $selected= "";
615       if ($key == $this->base) {
616         $selected= " selected";
617         $found= true;
618       }
619       $result.= "<option value='".$key."'$selected>".$value."</option>";
620     }
621     $result.= "</select>";
623     // Reset the currently used base to the first DN we found if there
624     // was no match.
625     if(!$found){
626       $this->base = $firstDN;
627     }
629     return $result;
630   }
633   function processElementFilter($data, $config, $row)
634   {
635     preg_match_all("/%\{filter:([^(]+)\((.*)\)\}/", $data, $matches, PREG_SET_ORDER);
637     foreach ($matches as $match) {
638       if (!isset($this->filters[$match[1]])) {
639         continue;
640       }
641       $cl= preg_replace('/::.*$/', '', $this->filters[$match[1]]);
642       $method= preg_replace('/^.*::/', '', $this->filters[$match[1]]);
644       // Prepare params for function call
645       $params= array();
646       preg_match_all('/"[^"]+"|[^,]+/', $match[2], $parts);
647       foreach ($parts[0] as $param) {
649         // Row is replaced by the row number
650         if ($param == "row") {
651           $params[]= $row;
652         }
654         // pid is replaced by the current PID
655         if ($param == "pid") {
656           $params[]= $this->pid;
657         }
659         // Fixie with "" is passed directly
660         if (preg_match('/^".*"$/', $param)){
661           $params[]= preg_replace('/"/', '', $param);
662         }
664         // LDAP variables get replaced by their objects
665         for ($i= 0; $i<$config['count']; $i++) {
666           if ($param == $config[$i]) {
667             $values= $config[$config[$i]];
668             if (is_array($values)){
669               unset($values['count']);
670             }
671             $params[]= $values;
672           }
673         }
675         // Move dn if needed
676         if ($param == "dn") {
677           $params[]= LDAP::fix($config["dn"]);
678         }
679       }
681       // Replace information
682       if ($cl == "listing") {
683         // Non static call - seems to result in errors
684         $data= @preg_replace('/'.preg_quote($match[0]).'/', call_user_func_array(array($this, "$method"), $params), $data);
685       } else {
686         // Static call
687         $data= preg_replace('/'.preg_quote($match[0]).'/', call_user_func_array(array($cl, $method), $params), $data);
688       }
689     }
691     return $data;
692   }
695   function getObjectType($types, $classes)
696   {
697     // Walk thru types and see if there's something matching
698     foreach ($types as $objectType) {
699       $ocs= $objectType['objectClass'];
700       if (!is_array($ocs)){
701         $ocs= array($ocs);
702       }
704       $found= true;
705       foreach ($ocs as $oc){
706         if (preg_match('/^!(.*)$/', $oc, $match)) {
707           $oc= $match[1];
708           if (in_array($oc, $classes)) {
709             $found= false;
710           }
711         } else {
712           if (!in_array($oc, $classes)) {
713             $found= false;
714           }
715         }
716       }
718       if ($found) {
719         return $objectType;
720       }
721     }
723     return null;
724   }
727   function filterObjectType($dn, $classes)
728   {
729     // Walk thru classes and return on first match
730     $result= "&nbsp;";
732     $objectType= $this->getObjectType($this->objectTypes, $classes);
733     if ($objectType) {
734       $result= "<img class='center' title='".LDAP::fix($dn)."' src='".$objectType["image"]."'>";
735       if (!isset($this->objectTypeCount[$objectType['label']])) {
736         $this->objectTypeCount[$objectType['label']]= 0;
737       }
738       $this->objectTypeCount[$objectType['label']]++;
739     }
740     return $result;
741   }
744   function filterActions($dn, $row, $classes)
745   {
746     // Do nothing if there's no menu defined
747     if (!isset($this->xmlData['actiontriggers']['action'])) {
748       return "&nbsp;";
749     }
751     // Go thru all actions
752     $result= "";
753     $actions= $this->xmlData['actiontriggers']['action'];
754     foreach($actions as $action) {
755       // Skip the entry completely if there's no permission to execute it
756       if (!$this->hasActionPermission($action, $dn)) {
757         continue;
758       }
760       // If there's an objectclass definition and we don't have it
761       // add an empty picture here.
762       if (isset($action['objectclass'])){
763         $objectclass= $action['objectclass'];
764         if (preg_match('/^!(.*)$/', $objectclass, $m)){
765           $objectclass= $m[1];
766           if(in_array($objectclass, $classes)) {
767             $result.= "<img src='images/empty.png' alt=' ' class='center' style='padding:1px'>";
768             continue;
769           }
770         } else {
771           if(!in_array($objectclass, $classes)) {
772             $result.= "<img src='images/empty.png' alt=' ' class='center' style='padding:1px'>";
773             continue;
774           }
775         }
776       }
778       // Render normal entries as usual
779       if ($action['type'] == "entry") {
780         $label= $this->processElementFilter($action['label'], $this->entries[$row], $row);
781         $image= $this->processElementFilter($action['image'], $this->entries[$row], $row);
782         $result.="<input class='center' type='image' src='$image' title='$label' ".
783                  "name='listing_".$action['name']."_$row' style='padding:1px'>";
784       }
786       // Handle special types
787       if ($action['type'] == "copypaste" || $action['type'] == "snapshot") {
789         $objectType= $this->getObjectType($this->objectTypes, $this->entries[$row]['objectClass']);
790         $category= $class= null;
791         if ($objectType) {
792           $category= $objectType['category'];
793           $class= $objectType['class'];
794         }
796         if ($action['type'] == "copypaste") {
797           $result.= $this->renderCopyPasteActions($row, $this->entries[$row]['dn'], $category, $class);
798         } else {
799           $result.= $this->renderSnapshotActions($row, $this->entries[$row]['dn'], $category, $class);
800         }
801       }
802     }
804     return $result;
805   }
808   function filterDepartmentLink($row, $dn, $description)
809   {
810     $attr= $this->departments[$row]['sort-attribute'];
811     $name= $this->departments[$row][$attr];
812     if (is_array($name)){
813       $name= $name[0];
814     }
815     $result= sprintf("%s [%s]", $name, $description[0]);
816     return("<a href='?plug=".$_GET['plug']."&amp;PID=$this->pid&amp;act=department_$row' title='$dn'>$result</a>");
817   }
820   function filterLink()
821   {
822     $result= "&nbsp;";
824     $row= func_get_arg(0);
825     $pid= $this->pid;
826     $dn= LDAP::fix(func_get_arg(1));
827     $params= array(func_get_arg(2));
829     // Collect sprintf params
830     for ($i = 3;$i < func_num_args();$i++) {
831       $val= func_get_arg($i);
832       if (is_array($val)){
833         $params[]= $val[0];
834         continue;
835       }
836       $params[]= $val;
837     }
839     $result= "&nbsp;";
840     $trans= call_user_func_array("sprintf", $params);
841     if ($trans != "") {
842       return("<a href='?plug=".$_GET['plug']."&amp;PID=$pid&amp;act=listing_edit_$row' title='$dn'>$trans</a>");
843     }
845     return $result;
846   }
849   function renderNavigation()
850   {
851     $result= array();
852     $enableBack = true;
853     $enableRoot = true;
854     $enableHome = true;
856     $ui = get_userinfo();
858     /* Check if base = first available base */
859     $deps = $ui->get_module_departments($this->module);
861     if(!count($deps) || $deps[0] == $this->filter->base){
862       $enableBack = false;
863       $enableRoot = false;
864     }
866     $listhead ="";
868     /* Check if we are in users home  department */
869     if(!count($deps) ||$this->filter->base == get_base_from_people($ui->dn)){
870       $enableHome = false;
871     }
873     /* Draw root button */
874     if($enableRoot){
875       $result["ROOT"]= "<input class='center' type='image' src='images/lists/root.png' align='middle' ".
876                        "title='"._("Go to root department")."' name='ROOT' alt='"._("Root")."'>";
877     }else{
878       $result["ROOT"]= "<img src='images/lists/root_grey.png' class='center' alt='"._("Root")."'>";
879     }
881     /* Draw back button */
882     if($enableBack){
883       $result["BACK"]= "<input class='center' type='image' align='middle' src='images/lists/back.png' ".
884                        "title='"._("Go up one department")."' alt='"._("Up")."' name='BACK'>";
885     }else{
886       $result["BACK"]= "<img src='images/lists/back_grey.png' class='center' alt='"._("Up")."'>";
887     }
889     /* Draw home button */
890     if($enableHome){
891       $result["HOME"]= "<input class='center' type='image' align='middle' src='images/lists/home.png' ".
892                        "title='"._("Go to users department")."' alt='"._("Home")."' name='HOME'>";
893     }else{
894       $result["HOME"]= "<img src='images/lists/home_grey.png' class='center' alt='"._("Home")."'>";
895     }
897     /* Draw reload button, this button is enabled everytime */
898     $result["RELOAD"]= "<input class='center' type='image' src='images/lists/reload.png' align='middle' ".
899                        "title='"._("Reload list")."' name='REFRESH' alt='"._("Submit")."'>";
901     return ($result);
902   }
905   function getAction()
906   {
907     // Do not do anything if this is not our PID, or there's even no PID available...
908     if(!isset($_REQUEST['PID']) || $_REQUEST['PID'] != $this->pid) {
909       return;
910     }
912     $result= array("targets" => array(), "action" => "");
914     // Filter GET with "act" attributes
915     if (isset($_GET['act'])) {
916       $key= validate($_GET['act']);
917       $target= preg_replace('/^listing_[a-zA-Z_]+_([0-9]+)$/', '$1', $key);
918       if (isset($this->entries[$target]['dn'])) {
919         $result['action']= preg_replace('/^listing_([a-zA-Z_]+)_[0-9]+$/', '$1', $key);
920         $result['targets'][]= $this->entries[$target]['dn'];
921       }
923       // Drop targets if empty
924       if (count($result['targets']) == 0) {
925         unset($result['targets']);
926       }
927       return $result;
928     }
930     // Filter POST with "listing_" attributes
931     foreach ($_POST as $key => $prop) {
933       // Capture selections
934       if (preg_match('/^listing_selected_[0-9]+$/', $key)) {
935         $target= preg_replace('/^listing_selected_([0-9]+)$/', '$1', $key);
936         if (isset($this->entries[$target]['dn'])) {
937           $result['targets'][]= $this->entries[$target]['dn'];
938         }
939         continue;
940       }
942       // Capture action with target - this is a one shot
943       if (preg_match('/^listing_[a-zA-Z_]+_[0-9]+(|_x)$/', $key)) {
944         $target= preg_replace('/^listing_[a-zA-Z_]+_([0-9]+)(|_x)$/', '$1', $key);
945         if (isset($this->entries[$target]['dn'])) {
946           $result['action']= preg_replace('/^listing_([a-zA-Z_]+)_[0-9]+(|_x)$/', '$1', $key);
947           $result['targets']= array($this->entries[$target]['dn']);
948         }
949         break;
950       }
952       // Capture action without target
953       if (preg_match('/^listing_[a-zA-Z_]+(|_x)$/', $key)) {
954         $result['action']= preg_replace('/^listing_([a-zA-Z_]+)(|_x)$/', '$1', $key);
955         continue;
956       }
957     }
959     // Filter POST with "act" attributes -> posted from action menu
960     if (isset($_POST['act']) && $_POST['act'] != '') {
961       if (!preg_match('/^export.*$/', $_POST['act'])){
962         $result['action']= validate($_POST['act']);
963       }
964     }
966     // Drop targets if empty
967     if (count($result['targets']) == 0) {
968       unset($result['targets']);
969     }
970     return $result;
971   }
974   function renderActionMenu()
975   {
976     // Don't send anything if the menu is not defined
977     if (!isset($this->xmlData['actionmenu']['action'])){
978       return "";
979     }
981     // Load shortcut
982     $actions= &$this->xmlData['actionmenu']['action'];
983     $result= "<input type='hidden' name='act' id='actionmenu' value=''><div style='display:none'><input type='submit' name='exec_act' id='exec_act' value=''></div>".
984              "<ul class='level1' id='root'><li><a href='#'>Aktionen&nbsp;<img ".
985              "border=0 class='center' src='images/lists/sort-down.png'></a>";
987     // Build ul/li list
988     $result.= $this->recurseActions($actions);
990     return "<div id='pulldown'>".$result."</li></ul><div>";
991   }
994   function recurseActions($actions)
995   {
996     static $level= 2;
997     $result= "<ul class='level$level'>";
998     $separator= "";
1000     foreach ($actions as $action) {
1002       // Skip the entry completely if there's no permission to execute it
1003       if (!$this->hasActionPermission($action, $this->filter->base)) {
1004         continue;
1005       }
1007       // Fill image if set
1008       $img= "";
1009       if (isset($action['image'])){
1010         $img= "<img border='0' class='center' src='".$action['image']."'>&nbsp;";
1011       }
1013       if ($action['type'] == "separator"){
1014         $separator= " style='border-top:1px solid #AAA' ";
1015         continue;
1016       }
1018       // Dive into subs
1019       if ($action['type'] == "sub" && isset($action['action'])) {
1020         $level++;
1021         if (isset($action['label'])){
1022           $result.= "<li$separator><a href='#'>$img"._($action['label'])."&nbsp;<img border='0' src='images/forward-arrow.png'></a>";
1023         }
1024         $result.= $this->recurseActions($action['action'])."</li>";
1025         $level--;
1026         $separator= "";
1027         continue;
1028       }
1030       // Render entry elseways
1031       if (isset($action['label'])){
1032         $result.= "<li$separator><a href='#' onClick='document.getElementById(\"actionmenu\").value= \"".$action['name']."\";mainform.submit();'>$img"._($action['label'])."</a></li>";
1033       }
1035       // Check for special types
1036       switch ($action['type']) {
1037         case 'copypaste':
1038           $result.= $this->renderCopyPasteMenu($separator);
1039           break;
1041         case 'snapshot':
1042           $result.= $this->renderSnapshotMenu($separator);
1043           break;
1045         case 'exporter':
1046           $result.= $this->renderExporterMenu($separator);
1047           break;
1049         case 'daemon':
1050           $result.= $this->renderDaemonMenu($separator);
1051           break;
1052       }
1054       $separator= "";
1055     }
1057     $result.= "</ul>";
1058     return $result;
1059   }
1062   function hasActionPermission($action, $dn)
1063   {
1064     $ui= get_userinfo();
1066     if (isset($action['acl'])) {
1067       $acls= $action['acl'];
1068       if (!is_array($acls)) {
1069         $acls= array($acls);
1070       }
1072       // Every ACL has to pass
1073       foreach ($acls as $acl) {
1074         $module= $this->module;
1075         $aclList= array();
1077         // Split for category and plugins if needed
1078         // match for "[rw]" style entries
1079         if (preg_match('/^\[([rwcdm]+)\]$/', $acl, $match)){
1080           $aclList= array($match[1]);
1081         }
1083         // match for "users[rw]" style entries
1084         if (preg_match('/^([a-zA-Z0-9]+)\[([rwcdm]+)\]$/', $acl, $match)){
1085           $module= $match[1];
1086           $aclList= array($match[2]);
1087         }
1089         // match for "users/user[rw]" style entries
1090         if (preg_match('/^([a-zA-Z0-9]+\/[a-zA-Z0-9]+)\[([rwcdm]+)\]$/', $acl, $match)){
1091           $module= $match[1];
1092           $aclList= array($match[2]);
1093         }
1095         // match "users/user[userPassword:rw(,...)*]" style entries
1096         if (preg_match('/^([a-zA-Z0-9]+\/[a-zA-Z0-9]+)\[([a-zA-Z0-9]+:[rwcdm]+(,[a-zA-Z0-9]+:[rwcdm]+)*)\]$/', $acl, $match)){
1097           $module= $match[1];
1098           $aclList= split(',', $match[2]);
1099         }
1101         // Walk thru prepared ACL by using $module
1102         foreach($aclList as $sAcl) {
1103           $checkAcl= "";
1105           // Category or detailed permission?
1106           if (strpos('/', $module) === false) {
1107             if (preg_match('/([a-zA-Z0-9]+):([rwcdm]+)/', $sAcl, $m) ) {
1108               $checkAcl= $ui->get_permissions($dn, $module, $m[1]);
1109               $sAcl= $m[2];
1110             } else {
1111               $checkAcl= $ui->get_permissions($dn, $module, '0');
1112             }
1113           } else {
1114             $checkAcl= $ui->get_category_permissions($dn, $module);
1115           }
1117           // Split up remaining part of the acl and check if it we're
1118           // allowed to do something...
1119           $parts= str_split($sAcl);
1120           foreach ($parts as $part) {
1121             if (strpos($checkAcl, $part) === false){
1122               return false;
1123             }
1124           }
1126         }
1127       }
1128     }
1130     return true;
1131   }
1134   function refreshBasesList()
1135   {
1136     global $config;
1137     $ui= get_userinfo();
1139     // Do some array munching to get it user friendly
1140     $ids= $config->idepartments;
1141     $d= $ui->get_module_departments($this->module);
1142     $k_ids= array_keys($ids);
1143     $deps= array_intersect($d,$k_ids);
1145     // Fill internal bases list
1146     $this->bases= array();
1147     foreach($k_ids as $department){
1148       $this->bases[$department] = $ids[$department];
1149     }
1150   }
1153   function getDepartments()
1154   {
1155     $departments= array();
1156     $ui= get_userinfo();
1158     // Get list of supported department types
1159     $types = departmentManagement::get_support_departments();
1161     // Load departments allowed by ACL
1162     $validDepartments = $ui->get_module_departments($this->module);
1164     // Build filter and look in the LDAP for possible sub departments
1165     // of current base
1166     $filter= "(&(objectClass=gosaDepartment)(|";
1167     $attrs= array("description", "objectClass");
1168     foreach($types as $name => $data){
1169       $filter.= "(objectClass=".$data['OC'].")";
1170       $attrs[]= $data['ATTR'];
1171     }
1172     $filter.= "))";
1173     $res= get_list($filter, $this->module, $this->base, $attrs, GL_NONE);
1175     // Analyze list of departments
1176     foreach ($res as $department) {
1177       if (!in_array($department['dn'], $validDepartments)) {
1178         continue;
1179       }
1181       // Add the attribute where we use for sorting
1182       $oc= null;
1183       foreach(array_keys($types) as $type) {
1184         if (in_array($type, $department['objectClass'])) {
1185           $oc= $type;
1186           break;
1187         }
1188       }
1189       $department['sort-attribute']= $types[$oc]['ATTR'];
1191       // Move to the result list
1192       $departments[]= $department;
1193     }
1195     return $departments;
1196   }
1199   function renderCopyPasteMenu($separator, $copy= true, $cut= true)
1200   {
1201     // We can only provide information if we've got a copypaste handler
1202     // instance
1203     if(!(isset($this->copyPasteHandler) && is_object($this->copyPasteHandler))){
1204       return "";
1205     }
1207     // Presets
1208     $result= "";
1209     $read= $paste= false;
1210     $ui= get_userinfo();
1212     // Switch flags to on if there's at least one category which allows read/paste
1213     foreach($this->categories as $category){
1214       $read= $read || preg_match('/r/', $ui->get_category_permissions($this->base, $category));
1215       $paste= $paste || $ui->is_pasteable($this->base, $category) == 1;
1216     }
1219     // Draw entries that allow copy and cut
1220     if($read){
1222       // Copy entry
1223       if($copy){
1224         $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>";
1225         $separator= "";
1226       }
1228       // Cut entry
1229       if($cut){
1230         $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>";
1231         $separator= "";
1232       }
1233     }
1235     // Draw entries that allow pasting entries
1236     if($paste){
1237       if($this->copyPasteHandler->entries_queued()){
1238         $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>";
1239       }else{
1240         $result.= "<li$separator><a href='#'><img src='images/lists/paste-grey.png' alt='' border='0' class='center'>&nbsp;"._("Paste")."</a></li>";
1241       }
1242     }
1243     
1244     return($result);
1245   }
1248   function renderCopyPasteActions($row, $dn, $category, $class, $copy= true, $cut= true)
1249   {
1250     // We can only provide information if we've got a copypaste handler
1251     // instance
1252     if(!(isset($this->copyPasteHandler) && is_object($this->copyPasteHandler))){
1253       return "";
1254     }
1256     // Presets
1257     $ui = get_userinfo();
1258     $result = "";
1260     // Render cut entries
1261     if($cut){
1262       if($ui->is_cutable($dn, $category, $class)){
1263         $result .= "<input class='center' type='image'
1264           src='images/lists/cut.png' alt='"._("Cut")."' name='listing_cut_$row' title='"._("Cut this entry")."' style='padding:1px'>";
1265       }else{
1266         $result.="<img src='images/empty.png' alt=' ' class='center' style='padding:1px'>";
1267       }
1268     }
1270     // Render copy entries
1271     if($copy){
1272       if($ui->is_copyable($dn, $category, $class)){
1273         $result.= "<input class='center' type='image'
1274           src='images/lists/copy.png' alt='"._("Copy")."' name='listing_copy_$row' title='"._("Copy this entry")."' style='padding:1px'>";
1275       }else{
1276         $result.="<img src='images/empty.png' alt=' ' class='center' style='padding:1px'>";
1277       }
1278     }
1280     return($result);
1281   }
1284   function renderSnapshotMenu($separator)
1285   {
1286     // We can only provide information if we've got a snapshot handler
1287     // instance
1288     if(!(isset($this->snapshotHandler) && is_object($this->snapshotHandler))){
1289       return "";
1290     }
1292     // Presets
1293     $result = "";
1294     $ui = get_userinfo();
1296     if($this->snapshotHandler->enabled() && $ui->allow_snapshot_restore($this->base, $this->module)){
1298       // Check if there is something to restore
1299       $restore= false;
1300       foreach($this->snapshotHandler->getSnapshotBases() as $base){
1301         $restore= $restore || count($this->snapshotHandler->getDeletedSnapshots($base)) > 0;
1302       }
1304       // Draw icons according to the restore flag
1305       if($restore){
1306         $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>";
1307       }else{
1308         $result.= "<li$separator><a href='#'><img src='images/lists/restore_grey.png' alt='' border='0' class='center'>&nbsp;"._("Restore snapshots")."</a></li>";
1309       }
1310     }
1312     return($result);
1313   }
1316   function renderExporterMenu($separator)
1317   {
1318     // Presets
1319     $result = "";
1321     // Draw entries
1322     $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'>";
1324     // Export CVS as build in exporter
1325     foreach ($this->exporter as $action => $exporter) {
1326       $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>";
1327     }
1329     // Finalize list
1330     $result.= "</ul></li>";
1332     return($result);
1333   }
1336   function renderSnapshotActions($row, $dn, $category, $class, $copy= true, $cut= true)
1337   {
1338     // We can only provide information if we've got a snapshot handler
1339     // instance
1340     if(!(isset($this->snapshotHandler) && is_object($this->snapshotHandler))){
1341       return "";
1342     }
1344     // Presets
1345     $result= "";
1346     $ui = get_userinfo();
1348     // Only act if enabled here
1349     if($this->snapshotHandler->enabled()){
1351       // Draw restore button
1352       if ($ui->allow_snapshot_restore($dn, $category)){
1354         // Do we have snapshots for this dn?
1355         if($this->snapshotHandler->hasSnapshots($dn)){
1356           $result.= "<input class='center' type='image' src='images/lists/restore.png' ".
1357                      "alt='"._("Restore snapshot")."' name='listing_restore_$row' title='".
1358                      _("Restore snapshot")."' style='padding:1px'>";
1359         } else {
1360           $result.= "<img src='images/lists/restore_grey.png' alt=' ' class='center' style='padding:1px'>";
1361         }
1362       }
1364       // Draw snapshot button
1365       if($ui->allow_snapshot_create($dn, $category)){
1366           $result.= "<input class='center' type='image' src='images/snapshot.png' ".
1367                      "alt='"._("Create snapshot")."' name='listing_snapshot_$row' title='".
1368                      _("Create a new snapshot from this object")."' style='padding:1px'>";
1369       }else{
1370           $result.= "<img src='images/empty.png' alt=' ' class='center' style='padding:1px'>";
1371       }
1372     }
1374     return($result);
1375   }
1378   function renderDaemonMenu($separator)
1379   {
1380     $result= "";
1382     // If there is a daemon registered, draw the menu entries
1383     if(class_available("DaemonEvent")){
1384       $events= DaemonEvent::get_event_types_by_category($this->categories);
1385       if(isset($events['BY_CLASS']) && count($events['BY_CLASS'])){
1386         foreach($events['BY_CLASS'] as $name => $event){
1387           $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>";
1388           $separator= "";
1389         }
1390       }
1391     }
1393     return $result;
1394   }
1398 ?>