Code

96e63ac83521f68ce404f41256e207d447c0d81e
[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     if ($this->baseMode) {
68       $this->base= session::global_get("CurrentMainBase");
69       if ($this->base == null) {
70         $this->base= $config->current['BASE'];
71       }
72       $this->refreshBasesList();
73     } else {
74       $this->base= $config->current['BASE'];
75     }
77     // Move footer information
78     $this->showFooter= ($config->get_cfg_value("listSummary") == "true");
80     // Register build in filters
81     $this->registerElementFilter("objectType", "listing::filterObjectType");
82     $this->registerElementFilter("departmentLink", "listing::filterDepartmentLink");
83     $this->registerElementFilter("link", "listing::filterLink");
84     $this->registerElementFilter("actions", "listing::filterActions");
86     // Load exporters
87     foreach($class_mapping as $class => $dummy) {
88       if (preg_match('/Exporter$/', $class)) {
89         $info= call_user_func(array($class, "getInfo"));
90         if ($info != null) {
91           $this->exporter= array_merge($this->exporter, $info);
92         }
93       }
94     }
95   }
98   function setCopyPasteHandler($handler)
99   {
100     $this->copyPasteHandler= &$handler;
101   }
104   function setSnapshotHandler($handler)
105   {
106     $this->snapshotHandler= &$handler;
107   }
110   function setFilter($filter)
111   {
112     $this->filter= &$filter;
113     if ($this->departmentBrowser){
114       $this->departments= $this->getDepartments();
115     }
116     $this->filter->setBase($this->base);
117   }
120   function registerElementFilter($name, $call)
121   {
122     if (!isset($this->filters[$name])) {
123       $this->filters[$name]= $call;
124       return true;
125     }
127     return false;
128   }
131   function load($filename)
132   {
133     $contents = file_get_contents($filename);
134     $this->xmlData= xml::xml2array($contents, 1);
136     if (!isset($this->xmlData['list'])) {
137       return false;
138     }
140     $this->xmlData= $this->xmlData["list"];
142     // Load some definition values
143     foreach (array("departmentBrowser", "departmentRootVisible", "multiSelect", "baseMode") as $token) {
144       if (isset($this->xmlData['definition'][$token]) &&
145           $this->xmlData['definition'][$token] == "true"){
146         $this->$token= true;
147       }
148     }
150     // Fill objectTypes from departments and xml definition
151     $types = departmentManagement::get_support_departments();
152     foreach ($types as $class => $data) {
153       $this->objectTypes[]= array("label" => $data['TITLE'],
154                                   "objectClass" => $data['OC'],
155                                   "image" => $data['IMG']);
156     }
157     $this->categories= array();
158     if (isset($this->xmlData['definition']['objectType'])) {
159       if(isset($this->xmlData['definition']['objectType']['label'])) {
160         $this->xmlData['definition']['objectType']= array($this->xmlData['definition']['objectType']);
161       }
162       foreach ($this->xmlData['definition']['objectType'] as $index => $otype) {
163         $this->objectTypes[]= $this->xmlData['definition']['objectType'][$index];
164         if (isset($this->xmlData['definition']['objectType'][$index]['category'])){
165           $this->categories[]= $this->xmlData['definition']['objectType'][$index]['category'];
166         }
167       }
168     }
170     // Parse layout per column
171     $this->colprops= $this->parseLayout($this->xmlData['table']['layout']);
173     // Prepare table headers
174     $this->renderHeader();
176     // Assign headline/module
177     $this->headline= _($this->xmlData['definition']['label']);
178     $this->module= $this->xmlData['definition']['module'];
179     if (!is_array($this->categories)){
180       $this->categories= array($this->categories);
181     }
183     // Evaluate columns to be exported
184     if (isset($this->xmlData['table']['column'])){
185       foreach ($this->xmlData['table']['column'] as $index => $config) {
186         if (isset($config['export']) && $config['export'] == "true"){
187           $this->exportColumns[]= $index;
188         }
189       }
190     }
192     return true;  
193   }
196   function renderHeader()
197   {
198     $this->header= array();
199     $this->plainHeader= array();
201     // Initialize sort?
202     $sortInit= false;
203     if (!$this->sortDirection) {
204       $this->sortColumn= 0;
205       if (isset($this->xmlData['definition']['defaultSortColumn'])){
206         $this->sortColumn= $this->xmlData['definition']['defaultSortColumn'];
207       } else {
208         $this->sortAttribute= "";
209       }
210       $this->sortDirection= array();
211       $sortInit= true;
212     }
214     if (isset($this->xmlData['table']['column'])){
215       foreach ($this->xmlData['table']['column'] as $index => $config) {
216         // Initialize everything to one direction
217         if ($sortInit) {
218           $this->sortDirection[$index]= false;
219         }
221         $sorter= "";
222         if ($index == $this->sortColumn && isset($config['sortAttribute']) &&
223             isset($config['sortType'])) {
224           $this->sortAttribute= $config['sortAttribute'];
225           $this->sortType= $config['sortType'];
226           $sorter= "&nbsp;<img border='0' title='".($this->sortDirection[$index]?_("Up"):_("Down"))."' src='images/lists/sort-".($this->sortDirection[$index]?"up":"down").".png' align='top'>";
227         }
228         $sortable= (isset($config['sortAttribute']));
230         $link= "href='?plug=".$_GET['plug']."&amp;PID=".$this->pid."&amp;act=SORT_$index'";
231         if (isset($config['label'])) {
232           if ($sortable) {
233             $this->header[$index]= "<td class='listheader' ".$this->colprops[$index]."><a $link>"._($config['label'])."$sorter</a></td>";
234           } else {
235             $this->header[$index]= "<td class='listheader' ".$this->colprops[$index].">"._($config['label'])."</td>";
236           }
237           $this->plainHeader[]= _($config['label']);
238         } else {
239           if ($sortable) {
240             $this->header[$index]= "<td class='listheader' ".$this->colprops[$index]."><a $link>&nbsp;$sorter</a></td>";
241           } else {
242             $this->header[$index]= "<td class='listheader' ".$this->colprops[$index].">&nbsp;</td>";
243           }
244           $this->plainHeader[]= "";
245         }
246       }
247     }
248   }
250   function render()
251   {
252     // Check for exeeded sizelimit
253     if (($message= check_sizelimit()) != ""){
254       return($message);
255     }
257     // Initialize list
258     $result= "<input type='hidden' value='$this->pid' name='PID'>\n";
259     $result.= "<div class='contentboxb' id='listing_container' style='border-top:1px solid #B0B0B0;'>\n";
260     $result.= "<table summary='$this->headline' style='width:600px;height:450px;' cellspacing='0' id='t_scrolltable'>
261 <tr><td class='scrollhead'><table summary='' style='width:100%;' cellspacing='0' id='t_scrollhead'>\n";
262     $this->numColumns= count($this->colprops) + ($this->multiSelect?1:0);
264     // Build list header
265     $result.= "<tr>\n";
266     if ($this->multiSelect) {
267       $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";
268     }
269     foreach ($this->header as $header) {
270       $result.= $header;
271     }
273     // Add 13px for scroller
274     $result.= "<td class='listheader' style='width:13px;border-right:0px;'>&nbsp;</td></table></td></tr>\n";
276     // New table for the real list contents
277     $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";
279     // No results? Just take an empty colspanned row
280     if (count($this->entries) + count($this->departments) == 0) {
281       $result.= "<tr class='rowxp0'><td class='list1nohighlight' colspan='$this->numColumns' style='height:100%;border-right:0px;width:100%;'>&nbsp;</td></tr>";
282     }
284     // Line color alternation
285     $alt= 0;
286     $deps= 0;
288     // Draw department browser if configured and we're not in sub mode
289     if ($this->departmentBrowser && $this->filter->scope != "sub") {
290       // Fill with department browser if configured this way
291       $departmentIterator= new departmentSortIterator($this->departments, $this->sortDirection[$this->sortColumn]);
292       foreach ($departmentIterator as $row => $entry){
293         $result.="<tr class='rowxp".($alt&1)."'>";
295         // Render multi select if needed
296         if ($this->multiSelect) {
297           $result.="<td style='text-align:center;width:20px;' class='list1'>&nbsp;</td>";
298         }
300         // Render defined department columns, fill the rest with some stuff
301         $rest= $this->numColumns - 1;
302         foreach ($this->xmlData['table']['department'] as $index => $config) {
303           $colspan= 1;
304           if (isset($config['span'])){
305             $colspan= $config['span'];
306           }
307           $result.="<td colspan='$colspan' ".$this->colprops[$index]." class='list1'>".$this->renderCell($config['value'], $entry, $row)."</td>";
308           $rest-= $colspan;
309         }
311         // Fill remaining cols with nothing
312         $last= $this->numColumns - $rest;
313         for ($i= 0; $i<$rest; $i++){
314           $result.= "<td ".$this->colprops[$last+$i-1]." class='list1'>&nbsp;</td>";
315         }
316         $result.="</tr>";
318         $alt++;
319       }
320       $deps= $alt;
321     }
323     // Fill with contents, sort as configured
324     foreach ($this->entries as $row => $entry) {
325       $trow= "";
327       // Render multi select if needed
328       if ($this->multiSelect) {
329         $trow.="<td style='text-align:center;width:20px;' class='list0'><input type='checkbox' id='listing_selected_$row' name='listing_selected_$row'></td>\n";
330       }
332       foreach ($this->xmlData['table']['column'] as $index => $config) {
333         $renderedCell= $this->renderCell($config['value'], $entry, $row);
334         $trow.="<td ".$this->colprops[$index]." class='list0'>".$renderedCell."</td>\n";
336         // Save rendered column
337         $sort= preg_replace('/.*>([^<]+)<.*$/', '$1', $renderedCell);
338         $sort= preg_replace('/&nbsp;/', '', $sort);
339         if (preg_match('/</', $sort)){
340           $sort= "";
341         }
342         $this->entries[$row]["_sort$index"]= $sort;
343       }
345       // Save rendered entry
346       $this->entries[$row]['_rendered']= $trow;
347     }
349     // Complete list by sorting entries for _sort$index and appending them to the output
350     $entryIterator= new listingSortIterator($this->entries, $this->sortDirection[$this->sortColumn], "_sort".$this->sortColumn, $this->sortType);
351     foreach ($entryIterator as $row => $entry){
352       $alt++;
353       $result.="<tr class='rowxp".($alt&1)."'>\n";
354       $result.= $entry['_rendered'];
355       $result.="</tr>\n";
356     }
358     // Need to fill the list if it's not full (nobody knows why this is 22 ;-))
359     $emptyListStyle= (count($this->entries) + $deps == 0)?"border:0;":"";
360     if ((count($this->entries) + $deps) < 22) {
361       $result.= "<tr>";
362       for ($i= 0; $i<$this->numColumns; $i++) {
363         if ($i == 0) {
364           $result.= "<td class='list1nohighlight' style='$emptyListStyle height:100%;'>&nbsp;</td>";
365           continue;
366         }
367         if ($i != $this->numColumns-1) {
368           $result.= "<td class='list1nohighlight' style='$emptyListStyle'>&nbsp;</td>";
369         } else {
370           $result.= "<td class='list1nohighlight' style='border-right:1px solid #AAA;$emptyListStyle'>&nbsp;</td>";
371         }
372       }
373       $result.= "</tr>";
374     }
376     $result.= "</table></div></td></tr>";
378     // Add the footer if requested
379     if ($this->showFooter) {
380       $result.= "<tr><td class='scrollhead'><table summary='' style='width:100%' cellspacing='0' id='t_scrollfoot'><tr><td class='listfooter' style='border-bottom:0px;'>";
382       foreach ($this->objectTypes as $objectType) {
383         if (isset($this->objectTypeCount[$objectType['label']])) {
384           $label= _($objectType['label']);
385           $result.= "<img class='center' src='".$objectType['image']."' title='$label' alt='$label'>&nbsp;".$this->objectTypeCount[$objectType['label']]."&nbsp;&nbsp;&nbsp;&nbsp;";
386         }
387       }
389       $result.= "<td class='listfooter' style='width:13px;border-right:0px;'>&nbsp;</td></table></td></tr>";
390     }
392     $result.= "</table></div>";
394     $smarty= get_smarty();
395     $smarty->assign("FILTER", $this->filter->render());
396     $smarty->assign("SIZELIMIT", print_sizelimit_warning());
397     $smarty->assign("LIST", $result);
399     // Assign navigation elements
400     $nav= $this->renderNavigation();
401     foreach ($nav as $key => $html) {
402       $smarty->assign($key, $html);
403     }
405     // Assign action menu / base
406     $smarty->assign("ACTIONS", $this->renderActionMenu());
407     $smarty->assign("BASE", $this->renderBase());
409     // Assign separator
410     $smarty->assign("SEPARATOR", "<img src='images/lists/seperator.png' alt='-' align='middle' height='16' width='1' class='center'>");
412     // Assign summary
413     $smarty->assign("HEADLINE", $this->headline);
415     return ($smarty->fetch(get_template_path($this->xmlData['definition']['template'], true)));
416   }
419   function update()
420   {
421     global $config;
422     $ui= get_userinfo();
424     // Reset object counter
425     $this->objectTypeCount= array();
427     // Do not do anything if this is not our PID or there's even
428     // no PID available
429     if(!isset($_REQUEST['PID']) || $_REQUEST['PID'] != $this->pid) {
430       return;
431     }
433     // Save base
434     if (isset($_POST['BASE']) && $this->baseMode) {
435       $base= validate($_POST['BASE']);
436       if (isset($this->bases[$base])) {
437         $this->base= $base;
438       }
439     }
441     // Override the base if we got a message from the browser navigation
442     if ($this->departmentBrowser && isset($_GET['act'])) {
443       if (preg_match('/^department_([0-9]+)$/', validate($_GET['act']), $match)){
444         if (isset($this->departments[$match[1]])){
445           $this->base= $this->departments[$match[1]]['dn'];
446         }
447       }
448     }
450     // Filter POST with "act" attributes -> posted from action menu
451     if (isset($_POST['exec_act']) && $_POST['act'] != '') {
452       if (preg_match('/^export.*$/', $_POST['act']) && isset($this->exporter[$_POST['act']])) {
453         $exporter= $this->exporter[$_POST['act']];
454         $userinfo= ", "._("created by")." ".$ui->cn." - ".strftime('%A, %d. %B %Y, %H:%M:%S');
455         $instance= new $exporter['class']($this->headline.$userinfo, $this->plainHeader, $this->entries, $this->exportColumns);
456         $type= call_user_func(array($exporter['class'], "getInfo"));
457         $type= $type[$_POST['act']];
458         send_binary_content($instance->query(), $type['filename'], $type= $type['mime']);
459       }
460     }
462     // Filter GET with "act" attributes
463     if (isset($_GET['act'])) {
464       $key= validate($_GET['act']);
465       if (preg_match('/^SORT_([0-9]+)$/', $key, $match)) {
466         // Switch to new column or invert search order?
467         $column= $match[1];
468         if ($this->sortColumn != $column) {
469           $this->sortColumn= $column;
470         } else {
471           $this->sortDirection[$column]= !$this->sortDirection[$column];
472         }
474         // Allow header to update itself according to the new sort settings
475         $this->renderHeader();
476       }
477     }
479     // Override base if we got signals from the navigation elements
480     $action= "";
481     foreach ($_POST as $key => $value) {
482       if (preg_match('/^(ROOT|BACK|HOME)_x$/', $key, $match)) {
483         $action= $match[1];
484         break;
485       }
486     }
488     // Navigation handling
489     if ($action == 'ROOT') {
490       $deps= $ui->get_module_departments($this->module);
491       $this->base= $deps[0];
492     }
493     if ($action == 'BACK') {
494       $deps= $ui->get_module_departments($this->module);
495       $base= preg_replace("/^[^,]+,/", "", $this->base);
496       if(in_array_ics($base, $deps)){
497         $this->base= $base;
498       }
499     }
500     if ($action == 'HOME') {
501       $ui= get_userinfo();
502       $this->base= get_base_from_people($ui->dn);
503     }
505     // Reload departments
506     if ($this->departmentBrowser){
507       $this->departments= $this->getDepartments();
508     }
510     // Update filter and refresh entries
511     $this->filter->setBase($this->base);
512     $this->entries= $this->filter->query();
513   }
516   function setBase($base)
517   {
518     $this->base= $base;
519   }
522   function getBase()
523   {
524     return $this->base;
525   }
528   function parseLayout($layout)
529   {
530     $result= array();
531     $layout= preg_replace("/^\|/", "", $layout);
532     $layout= preg_replace("/\|$/", "", $layout);
533     $cols= split("\|", $layout);
534     foreach ($cols as $index => $config) {
535       if ($config != "") {
536         $components= split(';', $config);
537         $config= "";
538         foreach ($components as $part) {
539           if (preg_match("/^r$/", $part)) {
540             $config.= "text-align:right;";
541             continue;
542           }
543           if (preg_match("/^l$/", $part)) {
544             $config.= "text-align:left;";
545             continue;
546           }
547           if (preg_match("/^c$/", $part)) {
548             $config.= "text-align:center;";
549             continue;
550           }
551           if (preg_match("/^[0-9]+(|px|%)$/", $part)) {
552             $config.= "width:$part;";
553             continue;
554           }
555         }
557         $result[$index]= " style='$config' ";
558       } else {
559         $result[$index]= null;
560       }
561     }
563     // Save number of columns for later use
564     $this->numColumns= count($cols);
566     return $result;
567   }
570   function renderCell($data, $config, $row)
571   {
572     // Replace flat attributes in data string
573     for ($i= 0; $i<$config['count']; $i++) {
574       $attr= $config[$i];
575       $value= "";
576       if (is_array($config[$attr])) {
577         $value= $config[$attr][0];
578       } else {
579         $value= $config[$attr];
580       }
581       $data= preg_replace("/%\{$attr\}/", $value, $data);
582     }
584     // Watch out for filters and prepare to execute them
585     $data= $this->processElementFilter($data, $config, $row);
587     // Replace all non replaced %{...} instances because they
588     // are non resolved attributes or filters
589     $data= preg_replace('/%{[^}]+}/', '&nbsp;', $data);
591     return $data;
592   }
595   function renderBase()
596   {
597     if (!$this->baseMode) {
598       return;
599     }
601     $result= "<select name='BASE' onChange='mainform.submit()' size='1'>";
602     $firstDN= null;
603     $found= false;
605     foreach ($this->bases as $key=>$value) {
606       // Keep first entry to fall back eventually
607       if(!$firstDN) {
608         $firstDN= $key;
609       }
611       // Prepare to render entry
612       $selected= "";
613       if ($key == $this->base) {
614         $selected= " selected";
615         $found= true;
616       }
617       $result.= "<option value='".$key."'$selected>".$value."</option>";
618     }
619     $result.= "</select>";
621     // Reset the currently used base to the first DN we found if there
622     // was no match.
623     if(!$found){
624       $this->base = $firstDN;
625     }
627     return $result;
628   }
631   function processElementFilter($data, $config, $row)
632   {
633     preg_match_all("/%\{filter:([^(]+)\((.*)\)\}/", $data, $matches, PREG_SET_ORDER);
635     foreach ($matches as $match) {
636       if (!isset($this->filters[$match[1]])) {
637         continue;
638       }
639       $cl= preg_replace('/::.*$/', '', $this->filters[$match[1]]);
640       $method= preg_replace('/^.*::/', '', $this->filters[$match[1]]);
642       // Prepare params for function call
643       $params= array();
644       preg_match_all('/"[^"]+"|[^,]+/', $match[2], $parts);
645       foreach ($parts[0] as $param) {
647         // Row is replaced by the row number
648         if ($param == "row") {
649           $params[]= $row;
650         }
652         // pid is replaced by the current PID
653         if ($param == "pid") {
654           $params[]= $this->pid;
655         }
657         // Fixie with "" is passed directly
658         if (preg_match('/^".*"$/', $param)){
659           $params[]= preg_replace('/"/', '', $param);
660         }
662         // LDAP variables get replaced by their objects
663         for ($i= 0; $i<$config['count']; $i++) {
664           if ($param == $config[$i]) {
665             $values= $config[$config[$i]];
666             if (is_array($values)){
667               unset($values['count']);
668             }
669             $params[]= $values;
670           }
671         }
673         // Move dn if needed
674         if ($param == "dn") {
675           $params[]= LDAP::fix($config["dn"]);
676         }
677       }
679       // Replace information
680       if ($cl == "listing") {
681         // Non static call - seems to result in errors
682         $data= @preg_replace('/'.preg_quote($match[0]).'/', call_user_func_array(array($this, "$method"), $params), $data);
683       } else {
684         // Static call
685         $data= preg_replace('/'.preg_quote($match[0]).'/', call_user_func_array(array($cl, $method), $params), $data);
686       }
687     }
689     return $data;
690   }
693   function getObjectType($types, $classes)
694   {
695     // Walk thru types and see if there's something matching
696     foreach ($types as $objectType) {
697       $ocs= $objectType['objectClass'];
698       if (!is_array($ocs)){
699         $ocs= array($ocs);
700       }
702       $found= true;
703       foreach ($ocs as $oc){
704         if (preg_match('/^!(.*)$/', $oc, $match)) {
705           $oc= $match[1];
706           if (in_array($oc, $classes)) {
707             $found= false;
708           }
709         } else {
710           if (!in_array($oc, $classes)) {
711             $found= false;
712           }
713         }
714       }
716       if ($found) {
717         return $objectType;
718       }
719     }
721     return null;
722   }
725   function filterObjectType($dn, $classes)
726   {
727     // Walk thru classes and return on first match
728     $result= "&nbsp;";
730     $objectType= $this->getObjectType($this->objectTypes, $classes);
731     if ($objectType) {
732       $result= "<img class='center' title='".LDAP::fix($dn)."' src='".$objectType["image"]."'>";
733       if (!isset($this->objectTypeCount[$objectType['label']])) {
734         $this->objectTypeCount[$objectType['label']]= 0;
735       }
736       $this->objectTypeCount[$objectType['label']]++;
737     }
738     return $result;
739   }
742   function filterActions($dn, $row, $classes)
743   {
744     // Do nothing if there's no menu defined
745     if (!isset($this->xmlData['actiontriggers']['action'])) {
746       return "&nbsp;";
747     }
749     // Go thru all actions
750     $result= "";
751     $actions= $this->xmlData['actiontriggers']['action'];
752     foreach($actions as $action) {
753       // Skip the entry completely if there's no permission to execute it
754       if (!$this->hasActionPermission($action, $dn)) {
755         continue;
756       }
758       // If there's an objectclass definition and we don't have it
759       // add an empty picture here.
760       if (isset($action['objectclass'])){
761         $objectclass= $action['objectclass'];
762         if (preg_match('/^!(.*)$/', $objectclass, $m)){
763           $objectclass= $m[1];
764           if(in_array($objectclass, $classes)) {
765             $result.= "<img src='images/empty.png' alt=' ' class='center' style='padding:1px'>";
766             continue;
767           }
768         } else {
769           if(!in_array($objectclass, $classes)) {
770             $result.= "<img src='images/empty.png' alt=' ' class='center' style='padding:1px'>";
771             continue;
772           }
773         }
774       }
776       // Render normal entries as usual
777       if ($action['type'] == "entry") {
778         $label= $this->processElementFilter($action['label'], $this->entries[$row], $row);
779         $image= $this->processElementFilter($action['image'], $this->entries[$row], $row);
780         $result.="<input class='center' type='image' src='$image' title='$label' ".
781                  "name='listing_".$action['name']."_$row' style='padding:1px'>";
782       }
784       // Handle special types
785       if ($action['type'] == "copypaste" || $action['type'] == "snapshot") {
787         $objectType= $this->getObjectType($this->objectTypes, $this->entries[$row]['objectClass']);
788         $category= $class= null;
789         if ($objectType) {
790           $category= $objectType['category'];
791           $class= $objectType['class'];
792         }
794         if ($action['type'] == "copypaste") {
795           $result.= $this->renderCopyPasteActions($row, $this->entries[$row]['dn'], $category, $class);
796         } else {
797           $result.= $this->renderSnapshotActions($row, $this->entries[$row]['dn'], $category, $class);
798         }
799       }
800     }
802     return $result;
803   }
806   function filterDepartmentLink($row, $dn, $description)
807   {
808     $attr= $this->departments[$row]['sort-attribute'];
809     $name= $this->departments[$row][$attr];
810     if (is_array($name)){
811       $name= $name[0];
812     }
813     $result= sprintf("%s [%s]", $name, $description[0]);
814     return("<a href='?plug=".$_GET['plug']."&amp;PID=$this->pid&amp;act=department_$row' title='$dn'>$result</a>");
815   }
818   function filterLink()
819   {
820     $result= "&nbsp;";
822     $row= func_get_arg(0);
823     $pid= $this->pid;
824     $dn= LDAP::fix(func_get_arg(1));
825     $params= array(func_get_arg(2));
827     // Collect sprintf params
828     for ($i = 3;$i < func_num_args();$i++) {
829       $val= func_get_arg($i);
830       if (is_array($val)){
831         $params[]= $val[0];
832         continue;
833       }
834       $params[]= $val;
835     }
837     $result= "&nbsp;";
838     $trans= call_user_func_array("sprintf", $params);
839     if ($trans != "") {
840       return("<a href='?plug=".$_GET['plug']."&amp;PID=$pid&amp;act=listing_edit_$row' title='$dn'>$trans</a>");
841     }
843     return $result;
844   }
847   function renderNavigation()
848   {
849     $result= array();
850     $enableBack = true;
851     $enableRoot = true;
852     $enableHome = true;
854     $ui = get_userinfo();
856     /* Check if base = first available base */
857     $deps = $ui->get_module_departments($this->module);
859     if(!count($deps) || $deps[0] == $this->filter->base){
860       $enableBack = false;
861       $enableRoot = false;
862     }
864     $listhead ="";
866     /* Check if we are in users home  department */
867     if(!count($deps) ||$this->filter->base == get_base_from_people($ui->dn)){
868       $enableHome = false;
869     }
871     /* Draw root button */
872     if($enableRoot){
873       $result["ROOT"]= "<input class='center' type='image' src='images/lists/root.png' align='middle' ".
874                        "title='"._("Go to root department")."' name='ROOT' alt='"._("Root")."'>";
875     }else{
876       $result["ROOT"]= "<img src='images/lists/root_grey.png' class='center' alt='"._("Root")."'>";
877     }
879     /* Draw back button */
880     if($enableBack){
881       $result["BACK"]= "<input class='center' type='image' align='middle' src='images/lists/back.png' ".
882                        "title='"._("Go up one department")."' alt='"._("Up")."' name='BACK'>";
883     }else{
884       $result["BACK"]= "<img src='images/lists/back_grey.png' class='center' alt='"._("Up")."'>";
885     }
887     /* Draw home button */
888     if($enableHome){
889       $result["HOME"]= "<input class='center' type='image' align='middle' src='images/lists/home.png' ".
890                        "title='"._("Go to users department")."' alt='"._("Home")."' name='HOME'>";
891     }else{
892       $result["HOME"]= "<img src='images/lists/home_grey.png' class='center' alt='"._("Home")."'>";
893     }
895     /* Draw reload button, this button is enabled everytime */
896     $result["RELOAD"]= "<input class='center' type='image' src='images/lists/reload.png' align='middle' ".
897                        "title='"._("Reload list")."' name='REFRESH' alt='"._("Submit")."'>";
899     return ($result);
900   }
903   function getAction()
904   {
905     // Do not do anything if this is not our PID, or there's even no PID available...
906     if(!isset($_REQUEST['PID']) || $_REQUEST['PID'] != $this->pid) {
907       return;
908     }
910     $result= array("targets" => array(), "action" => "");
912     // Filter GET with "act" attributes
913     if (isset($_GET['act'])) {
914       $key= validate($_GET['act']);
915       $target= preg_replace('/^listing_[a-zA-Z_]+_([0-9]+)$/', '$1', $key);
916       if (isset($this->entries[$target]['dn'])) {
917         $result['action']= preg_replace('/^listing_([a-zA-Z_]+)_[0-9]+$/', '$1', $key);
918         $result['targets'][]= $this->entries[$target]['dn'];
919       }
921       // Drop targets if empty
922       if (count($result['targets']) == 0) {
923         unset($result['targets']);
924       }
925       return $result;
926     }
928     // Filter POST with "listing_" attributes
929     foreach ($_POST as $key => $prop) {
931       // Capture selections
932       if (preg_match('/^listing_selected_[0-9]+$/', $key)) {
933         $target= preg_replace('/^listing_selected_([0-9]+)$/', '$1', $key);
934         if (isset($this->entries[$target]['dn'])) {
935           $result['targets'][]= $this->entries[$target]['dn'];
936         }
937         continue;
938       }
940       // Capture action with target - this is a one shot
941       if (preg_match('/^listing_[a-zA-Z_]+_[0-9]+(|_x)$/', $key)) {
942         $target= preg_replace('/^listing_[a-zA-Z_]+_([0-9]+)(|_x)$/', '$1', $key);
943         if (isset($this->entries[$target]['dn'])) {
944           $result['action']= preg_replace('/^listing_([a-zA-Z_]+)_[0-9]+(|_x)$/', '$1', $key);
945           $result['targets']= array($this->entries[$target]['dn']);
946         }
947         break;
948       }
950       // Capture action without target
951       if (preg_match('/^listing_[a-zA-Z_]+(|_x)$/', $key)) {
952         $result['action']= preg_replace('/^listing_([a-zA-Z_]+)(|_x)$/', '$1', $key);
953         continue;
954       }
955     }
957     // Filter POST with "act" attributes -> posted from action menu
958     if (isset($_POST['act']) && $_POST['act'] != '') {
959       if (!preg_match('/^export.*$/', $_POST['act'])){
960         $result['action']= validate($_POST['act']);
961       }
962     }
964     // Drop targets if empty
965     if (count($result['targets']) == 0) {
966       unset($result['targets']);
967     }
968     return $result;
969   }
972   function renderActionMenu()
973   {
974     // Don't send anything if the menu is not defined
975     if (!isset($this->xmlData['actionmenu']['action'])){
976       return "";
977     }
979     // Load shortcut
980     $actions= &$this->xmlData['actionmenu']['action'];
981     $result= "<input type='hidden' name='act' id='actionmenu' value=''><div style='display:none'><input type='submit' name='exec_act' id='exec_act' value=''></div>".
982              "<ul class='level1' id='root'><li><a href='#'>Aktionen&nbsp;<img ".
983              "border=0 class='center' src='images/lists/sort-down.png'></a>";
985     // Build ul/li list
986     $result.= $this->recurseActions($actions);
988     return "<div id='pulldown'>".$result."</li></ul><div>";
989   }
992   function recurseActions($actions)
993   {
994     static $level= 2;
995     $result= "<ul class='level$level'>";
996     $separator= "";
998     foreach ($actions as $action) {
1000       // Skip the entry completely if there's no permission to execute it
1001       if (!$this->hasActionPermission($action, $this->filter->base)) {
1002         continue;
1003       }
1005       // Fill image if set
1006       $img= "";
1007       if (isset($action['image'])){
1008         $img= "<img border='0' class='center' src='".$action['image']."'>&nbsp;";
1009       }
1011       if ($action['type'] == "separator"){
1012         $separator= " style='border-top:1px solid #AAA' ";
1013         continue;
1014       }
1016       // Dive into subs
1017       if ($action['type'] == "sub" && isset($action['action'])) {
1018         $level++;
1019         if (isset($action['label'])){
1020           $result.= "<li$separator><a href='#'>$img"._($action['label'])."&nbsp;<img border='0' src='images/forward-arrow.png'></a>";
1021         }
1022         $result.= $this->recurseActions($action['action'])."</li>";
1023         $level--;
1024         $separator= "";
1025         continue;
1026       }
1028       // Render entry elseways
1029       if (isset($action['label'])){
1030         $result.= "<li$separator><a href='#' onClick='document.getElementById(\"actionmenu\").value= \"".$action['name']."\";mainform.submit();'>$img"._($action['label'])."</a></li>";
1031       }
1033       // Check for special types
1034       switch ($action['type']) {
1035         case 'copypaste':
1036           $result.= $this->renderCopyPasteMenu($separator);
1037           break;
1039         case 'snapshot':
1040           $result.= $this->renderSnapshotMenu($separator);
1041           break;
1043         case 'exporter':
1044           $result.= $this->renderExporterMenu($separator);
1045           break;
1047         case 'daemon':
1048           $result.= $this->renderDaemonMenu($separator);
1049           break;
1050       }
1052       $separator= "";
1053     }
1055     $result.= "</ul>";
1056     return $result;
1057   }
1060   function hasActionPermission($action, $dn)
1061   {
1062     $ui= get_userinfo();
1064     if (isset($action['acl'])) {
1065       $acls= $action['acl'];
1066       if (!is_array($acls)) {
1067         $acls= array($acls);
1068       }
1070       // Every ACL has to pass
1071       foreach ($acls as $acl) {
1072         $module= $this->module;
1073         $aclList= array();
1075         // Split for category and plugins if needed
1076         // match for "[rw]" style entries
1077         if (preg_match('/^\[([rwcdm]+)\]$/', $acl, $match)){
1078           $aclList= array($match[1]);
1079         }
1081         // match for "users[rw]" style entries
1082         if (preg_match('/^([a-zA-Z0-9]+)\[([rwcdm]+)\]$/', $acl, $match)){
1083           $module= $match[1];
1084           $aclList= array($match[2]);
1085         }
1087         // match for "users/user[rw]" style entries
1088         if (preg_match('/^([a-zA-Z0-9]+\/[a-zA-Z0-9]+)\[([rwcdm]+)\]$/', $acl, $match)){
1089           $module= $match[1];
1090           $aclList= array($match[2]);
1091         }
1093         // match "users/user[userPassword:rw(,...)*]" style entries
1094         if (preg_match('/^([a-zA-Z0-9]+\/[a-zA-Z0-9]+)\[([a-zA-Z0-9]+:[rwcdm]+(,[a-zA-Z0-9]+:[rwcdm]+)*)\]$/', $acl, $match)){
1095           $module= $match[1];
1096           $aclList= split(',', $match[2]);
1097         }
1099         // Walk thru prepared ACL by using $module
1100         foreach($aclList as $sAcl) {
1101           $checkAcl= "";
1103           // Category or detailed permission?
1104           if (strpos('/', $module) === false) {
1105             if (preg_match('/([a-zA-Z0-9]+):([rwcdm]+)/', $sAcl, $m) ) {
1106               $checkAcl= $ui->get_permissions($dn, $module, $m[1]);
1107               $sAcl= $m[2];
1108             } else {
1109               $checkAcl= $ui->get_permissions($dn, $module, '0');
1110             }
1111           } else {
1112             $checkAcl= $ui->get_category_permissions($dn, $module);
1113           }
1115           // Split up remaining part of the acl and check if it we're
1116           // allowed to do something...
1117           $parts= str_split($sAcl);
1118           foreach ($parts as $part) {
1119             if (strpos($checkAcl, $part) === false){
1120               return false;
1121             }
1122           }
1124         }
1125       }
1126     }
1128     return true;
1129   }
1132   function refreshBasesList()
1133   {
1134     global $config;
1135     $ui= get_userinfo();
1137     // Do some array munching to get it user friendly
1138     $ids= $config->idepartments;
1139     $d= $ui->get_module_departments($this->module);
1140     $k_ids= array_keys($ids);
1141     $deps= array_intersect($d,$k_ids);
1143     // Fill internal bases list
1144     $this->bases= array();
1145     foreach($k_ids as $department){
1146       $this->bases[$department] = $ids[$department];
1147     }
1148   }
1151   function getDepartments()
1152   {
1153     $departments= array();
1154     $ui= get_userinfo();
1156     // Get list of supported department types
1157     $types = departmentManagement::get_support_departments();
1159     // Load departments allowed by ACL
1160     $validDepartments = $ui->get_module_departments($this->module);
1162     // Build filter and look in the LDAP for possible sub departments
1163     // of current base
1164     $filter= "(&(objectClass=gosaDepartment)(|";
1165     $attrs= array("description", "objectClass");
1166     foreach($types as $name => $data){
1167       $filter.= "(objectClass=".$data['OC'].")";
1168       $attrs[]= $data['ATTR'];
1169     }
1170     $filter.= "))";
1171     $res= get_list($filter, $this->module, $this->base, $attrs, GL_NONE | GL_SIZELIMIT);
1173     // Analyze list of departments
1174     foreach ($res as $department) {
1175       if (!in_array($department['dn'], $validDepartments)) {
1176         continue;
1177       }
1179       // Add the attribute where we use for sorting
1180       $oc= null;
1181       foreach(array_keys($types) as $type) {
1182         if (in_array($type, $department['objectClass'])) {
1183           $oc= $type;
1184           break;
1185         }
1186       }
1187       $department['sort-attribute']= $types[$oc]['ATTR'];
1189       // Move to the result list
1190       $departments[]= $department;
1191     }
1193     return $departments;
1194   }
1197   function renderCopyPasteMenu($separator, $copy= true, $cut= true)
1198   {
1199     // We can only provide information if we've got a copypaste handler
1200     // instance
1201     if(!(isset($this->copyPasteHandler) && is_object($this->copyPasteHandler))){
1202       return "";
1203     }
1205     // Presets
1206     $result= "";
1207     $read= $paste= false;
1208     $ui= get_userinfo();
1210     // Switch flags to on if there's at least one category which allows read/paste
1211     foreach($this->categories as $category){
1212       $read= $read || preg_match('/r/', $ui->get_category_permissions($this->base, $category));
1213       $paste= $paste || $ui->is_pasteable($this->base, $category) == 1;
1214     }
1217     // Draw entries that allow copy and cut
1218     if($read){
1220       // Copy entry
1221       if($copy){
1222         $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>";
1223         $separator= "";
1224       }
1226       // Cut entry
1227       if($cut){
1228         $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>";
1229         $separator= "";
1230       }
1231     }
1233     // Draw entries that allow pasting entries
1234     if($paste){
1235       if($this->copyPasteHandler->entries_queued()){
1236         $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>";
1237       }else{
1238         $result.= "<li$separator><a href='#'><img src='images/lists/paste-grey.png' alt='' border='0' class='center'>&nbsp;"._("Paste")."</a></li>";
1239       }
1240     }
1241     
1242     return($result);
1243   }
1246   function renderCopyPasteActions($row, $dn, $category, $class, $copy= true, $cut= true)
1247   {
1248     // We can only provide information if we've got a copypaste handler
1249     // instance
1250     if(!(isset($this->copyPasteHandler) && is_object($this->copyPasteHandler))){
1251       return "";
1252     }
1254     // Presets
1255     $ui = get_userinfo();
1256     $result = "";
1258     // Render cut entries
1259     if($cut){
1260       if($ui->is_cutable($dn, $category, $class)){
1261         $result .= "<input class='center' type='image'
1262           src='images/lists/cut.png' alt='"._("Cut")."' name='listing_cut_$row' title='"._("Cut this entry")."' style='padding:1px'>";
1263       }else{
1264         $result.="<img src='images/empty.png' alt=' ' class='center' style='padding:1px'>";
1265       }
1266     }
1268     // Render copy entries
1269     if($copy){
1270       if($ui->is_copyable($dn, $category, $class)){
1271         $result.= "<input class='center' type='image'
1272           src='images/lists/copy.png' alt='"._("Copy")."' name='listing_copy_$row' title='"._("Copy this entry")."' style='padding:1px'>";
1273       }else{
1274         $result.="<img src='images/empty.png' alt=' ' class='center' style='padding:1px'>";
1275       }
1276     }
1278     return($result);
1279   }
1282   function renderSnapshotMenu($separator)
1283   {
1284     // We can only provide information if we've got a snapshot handler
1285     // instance
1286     if(!(isset($this->snapshotHandler) && is_object($this->snapshotHandler))){
1287       return "";
1288     }
1290     // Presets
1291     $result = "";
1292     $ui = get_userinfo();
1294     if($this->snapshotHandler->enabled() && $ui->allow_snapshot_restore($this->base, $this->module)){
1296       // Check if there is something to restore
1297       $restore= false;
1298       foreach($this->snapshotHandler->getSnapshotBases() as $base){
1299         $restore= $restore || count($this->snapshotHandler->getDeletedSnapshots($base)) > 0;
1300       }
1302       // Draw icons according to the restore flag
1303       if($restore){
1304         $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>";
1305       }else{
1306         $result.= "<li$separator><a href='#'><img src='images/lists/restore_grey.png' alt='' border='0' class='center'>&nbsp;"._("Restore snapshots")."</a></li>";
1307       }
1308     }
1310     return($result);
1311   }
1314   function renderExporterMenu($separator)
1315   {
1316     // Presets
1317     $result = "";
1319     // Draw entries
1320     $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'>";
1322     // Export CVS as build in exporter
1323     foreach ($this->exporter as $action => $exporter) {
1324       $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>";
1325     }
1327     // Finalize list
1328     $result.= "</ul></li>";
1330     return($result);
1331   }
1334   function renderSnapshotActions($row, $dn, $category, $class, $copy= true, $cut= true)
1335   {
1336     // We can only provide information if we've got a snapshot handler
1337     // instance
1338     if(!(isset($this->snapshotHandler) && is_object($this->snapshotHandler))){
1339       return "";
1340     }
1342     // Presets
1343     $result= "";
1344     $ui = get_userinfo();
1346     // Only act if enabled here
1347     if($this->snapshotHandler->enabled()){
1349       // Draw restore button
1350       if ($ui->allow_snapshot_restore($dn, $category)){
1352         // Do we have snapshots for this dn?
1353         if($this->snapshotHandler->hasSnapshots($dn)){
1354           $result.= "<input class='center' type='image' src='images/lists/restore.png' ".
1355                      "alt='"._("Restore snapshot")."' name='listing_restore_$row' title='".
1356                      _("Restore snapshot")."' style='padding:1px'>";
1357         } else {
1358           $result.= "<img src='images/lists/restore_grey.png' alt=' ' class='center' style='padding:1px'>";
1359         }
1360       }
1362       // Draw snapshot button
1363       if($ui->allow_snapshot_create($dn, $category)){
1364           $result.= "<input class='center' type='image' src='images/snapshot.png' ".
1365                      "alt='"._("Create snapshot")."' name='listing_snapshot_$row' title='".
1366                      _("Create a new snapshot from this object")."' style='padding:1px'>";
1367       }else{
1368           $result.= "<img src='images/empty.png' alt=' ' class='center' style='padding:1px'>";
1369       }
1370     }
1372     return($result);
1373   }
1376   function renderDaemonMenu($separator)
1377   {
1378     $result= "";
1380     // If there is a daemon registered, draw the menu entries
1381     if(class_available("DaemonEvent")){
1382       $events= DaemonEvent::get_event_types_by_category($this->categories);
1383       if(isset($events['BY_CLASS']) && count($events['BY_CLASS'])){
1384         foreach($events['BY_CLASS'] as $name => $event){
1385           $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>";
1386           $separator= "";
1387         }
1388       }
1389     }
1391     return $result;
1392   }
1396 ?>