Code

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