Code

26eca3d1fda152d8325d70262ed1830557456eef
[gosa.git] / gosa-core / include / class_listing.inc
1 <?php
2 /*
3  * This code is part of GOsa (http://www.gosa-project.org)
4  * Copyright (C) 2003-2008 GONICUS GmbH
5  *
6  * ID: $$Id$$
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
23 class listing {
25   var $xmlData;
26   var $entries;
27   var $departments= array();
28   var $departmentBrowser= false;
29   var $departmentRootVisible= false;
30   var $multiSelect= false;
31   var $template;
32   var $headline;
33   var $module;
34   var $base;
35   var $sortDirection= null;
36   var $sortColumn= null;
37   var $sortAttribute;
38   var $sortType;
39   var $numColumns;
40   var $baseMode= false;
41   var $bases= array();
42   var $header= array();
43   var $colprops= array();
44   var $filters= array();
45   var $pid;
46   var $objectTypes= array();
47   var $objectTypeCount= array();
48   var $copyPasteHandler= null;
49   var $snapshotHandler= null;
50   var $exporter= array();
51   var $exportColumns= array();
54   function listing($filename)
55   {
56     global $config;
57     global $class_mapping;
59     // Initialize pid
60     $this->pid= preg_replace("/[^0-9]/", "", microtime(TRUE));
62     if (!$this->load($filename)) {
63       die("Cannot parse $filename!");
64     }
66     // Set base for filter
67     if ($this->baseMode) {
68       $this->base= session::global_get("CurrentMainBase");
69       if ($this->base == null) {
70         $this->base= $config->current['BASE'];
71       }
72       $this->refreshBasesList();
73     } else {
74       $this->base= $config->current['BASE'];
75     }
77     // Move footer information
78     $this->showFooter= ($config->get_cfg_value("listSummary") == "true");
80     // Register build in filters
81     $this->registerElementFilter("objectType", "listing::filterObjectType");
82     $this->registerElementFilter("departmentLink", "listing::filterDepartmentLink");
83     $this->registerElementFilter("link", "listing::filterLink");
84     $this->registerElementFilter("actions", "listing::filterActions");
86     // Load exporters
87     foreach($class_mapping as $class => $dummy) {
88       if (preg_match('/Exporter$/', $class)) {
89         $info= call_user_func(array($class, "getInfo"));
90         if ($info != null) {
91           $this->exporter= array_merge($this->exporter, $info);
92         }
93       }
94     }
95   }
98   function setCopyPasteHandler($handler)
99   {
100     $this->copyPasteHandler= &$handler;
101   }
104   function setSnapshotHandler($handler)
105   {
106     $this->snapshotHandler= &$handler;
107   }
110   function setFilter($filter)
111   {
112     $this->filter= &$filter;
113     if ($this->departmentBrowser){
114       $this->departments= $this->getDepartments();
115     }
116     $this->filter->setBase($this->base);
117   }
120   function registerElementFilter($name, $call)
121   {
122     if (!isset($this->filters[$name])) {
123       $this->filters[$name]= $call;
124       return true;
125     }
127     return false;
128   }
131   function load($filename)
132   {
133     $contents = file_get_contents($filename);
134     $this->xmlData= xml::xml2array($contents, 1);
136     if (!isset($this->xmlData['list'])) {
137       return false;
138     }
140     $this->xmlData= $this->xmlData["list"];
142     // Load some definition values
143     foreach (array("departmentBrowser", "departmentRootVisible", "multiSelect", "baseMode") as $token) {
144       if (isset($this->xmlData['definition'][$token]) &&
145           $this->xmlData['definition'][$token] == "true"){
146         $this->$token= true;
147       }
148     }
150     // Fill objectTypes from departments and xml definition
151     $types = departmentManagement::get_support_departments();
152     foreach ($types as $class => $data) {
153       $this->objectTypes[]= array("label" => $data['TITLE'],
154                                   "objectClass" => $data['OC'],
155                                   "image" => $data['IMG']);
156     }
157     $this->categories= array();
158     if (isset($this->xmlData['definition']['objectType'])) {
159       if(isset($this->xmlData['definition']['objectType']['label'])) {
160         $this->xmlData['definition']['objectType']= array($this->xmlData['definition']['objectType']);
161       }
162       foreach ($this->xmlData['definition']['objectType'] as $index => $otype) {
163         $this->objectTypes[]= $this->xmlData['definition']['objectType'][$index];
164         if (isset($this->xmlData['definition']['objectType'][$index]['category'])){
165           $this->categories[]= $this->xmlData['definition']['objectType'][$index]['category'];
166         }
167       }
168     }
170     // Parse layout per column
171     $this->colprops= $this->parseLayout($this->xmlData['table']['layout']);
173     // Prepare table headers
174     $this->renderHeader();
176     // Assign headline/module
177     $this->headline= _($this->xmlData['definition']['label']);
178     $this->module= $this->xmlData['definition']['module'];
179     if (!is_array($this->categories)){
180       $this->categories= array($this->categories);
181     }
183     // Evaluate columns to be exported
184     if (isset($this->xmlData['table']['column'])){
185       foreach ($this->xmlData['table']['column'] as $index => $config) {
186         if (isset($config['export']) && $config['export'] == "true"){
187           $this->exportColumns[]= $index;
188         }
189       }
190     }
192     return true;  
193   }
196   function renderHeader()
197   {
198     $this->header= array();
199     $this->plainHeader= array();
201     // Initialize sort?
202     $sortInit= false;
203     if (!$this->sortDirection) {
204       $this->sortColumn= 0;
205       if (isset($this->xmlData['definition']['defaultSortColumn'])){
206         $this->sortColumn= $this->xmlData['definition']['defaultSortColumn'];
207       } else {
208         $this->sortAttribute= "";
209       }
210       $this->sortDirection= array();
211       $sortInit= true;
212     }
214     if (isset($this->xmlData['table']['column'])){
215       foreach ($this->xmlData['table']['column'] as $index => $config) {
216         // Initialize everything to one direction
217         if ($sortInit) {
218           $this->sortDirection[$index]= false;
219         }
221         $sorter= "";
222         if ($index == $this->sortColumn && isset($config['sortAttribute']) &&
223             isset($config['sortType'])) {
224           $this->sortAttribute= $config['sortAttribute'];
225           $this->sortType= $config['sortType'];
226           $sorter= "&nbsp;<img border='0' title='".($this->sortDirection[$index]?_("Up"):_("Down"))."' src='images/lists/sort-".($this->sortDirection[$index]?"up":"down").".png' align='top'>";
227         }
228         $sortable= (isset($config['sortAttribute']));
230         $link= "href='?plug=".$_GET['plug']."&amp;PID=".$this->pid."&amp;act=SORT_$index'";
231         if (isset($config['label'])) {
232           if ($sortable) {
233             $this->header[$index]= "<td class='listheader' ".$this->colprops[$index]."><a $link>"._($config['label'])."$sorter</a></td>";
234           } else {
235             $this->header[$index]= "<td class='listheader' ".$this->colprops[$index].">"._($config['label'])."</td>";
236           }
237           $this->plainHeader[]= _($config['label']);
238         } else {
239           if ($sortable) {
240             $this->header[$index]= "<td class='listheader' ".$this->colprops[$index]."><a $link>&nbsp;$sorter</a></td>";
241           } else {
242             $this->header[$index]= "<td class='listheader' ".$this->colprops[$index].">&nbsp;</td>";
243           }
244           $this->plainHeader[]= "";
245         }
246       }
247     }
248   }
250   function render()
251   {
252     // Check for exeeded sizelimit
253     if (($message= check_sizelimit()) != ""){
254       return($message);
255     }
257     // Initialize list
258     $result= "<input type='hidden' value='$this->pid' name='PID'>\n";
259     $result.= "<div class='contentboxb' id='listing_container' style='border-top:1px solid #B0B0B0;'>\n";
260     $result.= "<table summary='$this->headline' style='width:600px;height:450px;' cellspacing='0' id='t_scrolltable'>
261 <tr><td class='scrollhead'><table summary='' style='width:100%;' cellspacing='0' id='t_scrollhead'>\n";
262     $this->numColumns= count($this->colprops) + ($this->multiSelect?1:0);
264     // Build list header
265     $result.= "<tr>\n";
266     if ($this->multiSelect) {
267       $result.= "<td class='listheader' style='width:20px;'><input type='checkbox' id='select_all' name='select_all' title='"._("Select all")."' onClick='toggle_all_(\"listing_selected_[0-9]*$\",\"select_all\");' ></td>\n";
268     }
269     foreach ($this->header as $header) {
270       $result.= $header;
271     }
273     // Add 13px for scroller
274     $result.= "<td class='listheader' style='width:13px;border-right:0px;'>&nbsp;</td></table></td></tr>\n";
276     // New table for the real list contents
277     $result.= "<tr><td colspan='$this->numColumns' class='scrollbody'><div style='width:600px;height:430px;' id='d_scrollbody' class='scrollbody'><table summary='' style='height:100%;width:581px;' cellspacing='0' id='t_scrollbody'>\n";
279     // No results? Just take an empty colspanned row
280     if (count($this->entries) + count($this->departments) == 0) {
281       $result.= "<tr class='rowxp0'><td class='list1nohighlight' colspan='$this->numColumns' style='height:100%;border-right:0px;width:100%;'>&nbsp;</td></tr>";
282     }
284     // Line color alternation
285     $alt= 0;
286     $deps= 0;
288     // Draw department browser if configured and we're not in sub mode
289     if ($this->departmentBrowser && $this->filter->scope != "sub") {
290       // Fill with department browser if configured this way
291       $departmentIterator= new departmentSortIterator($this->departments, $this->sortDirection[$this->sortColumn]);
292       foreach ($departmentIterator as $row => $entry){
293         $result.="<tr class='rowxp".($alt&1)."'>";
295         // Render multi select if needed
296         if ($this->multiSelect) {
297           $result.="<td style='text-align:center;width:20px;' class='list1'>&nbsp;</td>";
298         }
300         // Render defined department columns, fill the rest with some stuff
301         $rest= $this->numColumns - 1;
302         foreach ($this->xmlData['table']['department'] as $index => $config) {
303           $colspan= 1;
304           if (isset($config['span'])){
305             $colspan= $config['span'];
306           }
307           $result.="<td colspan='$colspan' ".$this->colprops[$index]." class='list1'>".$this->renderCell($config['value'], $entry, $row)."</td>";
308           $rest-= $colspan;
309         }
311         // Fill remaining cols with nothing
312         $last= $this->numColumns - $rest;
313         for ($i= 0; $i<$rest; $i++){
314           $result.= "<td ".$this->colprops[$last+$i-1]." class='list1'>&nbsp;</td>";
315         }
316         $result.="</tr>";
318         $alt++;
319       }
320       $deps= $alt;
321     }
323     // Fill with contents, sort as configured
324     foreach ($this->entries as $row => $entry) {
325       $trow= "";
327       // Render multi select if needed
328       if ($this->multiSelect) {
329         $trow.="<td style='text-align:center;width:20px;' class='list0'><input type='checkbox' id='listing_selected_$row' name='listing_selected_$row'></td>\n";
330       }
332       foreach ($this->xmlData['table']['column'] as $index => $config) {
333         $renderedCell= $this->renderCell($config['value'], $entry, $row);
334         $trow.="<td ".$this->colprops[$index]." class='list0'>".$renderedCell."</td>\n";
336         // Save rendered column
337         $sort= preg_replace('/.*>([^<]+)<.*$/', '$1', $renderedCell);
338         $sort= preg_replace('/&nbsp;/', '', $sort);
339         if (preg_match('/</', $sort)){
340           $sort= "";
341         }
342         $this->entries[$row]["_sort$index"]= $sort;
343       }
345       // Save rendered entry
346       $this->entries[$row]['_rendered']= $trow;
347     }
349     // Complete list by sorting entries for _sort$index and appending them to the output
350     $entryIterator= new listingSortIterator($this->entries, $this->sortDirection[$this->sortColumn], "_sort".$this->sortColumn, $this->sortType);
351     foreach ($entryIterator as $row => $entry){
352       $alt++;
353       $result.="<tr class='rowxp".($alt&1)."'>\n";
354       $result.= $entry['_rendered'];
355       $result.="</tr>\n";
356     }
358     // Need to fill the list if it's not full (nobody knows why this is 22 ;-))
359     $emptyListStyle= (count($this->entries) + $deps == 0)?"border:0;":"";
360     if ((count($this->entries) + $deps) < 22) {
361       $result.= "<tr>";
362       for ($i= 0; $i<$this->numColumns; $i++) {
363         if ($i == 0) {
364           $result.= "<td class='list1nohighlight' style='$emptyListStyle height:100%;'>&nbsp;</td>";
365           continue;
366         }
367         if ($i != $this->numColumns-1) {
368           $result.= "<td class='list1nohighlight' style='$emptyListStyle'>&nbsp;</td>";
369         } else {
370           $result.= "<td class='list1nohighlight' style='border-right:1px solid #AAA;$emptyListStyle'>&nbsp;</td>";
371         }
372       }
373       $result.= "</tr>";
374     }
376     $result.= "</table></div></td></tr>";
378     // Add the footer if requested
379     if ($this->showFooter) {
380       $result.= "<tr><td class='scrollhead'><table summary='' style='width:100%' cellspacing='0' id='t_scrollfoot'><tr><td class='listfooter' style='border-bottom:0px;'>";
382       foreach ($this->objectTypes as $objectType) {
383         if (isset($this->objectTypeCount[$objectType['label']])) {
384           $label= _($objectType['label']);
385           $result.= "<img class='center' src='".$objectType['image']."' title='$label' alt='$label'>&nbsp;".$this->objectTypeCount[$objectType['label']]."&nbsp;&nbsp;&nbsp;&nbsp;";
386         }
387       }
389       $result.= "<td class='listfooter' style='width:13px;border-right:0px;'>&nbsp;</td></table></td></tr>";
390     }
392     $result.= "</table></div>";
394     $smarty= get_smarty();
395     $smarty->assign("FILTER", $this->filter->render());
396     $smarty->assign("SIZELIMIT", print_sizelimit_warning());
397     $smarty->assign("LIST", $result);
399     // Assign navigation elements
400     $nav= $this->renderNavigation();
401     foreach ($nav as $key => $html) {
402       $smarty->assign($key, $html);
403     }
405     // Assign action menu / base
406     $smarty->assign("ACTIONS", $this->renderActionMenu());
407     $smarty->assign("BASE", $this->renderBase());
409     // Assign separator
410     $smarty->assign("SEPARATOR", "<img src='images/lists/seperator.png' alt='-' align='middle' height='16' width='1' class='center'>");
412     // Assign summary
413     $smarty->assign("HEADLINE", $this->headline);
415     return ($smarty->fetch(get_template_path($this->xmlData['definition']['template'], true)));
416   }
419   function update()
420   {
421     global $config;
422     $ui= get_userinfo();
424     // Reset object counter
425     $this->objectTypeCount= array();
427     // Do not do anything if this is not our PID
428     if(isset($_REQUEST['PID']) && $_REQUEST['PID'] != $this->pid) {
429       return;
430     }
432     // Save base
433     if (isset($_POST['BASE']) && $this->baseMode) {
434       $base= validate($_POST['BASE']);
435       if (isset($this->bases[$base])) {
436         $this->base= $base;
437       }
438     }
440     // Override the base if we got a message from the browser navigation
441     if ($this->departmentBrowser && isset($_GET['act'])) {
442       if (preg_match('/^department_([0-9]+)$/', validate($_GET['act']), $match)){
443         if (isset($this->departments[$match[1]])){
444           $this->base= $this->departments[$match[1]]['dn'];
445         }
446       }
447     }
449     // Filter POST with "act" attributes -> posted from action menu
450     if (isset($_POST['exec_act']) && $_POST['act'] != '') {
451       if (preg_match('/^export.*$/', $_POST['act']) && isset($this->exporter[$_POST['act']])) {
452         $exporter= $this->exporter[$_POST['act']];
453         $userinfo= ", "._("created by")." ".$ui->cn." - ".strftime('%A, %d. %B %Y, %H:%M:%S');
454         $instance= new $exporter['class']($this->headline.$userinfo, $this->plainHeader, $this->entries, $this->exportColumns);
455         $type= call_user_func(array($exporter['class'], "getInfo"));
456         $type= $type[$_POST['act']];
457         send_binary_content($instance->query(), $type['filename'], $type= $type['mime']);
458       }
459     }
461     // Filter GET with "act" attributes
462     if (isset($_GET['act'])) {
463       $key= validate($_GET['act']);
464       if (preg_match('/^SORT_([0-9]+)$/', $key, $match)) {
465         // Switch to new column or invert search order?
466         $column= $match[1];
467         if ($this->sortColumn != $column) {
468           $this->sortColumn= $column;
469         } else {
470           $this->sortDirection[$column]= !$this->sortDirection[$column];
471         }
473         // Allow header to update itself according to the new sort settings
474         $this->renderHeader();
475       }
476     }
478     // Override base if we got signals from the navigation elements
479     $action= "";
480     foreach ($_POST as $key => $value) {
481       if (preg_match('/^(ROOT|BACK|HOME)_x$/', $key, $match)) {
482         $action= $match[1];
483         break;
484       }
485     }
487     // Navigation handling
488     if ($action == 'ROOT') {
489       $deps= $ui->get_module_departments($this->module);
490       $this->base= $deps[0];
491     }
492     if ($action == 'BACK') {
493       $deps= $ui->get_module_departments($this->module);
494       $base= preg_replace("/^[^,]+,/", "", $this->base);
495       if(in_array_ics($base, $deps)){
496         $this->base= $base;
497       }
498     }
499     if ($action == 'HOME') {
500       $ui= get_userinfo();
501       $this->base= get_base_from_people($ui->dn);
502     }
504     // Reload departments
505     if ($this->departmentBrowser){
506       $this->departments= $this->getDepartments();
507     }
509     // Update filter and refresh entries
510     $this->filter->setBase($this->base);
511     $this->entries= $this->filter->query();
512   }
515   function setBase($base)
516   {
517     $this->base= $base;
518   }
521   function getBase()
522   {
523     return $this->base;
524   }
527   function parseLayout($layout)
528   {
529     $result= array();
530     $layout= preg_replace("/^\|/", "", $layout);
531     $layout= preg_replace("/\|$/", "", $layout);
532     $cols= split("\|", $layout);
533     foreach ($cols as $index => $config) {
534       if ($config != "") {
535         $components= split(';', $config);
536         $config= "";
537         foreach ($components as $part) {
538           if (preg_match("/^r$/", $part)) {
539             $config.= "text-align:right;";
540             continue;
541           }
542           if (preg_match("/^l$/", $part)) {
543             $config.= "text-align:left;";
544             continue;
545           }
546           if (preg_match("/^c$/", $part)) {
547             $config.= "text-align:center;";
548             continue;
549           }
550           if (preg_match("/^[0-9]+(|px|%)$/", $part)) {
551             $config.= "width:$part;";
552             continue;
553           }
554         }
556         $result[$index]= " style='$config' ";
557       } else {
558         $result[$index]= null;
559       }
560     }
562     // Save number of columns for later use
563     $this->numColumns= count($cols);
565     return $result;
566   }
569   function renderCell($data, $config, $row)
570   {
571     // Replace flat attributes in data string
572     for ($i= 0; $i<$config['count']; $i++) {
573       $attr= $config[$i];
574       $value= "";
575       if (is_array($config[$attr])) {
576         $value= $config[$attr][0];
577       } else {
578         $value= $config[$attr];
579       }
580       $data= preg_replace("/%\{$attr\}/", $value, $data);
581     }
583     // Watch out for filters and prepare to execute them
584     $data= $this->processElementFilter($data, $config, $row);
586     // Replace all non replaced %{...} instances because they
587     // are non resolved attributes or filters
588     $data= preg_replace('/%{[^}]+}/', '&nbsp;', $data);
590     return $data;
591   }
594   function renderBase()
595   {
596     if (!$this->baseMode) {
597       return;
598     }
600     $result= "<select name='BASE' onChange='mainform.submit()' size='1'>";
601     $firstDN= null;
602     $found= false;
604     foreach ($this->bases as $key=>$value) {
605       // Keep first entry to fall back eventually
606       if(!$firstDN) {
607         $firstDN= $key;
608       }
610       // Prepare to render entry
611       $selected= "";
612       if ($key == $this->base) {
613         $selected= " selected";
614         $found= true;
615       }
616       $result.= "<option value='".$key."'$selected>".$value."</option>";
617     }
618     $result.= "</select>";
620     // Reset the currently used base to the first DN we found if there
621     // was no match.
622     if(!$found){
623       $this->base = $firstDN;
624     }
626     return $result;
627   }
630   function processElementFilter($data, $config, $row)
631   {
632     preg_match_all("/%\{filter:([^(]+)\((.*)\)\}/", $data, $matches, PREG_SET_ORDER);
634     foreach ($matches as $match) {
635       if (!isset($this->filters[$match[1]])) {
636         continue;
637       }
638       $cl= preg_replace('/::.*$/', '', $this->filters[$match[1]]);
639       $method= preg_replace('/^.*::/', '', $this->filters[$match[1]]);
641       // Prepare params for function call
642       $params= array();
643       preg_match_all('/"[^"]+"|[^,]+/', $match[2], $parts);
644       foreach ($parts[0] as $param) {
646         // Row is replaced by the row number
647         if ($param == "row") {
648           $params[]= $row;
649         }
651         // pid is replaced by the current PID
652         if ($param == "pid") {
653           $params[]= $this->pid;
654         }
656         // Fixie with "" is passed directly
657         if (preg_match('/^".*"$/', $param)){
658           $params[]= preg_replace('/"/', '', $param);
659         }
661         // LDAP variables get replaced by their objects
662         for ($i= 0; $i<$config['count']; $i++) {
663           if ($param == $config[$i]) {
664             $values= $config[$config[$i]];
665             if (is_array($values)){
666               unset($values['count']);
667             }
668             $params[]= $values;
669           }
670         }
672         // Move dn if needed
673         if ($param == "dn") {
674           $params[]= LDAP::fix($config["dn"]);
675         }
676       }
678       // Replace information
679       if ($cl == "listing") {
680         // Non static call - seems to result in errors
681         $data= @preg_replace('/'.preg_quote($match[0]).'/', call_user_func_array(array($this, "$method"), $params), $data);
682       } else {
683         // Static call
684         $data= preg_replace('/'.preg_quote($match[0]).'/', call_user_func_array(array($cl, $method), $params), $data);
685       }
686     }
688     return $data;
689   }
692   function getObjectType($types, $classes)
693   {
694     // Walk thru types and see if there's something matching
695     foreach ($types as $objectType) {
696       $ocs= $objectType['objectClass'];
697       if (!is_array($ocs)){
698         $ocs= array($ocs);
699       }
701       $found= true;
702       foreach ($ocs as $oc){
703         if (preg_match('/^!(.*)$/', $oc, $match)) {
704           $oc= $match[1];
705           if (in_array($oc, $classes)) {
706             $found= false;
707           }
708         } else {
709           if (!in_array($oc, $classes)) {
710             $found= false;
711           }
712         }
713       }
715       if ($found) {
716         return $objectType;
717       }
718     }
720     return null;
721   }
724   function filterObjectType($dn, $classes)
725   {
726     // Walk thru classes and return on first match
727     $result= "&nbsp;";
729     $objectType= $this->getObjectType($this->objectTypes, $classes);
730     if ($objectType) {
731       $result= "<img class='center' title='".LDAP::fix($dn)."' src='".$objectType["image"]."'>";
732       if (!isset($this->objectTypeCount[$objectType['label']])) {
733         $this->objectTypeCount[$objectType['label']]= 0;
734       }
735       $this->objectTypeCount[$objectType['label']]++;
736     }
737     return $result;
738   }
741   function filterActions($dn, $row, $classes)
742   {
743     // Do nothing if there's no menu defined
744     if (!isset($this->xmlData['actiontriggers']['action'])) {
745       return "&nbsp;";
746     }
748     // Go thru all actions
749     $result= "";
750     $actions= $this->xmlData['actiontriggers']['action'];
751     foreach($actions as $action) {
752       // Skip the entry completely if there's no permission to execute it
753       if (!$this->hasActionPermission($action, $dn)) {
754         continue;
755       }
757       // If there's an objectclass definition and we don't have it
758       // add an empty picture here.
759       if (isset($action['objectclass'])){
760         $objectclass= $action['objectclass'];
761         if (preg_match('/^!(.*)$/', $objectclass, $m)){
762           $objectclass= $m[1];
763           if(in_array($objectclass, $classes)) {
764             $result.= "<img src='images/empty.png' alt=' ' class='center' style='padding:1px'>";
765             continue;
766           }
767         } else {
768           if(!in_array($objectclass, $classes)) {
769             $result.= "<img src='images/empty.png' alt=' ' class='center' style='padding:1px'>";
770             continue;
771           }
772         }
773       }
775       // Render normal entries as usual
776       if ($action['type'] == "entry") {
777         $label= $this->processElementFilter($action['label'], $this->entries[$row], $row);
778         $image= $this->processElementFilter($action['image'], $this->entries[$row], $row);
779         $result.="<input class='center' type='image' src='$image' title='$label' ".
780                  "name='listing_".$action['name']."_$row' style='padding:1px'>";
781       }
783       // Handle special types
784       if ($action['type'] == "copypaste" || $action['type'] == "snapshot") {
786         $objectType= $this->getObjectType($this->objectTypes, $this->entries[$row]['objectClass']);
787         $category= $class= null;
788         if ($objectType) {
789           $category= $objectType['category'];
790           $class= $objectType['class'];
791         }
793         if ($action['type'] == "copypaste") {
794           $result.= $this->renderCopyPasteActions($row, $this->entries[$row]['dn'], $category, $class);
795         } else {
796           $result.= $this->renderSnapshotActions($row, $this->entries[$row]['dn'], $category, $class);
797         }
798       }
799     }
801     return $result;
802   }
805   function filterDepartmentLink($row, $dn, $description)
806   {
807     $attr= $this->departments[$row]['sort-attribute'];
808     $name= $this->departments[$row][$attr];
809     if (is_array($name)){
810       $name= $name[0];
811     }
812     $result= sprintf("%s [%s]", $name, $description[0]);
813     return("<a href='?plug=".$_GET['plug']."&amp;PID=$this->pid&amp;act=department_$row' title='$dn'>$result</a>");
814   }
817   function filterLink()
818   {
819     $result= "&nbsp;";
821     $row= func_get_arg(0);
822     $pid= $this->pid;
823     $dn= LDAP::fix(func_get_arg(1));
824     $params= array(func_get_arg(2));
826     // Collect sprintf params
827     for ($i = 3;$i < func_num_args();$i++) {
828       $val= func_get_arg($i);
829       if (is_array($val)){
830         $params[]= $val[0];
831         continue;
832       }
833       $params[]= $val;
834     }
836     $result= "&nbsp;";
837     $trans= call_user_func_array("sprintf", $params);
838     if ($trans != "") {
839       return("<a href='?plug=".$_GET['plug']."&amp;PID=$pid&amp;act=listing_edit_$row' title='$dn'>$trans</a>");
840     }
842     return $result;
843   }
846   function renderNavigation()
847   {
848     $result= array();
849     $enableBack = true;
850     $enableRoot = true;
851     $enableHome = true;
853     $ui = get_userinfo();
855     /* Check if base = first available base */
856     $deps = $ui->get_module_departments($this->module);
858     if(!count($deps) || $deps[0] == $this->filter->base){
859       $enableBack = false;
860       $enableRoot = false;
861     }
863     $listhead ="";
865     /* Check if we are in users home  department */
866     if(!count($deps) ||$this->filter->base == get_base_from_people($ui->dn)){
867       $enableHome = false;
868     }
870     /* Draw root button */
871     if($enableRoot){
872       $result["ROOT"]= "<input class='center' type='image' src='images/lists/root.png' align='middle' ".
873                        "title='"._("Go to root department")."' name='ROOT' alt='"._("Root")."'>";
874     }else{
875       $result["ROOT"]= "<img src='images/lists/root_grey.png' class='center' alt='"._("Root")."'>";
876     }
878     /* Draw back button */
879     if($enableBack){
880       $result["BACK"]= "<input class='center' type='image' align='middle' src='images/lists/back.png' ".
881                        "title='"._("Go up one department")."' alt='"._("Up")."' name='BACK'>";
882     }else{
883       $result["BACK"]= "<img src='images/lists/back_grey.png' class='center' alt='"._("Up")."'>";
884     }
886     /* Draw home button */
887     if($enableHome){
888       $result["HOME"]= "<input class='center' type='image' align='middle' src='images/lists/home.png' ".
889                        "title='"._("Go to users department")."' alt='"._("Home")."' name='HOME'>";
890     }else{
891       $result["HOME"]= "<img src='images/lists/home_grey.png' class='center' alt='"._("Home")."'>";
892     }
894     /* Draw reload button, this button is enabled everytime */
895     $result["RELOAD"]= "<input class='center' type='image' src='images/lists/reload.png' align='middle' ".
896                        "title='"._("Reload list")."' name='REFRESH' alt='"._("Submit")."'>";
898     return ($result);
899   }
902   function getAction()
903   {
904     // Do not do anything if this is not our PID, or there's even no PID available...
905     if(!isset($_REQUEST['PID']) || $_REQUEST['PID'] != $this->pid) {
906       return;
907     }
909     $result= array("targets" => array(), "action" => "");
911     // Filter GET with "act" attributes
912     if (isset($_GET['act'])) {
913       $key= validate($_GET['act']);
914       $target= preg_replace('/^listing_[a-zA-Z_]+_([0-9]+)$/', '$1', $key);
915       if (isset($this->entries[$target]['dn'])) {
916         $result['action']= preg_replace('/^listing_([a-zA-Z_]+)_[0-9]+$/', '$1', $key);
917         $result['targets'][]= $this->entries[$target]['dn'];
918       }
920       // Drop targets if empty
921       if (count($result['targets']) == 0) {
922         unset($result['targets']);
923       }
924       return $result;
925     }
927     // Filter POST with "listing_" attributes
928     foreach ($_POST as $key => $prop) {
930       // Capture selections
931       if (preg_match('/^listing_selected_[0-9]+$/', $key)) {
932         $target= preg_replace('/^listing_selected_([0-9]+)$/', '$1', $key);
933         if (isset($this->entries[$target]['dn'])) {
934           $result['targets'][]= $this->entries[$target]['dn'];
935         }
936         continue;
937       }
939       // Capture action with target - this is a one shot
940       if (preg_match('/^listing_[a-zA-Z_]+_[0-9]+(|_x)$/', $key)) {
941         $target= preg_replace('/^listing_[a-zA-Z_]+_([0-9]+)(|_x)$/', '$1', $key);
942         if (isset($this->entries[$target]['dn'])) {
943           $result['action']= preg_replace('/^listing_([a-zA-Z_]+)_[0-9]+(|_x)$/', '$1', $key);
944           $result['targets']= array($this->entries[$target]['dn']);
945         }
946         break;
947       }
949       // Capture action without target
950       if (preg_match('/^listing_[a-zA-Z_]+(|_x)$/', $key)) {
951         $result['action']= preg_replace('/^listing_([a-zA-Z_]+)(|_x)$/', '$1', $key);
952         continue;
953       }
954     }
956     // Filter POST with "act" attributes -> posted from action menu
957     if (isset($_POST['act']) && $_POST['act'] != '') {
958       if (!preg_match('/^export.*$/', $_POST['act'])){
959         $result['action']= validate($_POST['act']);
960       }
961     }
963     // Drop targets if empty
964     if (count($result['targets']) == 0) {
965       unset($result['targets']);
966     }
967     return $result;
968   }
971   function renderActionMenu()
972   {
973     // Don't send anything if the menu is not defined
974     if (!isset($this->xmlData['actionmenu']['action'])){
975       return "";
976     }
978     // Load shortcut
979     $actions= &$this->xmlData['actionmenu']['action'];
980     $result= "<input type='hidden' name='act' id='actionmenu' value=''><div style='display:none'><input type='submit' name='exec_act' id='exec_act' value=''></div>".
981              "<ul class='level1' id='root'><li><a href='#'>Aktionen&nbsp;<img ".
982              "border=0 class='center' src='images/lists/sort-down.png'></a>";
984     // Build ul/li list
985     $result.= $this->recurseActions($actions);
987     return "<div id='pulldown'>".$result."</li></ul><div>";
988   }
991   function recurseActions($actions)
992   {
993     static $level= 2;
994     $result= "<ul class='level$level'>";
995     $separator= "";
997     foreach ($actions as $action) {
999       // Skip the entry completely if there's no permission to execute it
1000       if (!$this->hasActionPermission($action, $this->filter->base)) {
1001         continue;
1002       }
1004       // Fill image if set
1005       $img= "";
1006       if (isset($action['image'])){
1007         $img= "<img border='0' class='center' src='".$action['image']."'>&nbsp;";
1008       }
1010       if ($action['type'] == "separator"){
1011         $separator= " style='border-top:1px solid #AAA' ";
1012         continue;
1013       }
1015       // Dive into subs
1016       if ($action['type'] == "sub" && isset($action['action'])) {
1017         $level++;
1018         if (isset($action['label'])){
1019           $result.= "<li$separator><a href='#'>$img"._($action['label'])."&nbsp;<img border='0' src='images/forward-arrow.png'></a>";
1020         }
1021         $result.= $this->recurseActions($action['action'])."</li>";
1022         $level--;
1023         $separator= "";
1024         continue;
1025       }
1027       // Render entry elseways
1028       if (isset($action['label'])){
1029         $result.= "<li$separator><a href='#' onClick='document.getElementById(\"actionmenu\").value= \"".$action['name']."\";mainform.submit();'>$img"._($action['label'])."</a></li>";
1030       }
1032       // Check for special types
1033       switch ($action['type']) {
1034         case 'copypaste':
1035           $result.= $this->renderCopyPasteMenu($separator);
1036           break;
1038         case 'snapshot':
1039           $result.= $this->renderSnapshotMenu($separator);
1040           break;
1042         case 'exporter':
1043           $result.= $this->renderExporterMenu($separator);
1044           break;
1046         case 'daemon':
1047           $result.= $this->renderDaemonMenu($separator);
1048           break;
1049       }
1051       $separator= "";
1052     }
1054     $result.= "</ul>";
1055     return $result;
1056   }
1059   function hasActionPermission($action, $dn)
1060   {
1061     $ui= get_userinfo();
1063     if (isset($action['acl'])) {
1064       $acls= $action['acl'];
1065       if (!is_array($acls)) {
1066         $acls= array($acls);
1067       }
1069       // Every ACL has to pass
1070       foreach ($acls as $acl) {
1071         $module= $this->module;
1072         $aclList= array();
1074         // Split for category and plugins if needed
1075         // match for "[rw]" style entries
1076         if (preg_match('/^\[([rwcdm]+)\]$/', $acl, $match)){
1077           $aclList= array($match[1]);
1078         }
1080         // match for "users[rw]" style entries
1081         if (preg_match('/^([a-zA-Z0-9]+)\[([rwcdm]+)\]$/', $acl, $match)){
1082           $module= $match[1];
1083           $aclList= array($match[2]);
1084         }
1086         // match for "users/user[rw]" style entries
1087         if (preg_match('/^([a-zA-Z0-9]+\/[a-zA-Z0-9]+)\[([rwcdm]+)\]$/', $acl, $match)){
1088           $module= $match[1];
1089           $aclList= array($match[2]);
1090         }
1092         // match "users/user[userPassword:rw(,...)*]" style entries
1093         if (preg_match('/^([a-zA-Z0-9]+\/[a-zA-Z0-9]+)\[([a-zA-Z0-9]+:[rwcdm]+(,[a-zA-Z0-9]+:[rwcdm]+)*)\]$/', $acl, $match)){
1094           $module= $match[1];
1095           $aclList= split(',', $match[2]);
1096         }
1098         // Walk thru prepared ACL by using $module
1099         foreach($aclList as $sAcl) {
1100           $checkAcl= "";
1102           // Category or detailed permission?
1103           if (strpos('/', $module) === false) {
1104             if (preg_match('/([a-zA-Z0-9]+):([rwcdm]+)/', $sAcl, $m) ) {
1105               $checkAcl= $ui->get_permissions($dn, $module, $m[1]);
1106               $sAcl= $m[2];
1107             } else {
1108               $checkAcl= $ui->get_permissions($dn, $module, '0');
1109             }
1110           } else {
1111             $checkAcl= $ui->get_category_permissions($dn, $module);
1112           }
1114           // Split up remaining part of the acl and check if it we're
1115           // allowed to do something...
1116           $parts= str_split($sAcl);
1117           foreach ($parts as $part) {
1118             if (strpos($checkAcl, $part) === false){
1119               return false;
1120             }
1121           }
1123         }
1124       }
1125     }
1127     return true;
1128   }
1131   function refreshBasesList()
1132   {
1133     global $config;
1134     $ui= get_userinfo();
1136     // Do some array munching to get it user friendly
1137     $ids= $config->idepartments;
1138     $d= $ui->get_module_departments($this->module);
1139     $k_ids= array_keys($ids);
1140     $deps= array_intersect($d,$k_ids);
1142     // Fill internal bases list
1143     $this->bases= array();
1144     foreach($k_ids as $department){
1145       $this->bases[$department] = $ids[$department];
1146     }
1147   }
1150   function getDepartments()
1151   {
1152     $departments= array();
1153     $ui= get_userinfo();
1155     // Get list of supported department types
1156     $types = departmentManagement::get_support_departments();
1158     // Load departments allowed by ACL
1159     $validDepartments = $ui->get_module_departments($this->module);
1161     // Build filter and look in the LDAP for possible sub departments
1162     // of current base
1163     $filter= "(&(objectClass=gosaDepartment)(|";
1164     $attrs= array("description", "objectClass");
1165     foreach($types as $name => $data){
1166       $filter.= "(objectClass=".$data['OC'].")";
1167       $attrs[]= $data['ATTR'];
1168     }
1169     $filter.= "))";
1170     $res= get_list($filter, $this->module, $this->base, $attrs, GL_NONE | GL_SIZELIMIT);
1172     // Analyze list of departments
1173     foreach ($res as $department) {
1174       if (!in_array($department['dn'], $validDepartments)) {
1175         continue;
1176       }
1178       // Add the attribute where we use for sorting
1179       $oc= null;
1180       foreach(array_keys($types) as $type) {
1181         if (in_array($type, $department['objectClass'])) {
1182           $oc= $type;
1183           break;
1184         }
1185       }
1186       $department['sort-attribute']= $types[$oc]['ATTR'];
1188       // Move to the result list
1189       $departments[]= $department;
1190     }
1192     return $departments;
1193   }
1196   function renderCopyPasteMenu($separator, $copy= true, $cut= true)
1197   {
1198     // We can only provide information if we've got a copypaste handler
1199     // instance
1200     if(!(isset($this->copyPasteHandler) && is_object($this->copyPasteHandler))){
1201       return "";
1202     }
1204     // Presets
1205     $result= "";
1206     $read= $paste= false;
1207     $ui= get_userinfo();
1209     // Switch flags to on if there's at least one category which allows read/paste
1210     foreach($this->categories as $category){
1211       $read= $read || preg_match('/r/', $ui->get_category_permissions($this->base, $category));
1212       $paste= $paste || $ui->is_pasteable($this->base, $category) == 1;
1213     }
1216     // Draw entries that allow copy and cut
1217     if($read){
1219       // Copy entry
1220       if($copy){
1221         $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>";
1222         $separator= "";
1223       }
1225       // Cut entry
1226       if($cut){
1227         $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>";
1228         $separator= "";
1229       }
1230     }
1232     // Draw entries that allow pasting entries
1233     if($paste){
1234       if($this->copyPasteHandler->entries_queued()){
1235         $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>";
1236       }else{
1237         $result.= "<li$separator><a href='#'><img src='images/lists/paste-grey.png' alt='' border='0' class='center'>&nbsp;"._("Paste")."</a></li>";
1238       }
1239     }
1240     
1241     return($result);
1242   }
1245   function renderCopyPasteActions($row, $dn, $category, $class, $copy= true, $cut= true)
1246   {
1247     // We can only provide information if we've got a copypaste handler
1248     // instance
1249     if(!(isset($this->copyPasteHandler) && is_object($this->copyPasteHandler))){
1250       return "";
1251     }
1253     // Presets
1254     $ui = get_userinfo();
1255     $result = "";
1257     // Render cut entries
1258     if($cut){
1259       if($ui->is_cutable($dn, $category, $class)){
1260         $result .= "<input class='center' type='image'
1261           src='images/lists/cut.png' alt='"._("Cut")."' name='listing_cut_$row' title='"._("Cut this entry")."' style='padding:1px'>";
1262       }else{
1263         $result.="<img src='images/empty.png' alt=' ' class='center' style='padding:1px'>";
1264       }
1265     }
1267     // Render copy entries
1268     if($copy){
1269       if($ui->is_copyable($dn, $category, $class)){
1270         $result.= "<input class='center' type='image'
1271           src='images/lists/copy.png' alt='"._("Copy")."' name='listing_copy_$row' title='"._("Copy this entry")."' style='padding:1px'>";
1272       }else{
1273         $result.="<img src='images/empty.png' alt=' ' class='center' style='padding:1px'>";
1274       }
1275     }
1277     return($result);
1278   }
1281   function renderSnapshotMenu($separator)
1282   {
1283     // We can only provide information if we've got a snapshot handler
1284     // instance
1285     if(!(isset($this->snapshotHandler) && is_object($this->snapshotHandler))){
1286       return "";
1287     }
1289     // Presets
1290     $result = "";
1291     $ui = get_userinfo();
1293     if($this->snapshotHandler->enabled() && $ui->allow_snapshot_restore($this->base, $this->module)){
1295       // Check if there is something to restore
1296       $restore= false;
1297       foreach($this->snapshotHandler->getSnapshotBases() as $base){
1298         $restore= $restore || count($this->snapshotHandler->getDeletedSnapshots($base)) > 0;
1299       }
1301       // Draw icons according to the restore flag
1302       if($restore){
1303         $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>";
1304       }else{
1305         $result.= "<li$separator><a href='#'><img src='images/lists/restore_grey.png' alt='' border='0' class='center'>&nbsp;"._("Restore snapshots")."</a></li>";
1306       }
1307     }
1309     return($result);
1310   }
1313   function renderExporterMenu($separator)
1314   {
1315     // Presets
1316     $result = "";
1318     // Draw entries
1319     $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'>";
1321     // Export CVS as build in exporter
1322     foreach ($this->exporter as $action => $exporter) {
1323       $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>";
1324     }
1326     // Finalize list
1327     $result.= "</ul></li>";
1329     return($result);
1330   }
1333   function renderSnapshotActions($row, $dn, $category, $class, $copy= true, $cut= true)
1334   {
1335     // We can only provide information if we've got a snapshot handler
1336     // instance
1337     if(!(isset($this->snapshotHandler) && is_object($this->snapshotHandler))){
1338       return "";
1339     }
1341     // Presets
1342     $result= "";
1343     $ui = get_userinfo();
1345     // Only act if enabled here
1346     if($this->snapshotHandler->enabled()){
1348       // Draw restore button
1349       if ($ui->allow_snapshot_restore($dn, $category)){
1351         // Do we have snapshots for this dn?
1352         if($this->snapshotHandler->hasSnapshots($dn)){
1353           $result.= "<input class='center' type='image' src='images/lists/restore.png' ".
1354                      "alt='"._("Restore snapshot")."' name='listing_restore_$row' title='".
1355                      _("Restore snapshot")."' style='padding:1px'>";
1356         } else {
1357           $result.= "<img src='images/lists/restore_grey.png' alt=' ' class='center' style='padding:1px'>";
1358         }
1359       }
1361       // Draw snapshot button
1362       if($ui->allow_snapshot_create($dn, $category)){
1363           $result.= "<input class='center' type='image' src='images/snapshot.png' ".
1364                      "alt='"._("Create snapshot")."' name='listing_snapshot_$row' title='".
1365                      _("Create a new snapshot from this object")."' style='padding:1px'>";
1366       }else{
1367           $result.= "<img src='images/empty.png' alt=' ' class='center' style='padding:1px'>";
1368       }
1369     }
1371     return($result);
1372   }
1375   function renderDaemonMenu($separator)
1376   {
1377     $result= "";
1379     // If there is a daemon registered, draw the menu entries
1380     if(class_available("DaemonEvent")){
1381       $events= DaemonEvent::get_event_types_by_category($this->categories);
1382       if(isset($events['BY_CLASS']) && count($events['BY_CLASS'])){
1383         foreach($events['BY_CLASS'] as $name => $event){
1384           $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>";
1385           $separator= "";
1386         }
1387       }
1388     }
1390     return $result;
1391   }
1395 ?>