Code

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