Code

c160807a2dcb323df4fd2a59a42be9fd2aecce8e
[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;
52   function listing($filename)
53   {
54     global $config;
56     // Initialize pid
57     $this->pid= preg_replace("/[^0-9]/", "", microtime(TRUE));
59     if (!$this->load($filename)) {
60       die("Cannot parse $filename!");
61     }
63     // Set base for filter
64     $this->base= session::global_get("CurrentMainBase");
65     if ($this->base == null) {
66       $this->base= $config->current['BASE'];
67     }
68     $this->refreshBasesList();
70     // Move footer information
71     $this->showFooter= ($config->get_cfg_value("listSummary") == "true");
73     // Register build in filters
74     $this->registerElementFilter("objectType", "listing::filterObjectType");
75     $this->registerElementFilter("departmentLink", "listing::filterDepartmentLink");
76     $this->registerElementFilter("link", "listing::filterLink");
77     $this->registerElementFilter("actions", "listing::filterActions");
78   }
81   function setCopyPasteHandler($handler)
82   {
83     $this->copyPasteHandler= &$handler;
84   }
87   function setSnapshotHandler($handler)
88   {
89     $this->snapshotHandler= &$handler;
90   }
93   function setFilter($filter)
94   {
95     $this->filter= &$filter;
96     if ($this->departmentBrowser){
97       $this->departments= $this->getDepartments();
98     }
99     $this->filter->setBase($this->base);
100     $this->entries= $this->filter->query();
101   }
104   function registerElementFilter($name, $call)
105   {
106     if (!isset($this->filters[$name])) {
107       $this->filters[$name]= $call;
108       return true;
109     }
111     return false;
112   }
115   function load($filename)
116   {
117     $contents = file_get_contents($filename);
118     $this->xmlData= xml::xml2array($contents, 1);
120     if (!isset($this->xmlData['list'])) {
121       return false;
122     }
124     $this->xmlData= $this->xmlData["list"];
126     // Load some definition values
127     foreach (array("departmentBrowser", "departmentRootVisible", "multiSelect", "baseMode") as $token) {
128       if (isset($this->xmlData['definition'][$token]) &&
129           $this->xmlData['definition'][$token] == "true"){
130         $this->$token= true;
131       }
132     }
134     // Fill objectTypes from departments and xml definition
135     $types = departmentManagement::get_support_departments();
136     foreach ($types as $class => $data) {
137       $this->objectTypes[]= array("label" => $data['TITLE'],
138                                   "objectClass" => $data['OC'],
139                                   "image" => $data['IMG']);
140     }
141     $this->categories= array();
142     if (isset($this->xmlData['definition']['objectType'])) {
143       if(isset($this->xmlData['definition']['objectType']['label'])) {
144         $this->xmlData['definition']['objectType']= array($this->xmlData['definition']['objectType']);
145       }
146       foreach ($this->xmlData['definition']['objectType'] as $index => $otype) {
147         $this->objectTypes[]= $this->xmlData['definition']['objectType'][$index];
148         if (isset($this->xmlData['definition']['objectType'][$index]['category'])){
149           $this->categories[]= $this->xmlData['definition']['objectType'][$index]['category'];
150         }
151       }
152     }
154     // Parse layout per column
155     $this->colprops= $this->parseLayout($this->xmlData['table']['layout']);
157     // Prepare table headers
158     $this->renderHeader();
160     // Assign headline/module
161     $this->headline= _($this->xmlData['definition']['label']);
162     $this->module= $this->xmlData['definition']['module'];
163     if (!is_array($this->categories)){
164       $this->categories= array($this->categories);
165     }
167     return true;  
168   }
171   function renderHeader()
172   {
173     $this->header= array();
175     // Initialize sort?
176     $sortInit= false;
177     if (!$this->sortDirection) {
178       $this->sortColumn= 0;
179       if (isset($this->xmlData['definition']['defaultSortColumn'])){
180         $this->sortColumn= $this->xmlData['definition']['defaultSortColumn'];
181       } else {
182         $this->sortAttribute= "";
183       }
184       $this->sortDirection= array();
185       $sortInit= true;
186     }
188     if (isset($this->xmlData['table']['column'])){
189       foreach ($this->xmlData['table']['column'] as $index => $config) {
190         // Initialize everything to one direction
191         if ($sortInit) {
192           $this->sortDirection[$index]= false;
193         }
195         $sorter= "";
196         if ($index == $this->sortColumn && isset($config['sortAttribute']) &&
197             isset($config['sortType'])) {
198           $this->sortAttribute= $config['sortAttribute'];
199           $this->sortType= $config['sortType'];
200           $sorter= "&nbsp;<img border='0' title='".($this->sortDirection[$index]?_("Up"):_("Down"))."' src='images/lists/sort-".($this->sortDirection[$index]?"up":"down").".png' align='top'>";
201         }
202         $sortable= (isset($config['sortAttribute']));
204         $link= "href='?plug=".$_GET['plug']."&amp;PID=".$this->pid."&amp;act=SORT_$index'";
205         if (isset($config['label'])) {
206           if ($sortable) {
207             $this->header[$index]= "<td class='listheader' ".$this->colprops[$index]."><a $link>"._($config['label'])."$sorter</a></td>";
208           } else {
209             $this->header[$index]= "<td class='listheader' ".$this->colprops[$index].">"._($config['label'])."</td>";
210           }
211         } else {
212           if ($sortable) {
213             $this->header[$index]= "<td class='listheader' ".$this->colprops[$index]."><a $link>&nbsp;$sorter</a></td>";
214           } else {
215             $this->header[$index]= "<td class='listheader' ".$this->colprops[$index].">&nbsp;</td>";
216           }
217         }
218       }
219     }
220   }
222   function render()
223   {
224     // Check for exeeded sizelimit
225     if (($message= check_sizelimit()) != ""){
226       return($message);
227     }
229     // Initialize list
230     $result= "<input type='hidden' value='$this->pid' name='PID'>\n";
231     $result.= "<div class='contentboxb' id='listing_container' style='border-top:1px solid #B0B0B0;'>\n";
232     $result.= "<table summary='$this->headline' style='width:600px;height:450px;' cellspacing='0' id='t_scrolltable'>
233 <tr><td class='scrollhead'><table summary='' style='width:100%;' cellspacing='0' id='t_scrollhead'>\n";
234     $this->numColumns= count($this->colprops) + ($this->multiSelect?1:0);
236     // Build list header
237     $result.= "<tr>\n";
238     if ($this->multiSelect) {
239       $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";
240     }
241     foreach ($this->header as $header) {
242       $result.= $header;
243     }
245     // Add 13px for scroller
246     $result.= "<td class='listheader' style='width:13px;border-right:0px;'>&nbsp;</td></table></td></tr>\n";
248     // New table for the real list contents
249     $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";
251     // No results? Just take an empty colspanned row
252     if (count($this->entries) + count($this->departments) == 0) {
253       $result.= "<tr class='rowxp0'><td class='list1nohighlight' colspan='$this->numColumns' style='height:100%;border-right:0px;width:100%;'>&nbsp;</td></tr>";
254     }
256     // Line color alternation
257     $alt= 0;
258     $deps= 0;
260     // Draw department browser if configured and we're not in sub mode
261     if ($this->departmentBrowser && $this->filter->scope != "sub") {
262       // Fill with department browser if configured this way
263       $departmentIterator= new departmentSortIterator($this->departments, $this->sortDirection[$this->sortColumn]);
264       foreach ($departmentIterator as $row => $entry){
265         $result.="<tr class='rowxp".($alt&1)."'>";
267         // Render multi select if needed
268         if ($this->multiSelect) {
269           $result.="<td style='text-align:center;width:20px;' class='list1'>&nbsp;</td>";
270         }
272         // Render defined department columns, fill the rest with some stuff
273         $rest= $this->numColumns - 1;
274         foreach ($this->xmlData['table']['department'] as $index => $config) {
275           $colspan= 1;
276           if (isset($config['span'])){
277             $colspan= $config['span'];
278           }
279           $result.="<td colspan='$colspan' ".$this->colprops[$index]." class='list1'>".$this->renderCell($config['value'], $entry, $row)."</td>";
280           $rest-= $colspan;
281         }
283         // Fill remaining cols with nothing
284         $last= $this->numColumns - $rest;
285         for ($i= 0; $i<$rest; $i++){
286           $result.= "<td ".$this->colprops[$last+$i-1]." class='list1'>&nbsp;</td>";
287         }
288         $result.="</tr>";
290         $alt++;
291       }
292       $deps= $alt;
293     }
295     // Fill with contents, sort as configured
296     foreach ($this->entries as $row => $entry) {
297       $trow ="<tr class='rowxp".($alt&1)."'>\n";
299       // Render multi select if needed
300       if ($this->multiSelect) {
301         $trow.="<td style='text-align:center;width:20px;' class='list0'><input type='checkbox' id='listing_selected_$row' name='listing_selected_$row'></td>\n";
302       }
304       foreach ($this->xmlData['table']['column'] as $index => $config) {
305         $renderedCell= $this->renderCell($config['value'], $entry, $row);
306         $trow.="<td ".$this->colprops[$index]." class='list0'>".$renderedCell."</td>\n";
308         // Save rendered column
309         $sort= preg_replace('/.*>([^<]+)<.*$/', '$1', $renderedCell);
310         if (preg_match('/</', $sort)){
311           $sort= "";
312         }
313         $this->entries[$row]["_sort$index"]= $sort;
314       }
315       $trow.="</tr>\n";
317       // Save rendered entry
318       $this->entries[$row]['_rendered']= $trow;
320       $alt++;
321     }
323     // Complete list by sorting entries for _sort$index and appending them to the output
324     $entryIterator= new listingSortIterator($this->entries, $this->sortDirection[$this->sortColumn], "_sort".$this->sortColumn, $this->sortType);
325     foreach ($entryIterator as $row => $entry){
326       $result.= $entry['_rendered'];
327     }
329     // Need to fill the list if it's not full (nobody knows why this is 22 ;-))
330     $emptyListStyle= (count($this->entries) + $deps == 0)?"border:0;":"";
331     if ((count($this->entries) + $deps) < 22) {
332       $result.= "<tr>";
333       for ($i= 0; $i<$this->numColumns; $i++) {
334         if ($i == 0) {
335           $result.= "<td class='list1nohighlight' style='$emptyListStyle height:100%;'>&nbsp;</td>";
336           continue;
337         }
338         if ($i != $this->numColumns-1) {
339           $result.= "<td class='list1nohighlight' style='$emptyListStyle'>&nbsp;</td>";
340         } else {
341           $result.= "<td class='list1nohighlight' style='border-right:1px solid #AAA;$emptyListStyle'>&nbsp;</td>";
342         }
343       }
344       $result.= "</tr>";
345     }
347     $result.= "</table></div></td></tr>";
349     // Add the footer if requested
350     if ($this->showFooter) {
351       $result.= "<tr><td class='scrollhead'><table summary='' style='width:100%' cellspacing='0' id='t_scrollfoot'><tr><td class='listfooter' style='border-bottom:0px;'>";
353       foreach ($this->objectTypes as $objectType) {
354         if (isset($this->objectTypeCount[$objectType['label']])) {
355           $label= _($objectType['label']);
356           $result.= "<img class='center' src='".$objectType['image']."' title='$label' alt='$label'>&nbsp;".$this->objectTypeCount[$objectType['label']]."&nbsp;&nbsp;&nbsp;&nbsp;";
357         }
358       }
360       $result.= "<td class='listfooter' style='width:13px;border-right:0px;'>&nbsp;</td></table></td></tr>";
361     }
363     $result.= "</table></div>";
365     $smarty= get_smarty();
366     $smarty->assign("FILTER", $this->filter->render());
367     $smarty->assign("SIZELIMIT", print_sizelimit_warning());
368     $smarty->assign("LIST", $result);
370     // Assign navigation elements
371     $nav= $this->renderNavigation();
372     foreach ($nav as $key => $html) {
373       $smarty->assign($key, $html);
374     }
376     // Assign action menu / base
377     $smarty->assign("ACTIONS", $this->renderActionMenu());
378     $smarty->assign("BASE", $this->renderBase());
380     // Assign separator
381     $smarty->assign("SEPARATOR", "<img src='images/lists/seperator.png' alt='-' align='middle' height='16' width='1' class='center'>");
383     // Assign summary
384     $smarty->assign("HEADLINE", $this->headline);
386     return ($smarty->fetch(get_template_path($this->xmlData['definition']['template'], true)));
387   }
390   function update()
391   {
392     global $config;
393     $ui= get_userinfo();
395     // Reset object counter
396     $this->objectTypeCount= array();
398     // Do not do anything if this is not our PID
399     if(isset($_REQUEST['PID']) && $_REQUEST['PID'] != $this->pid) {
400       return;
401     }
403     // Save base
404     if (isset($_POST['BASE']) && $this->baseMode == true) {
405       $base= validate($_POST['BASE']);
406       if (isset($this->bases[$base])) {
407         $this->base= $base;
408       }
409     }
411     // Override the base if we got a message from the browser navigation
412     if ($this->departmentBrowser && isset($_GET['act'])) {
413       if (preg_match('/^department_([0-9]+)$/', validate($_GET['act']), $match)){
414         if (isset($this->departments[$match[1]])){
415           $this->base= $this->departments[$match[1]]['dn'];
416         }
417       }
418     }
420     // Filter GET with "act" attributes
421     if (isset($_GET['act'])) {
422       $key= validate($_GET['act']);
423       if (preg_match('/^SORT_([0-9]+)$/', $key, $match)) {
424         // Switch to new column or invert search order?
425         $column= $match[1];
426         if ($this->sortColumn != $column) {
427           $this->sortColumn= $column;
428         } else {
429           $this->sortDirection[$column]= !$this->sortDirection[$column];
430         }
432         // Allow header to update itself according to the new sort settings
433         $this->renderHeader();
434       }
435     }
437     // Override base if we got signals from the navigation elements
438     $action= "";
439     foreach ($_POST as $key => $value) {
440       if (preg_match('/^(ROOT|BACK|HOME)_x$/', $key, $match)) {
441         $action= $match[1];
442         break;
443       }
444     }
446     // Navigation handling
447     if ($action == 'ROOT') {
448       $deps= $ui->get_module_departments($this->module);
449       $this->base= $deps[0];
450     }
451     if ($action == 'BACK') {
452       $deps= $ui->get_module_departments($this->module);
453       $base= preg_replace("/^[^,]+,/", "", $this->base);
454       if(in_array_ics($base, $deps)){
455         $this->base= $base;
456       }
457     }
458     if ($action == 'HOME') {
459       $ui= get_userinfo();
460       $this->base= get_base_from_people($ui->dn);
461     }
463     // Reload departments
464     if ($this->departmentBrowser){
465       $this->departments= $this->getDepartments();
466     }
468     // Update filter and refresh entries
469     $this->filter->setBase($this->base);
470     $this->entries= $this->filter->query();
471   }
474   function getBase()
475   {
476     return $this->base;
477   }
480   function parseLayout($layout)
481   {
482     $result= array();
483     $layout= preg_replace("/^\|/", "", $layout);
484     $layout= preg_replace("/\|$/", "", $layout);
485     $cols= split("\|", $layout);
486     foreach ($cols as $index => $config) {
487       if ($config != "") {
488         $components= split(';', $config);
489         $config= "";
490         foreach ($components as $part) {
491           if (preg_match("/^r$/", $part)) {
492             $config.= "text-align:right;";
493             continue;
494           }
495           if (preg_match("/^l$/", $part)) {
496             $config.= "text-align:left;";
497             continue;
498           }
499           if (preg_match("/^c$/", $part)) {
500             $config.= "text-align:center;";
501             continue;
502           }
503           if (preg_match("/^[0-9]+(|px|%)$/", $part)) {
504             $config.= "width:$part;";
505             continue;
506           }
507         }
509         $result[$index]= " style='$config' ";
510       } else {
511         $result[$index]= null;
512       }
513     }
515     // Save number of columns for later use
516     $this->numColumns= count($cols);
518     return $result;
519   }
522   function renderCell($data, $config, $row)
523   {
524     // Replace flat attributes in data string
525     for ($i= 0; $i<$config['count']; $i++) {
526       $attr= $config[$i];
527       $value= "";
528       if (is_array($config[$attr])) {
529         $value= $config[$attr][0];
530       } else {
531         $value= $config[$attr];
532       }
533       $data= preg_replace("/%\{$attr\}/", $value, $data);
534     }
536     // Watch out for filters and prepare to execute them
537     $data= $this->processElementFilter($data, $config, $row);
539     // Replace all non replaced %{...} instances because they
540     // are non resolved attributes or filters
541     $data= preg_replace('/%{[^}]+}/', '&nbsp;', $data);
543     return $data;
544   }
547   function renderBase()
548   {
549     $result= "<select name='BASE' onChange='mainform.submit()' size='1'>";
550     $firstDN= null;
551     $found= false;
553     foreach ($this->bases as $key=>$value) {
554       // Keep first entry to fall back eventually
555       if(!$firstDN) {
556         $firstDN= $key;
557       }
559       // Prepare to render entry
560       $selected= "";
561       if ($key == $this->base) {
562         $selected= " selected";
563         $found= true;
564       }
565       $result.= "<option value='".$key."'$selected>".$value."</option>";
566     }
567     $result.= "</select>";
569     // Reset the currently used base to the first DN we found if there
570     // was no match.
571     if(!$found){
572       $this->base = $firstDN;
573     }
575     return $result;
576   }
579   function processElementFilter($data, $config, $row)
580   {
581     preg_match_all("/%\{filter:([^(]+)\((.*)\)\}/", $data, $matches, PREG_SET_ORDER);
583     foreach ($matches as $match) {
584       if (!isset($this->filters[$match[1]])) {
585         continue;
586       }
587       $cl= preg_replace('/::.*$/', '', $this->filters[$match[1]]);
588       $method= preg_replace('/^.*::/', '', $this->filters[$match[1]]);
590       // Prepare params for function call
591       $params= array();
592       preg_match_all('/"[^"]+"|[^,]+/', $match[2], $parts);
593       foreach ($parts[0] as $param) {
595         // Row is replaced by the row number
596         if ($param == "row") {
597           $params[]= $row;
598         }
600         // pid is replaced by the current PID
601         if ($param == "pid") {
602           $params[]= $this->pid;
603         }
605         // Fixie with "" is passed directly
606         if (preg_match('/^".*"$/', $param)){
607           $params[]= preg_replace('/"/', '', $param);
608         }
610         // LDAP variables get replaced by their objects
611         for ($i= 0; $i<$config['count']; $i++) {
612           if ($param == $config[$i]) {
613             $values= $config[$config[$i]];
614             if (is_array($values)){
615               unset($values['count']);
616             }
617             $params[]= $values;
618           }
619         }
621         // Move dn if needed
622         if ($param == "dn") {
623           $params[]= LDAP::fix($config["dn"]);
624         }
625       }
627       // Replace information
628       if ($cl == "listing") {
629         // Non static call - seems to result in errors
630         $data= @preg_replace('/'.preg_quote($match[0]).'/', call_user_func_array(array($this, "$method"), $params), $data);
631       } else {
632         // Static call
633         $data= preg_replace('/'.preg_quote($match[0]).'/', call_user_func_array(array($cl, $method), $params), $data);
634       }
635     }
637     return $data;
638   }
641   function getObjectType($types, $classes)
642   {
643     // Walk thru types and see if there's something matching
644     foreach ($types as $objectType) {
645       $ocs= $objectType['objectClass'];
646       if (!is_array($ocs)){
647         $ocs= array($ocs);
648       }
650       $found= true;
651       foreach ($ocs as $oc){
652         if (preg_match('/^!(.*)$/', $oc, $match)) {
653           $oc= $match[1];
654           if (in_array($oc, $classes)) {
655             $found= false;
656           }
657         } else {
658           if (!in_array($oc, $classes)) {
659             $found= false;
660           }
661         }
662       }
664       if ($found) {
665         return $objectType;
666       }
667     }
669     return null;
670   }
673   function filterObjectType($dn, $classes)
674   {
675     // Walk thru classes and return on first match
676     $result= "&nbsp;";
678     $objectType= $this->getObjectType($this->objectTypes, $classes);
679     if ($objectType) {
680       $result= "<img class='center' title='".LDAP::fix($dn)."' src='".$objectType["image"]."'>";
681       if (!isset($this->objectTypeCount[$objectType['label']])) {
682         $this->objectTypeCount[$objectType['label']]= 0;
683       }
684       $this->objectTypeCount[$objectType['label']]++;
685     }
686     return $result;
687   }
690   function filterActions($dn, $row, $classes)
691   {
692     // Do nothing if there's no menu defined
693     if (!isset($this->xmlData['actiontriggers']['action'])) {
694       return "&nbsp;";
695     }
697     // Go thru all actions
698     $result= "";
699     $actions= $this->xmlData['actiontriggers']['action'];
700     foreach($actions as $action) {
701       // Skip the entry completely if there's no permission to execute it
702       if (!$this->hasActionPermission($action, $dn)) {
703         continue;
704       }
706       // If there's an objectclass definition and we don't have it
707       // add an empty picture here.
708       if (isset($action['objectclass'])){
709         $objectclass= $action['objectclass'];
710         if (preg_match('/^!(.*)$/', $objectclass, $m)){
711           $objectclass= $m[1];
712           if(in_array($objectclass, $classes)) {
713             $result.= "<img src='images/empty.png' alt=' ' class='center' style='padding:1px'>";
714             continue;
715           }
716         } else {
717           if(!in_array($objectclass, $classes)) {
718             $result.= "<img src='images/empty.png' alt=' ' class='center' style='padding:1px'>";
719             continue;
720           }
721         }
722       }
724       // Render normal entries as usual
725       if ($action['type'] == "entry") {
726         $label= $this->processElementFilter($action['label'], $this->entries[$row], $row);
727         $image= $this->processElementFilter($action['image'], $this->entries[$row], $row);
728         $result.="<input class='center' type='image' src='$image' title='$label' ".
729                  "name='listing_".$action['name']."_$row' style='padding:1px'>";
730       }
732       // Handle special types
733       if ($action['type'] == "copypaste" || $action['type'] == "snapshot") {
735         $objectType= $this->getObjectType($this->objectTypes, $this->entries[$row]['objectClass']);
736         $category= $class= null;
737         if ($objectType) {
738           $category= $objectType['category'];
739           $class= $objectType['class'];
740         }
742         if ($action['type'] == "copypaste") {
743           $result.= $this->renderCopyPasteActions($row, $this->entries[$row]['dn'], $category, $class);
744         } else {
745           $result.= $this->renderSnapshotActions($row, $this->entries[$row]['dn'], $category, $class);
746         }
747       }
748     }
750     return $result;
751   }
754   function filterDepartmentLink($row, $dn, $description)
755   {
756     $attr= $this->departments[$row]['sort-attribute'];
757     $name= $this->departments[$row][$attr];
758     if (is_array($name)){
759       $name= $name[0];
760     }
761     $result= sprintf("%s [%s]", $name, $description[0]);
762     return("<a href='?plug=".$_GET['plug']."&amp;PID=$this->pid&amp;act=department_$row' title='$dn'>$result</a>");
763   }
766   function filterLink()
767   {
768     $result= "&nbsp;";
770     $row= func_get_arg(0);
771     $pid= $this->pid;
772     $dn= LDAP::fix(func_get_arg(1));
773     $params= array(func_get_arg(2));
775     // Collect sprintf params
776     for ($i = 3;$i < func_num_args();$i++) {
777       $val= func_get_arg($i);
778       if (is_array($val)){
779         $params[]= $val[0];
780         continue;
781       }
782       $params[]= $val;
783     }
785     $result= "&nbsp;";
786     $trans= call_user_func_array("sprintf", $params);
787     if ($trans != "") {
788       return("<a href='?plug=".$_GET['plug']."&amp;PID=$pid&amp;act=listing_edit_$row' title='$dn'>$trans</a>");
789     }
791     return $result;
792   }
795   function renderNavigation()
796   {
797     $result= array();
798     $enableBack = true;
799     $enableRoot = true;
800     $enableHome = true;
802     $ui = get_userinfo();
804     /* Check if base = first available base */
805     $deps = $ui->get_module_departments($this->module);
807     if(!count($deps) || $deps[0] == $this->filter->base){
808       $enableBack = false;
809       $enableRoot = false;
810     }
812     $listhead ="";
814     /* Check if we are in users home  department */
815     if(!count($deps) ||$this->filter->base == get_base_from_people($ui->dn)){
816       $enableHome = false;
817     }
819     /* Draw root button */
820     if($enableRoot){
821       $result["ROOT"]= "<input class='center' type='image' src='images/lists/root.png' align='middle' ".
822                        "title='"._("Go to root department")."' name='ROOT' alt='"._("Root")."'>";
823     }else{
824       $result["ROOT"]= "<img src='images/lists/root_grey.png' class='center' alt='"._("Root")."'>";
825     }
827     /* Draw back button */
828     if($enableBack){
829       $result["BACK"]= "<input class='center' type='image' align='middle' src='images/lists/back.png' ".
830                        "title='"._("Go up one department")."' alt='"._("Up")."' name='BACK'>";
831     }else{
832       $result["BACK"]= "<img src='images/lists/back_grey.png' class='center' alt='"._("Up")."'>";
833     }
835     /* Draw home button */
836     if($enableHome){
837       $result["HOME"]= "<input class='center' type='image' align='middle' src='images/lists/home.png' ".
838                        "title='"._("Go to users department")."' alt='"._("Home")."' name='HOME'>";
839     }else{
840       $result["HOME"]= "<img src='images/lists/home_grey.png' class='center' alt='"._("Home")."'>";
841     }
843     /* Draw reload button, this button is enabled everytime */
844     $result["RELOAD"]= "<input class='center' type='image' src='images/lists/reload.png' align='middle' ".
845                        "title='"._("Reload list")."' name='REFRESH' alt='"._("Submit")."'>";
847     return ($result);
848   }
851   function getAction()
852   {
853     // Do not do anything if this is not our PID
854     if(isset($_REQUEST['PID']) && $_REQUEST['PID'] != $this->pid) {
855       return;
856     }
858     $result= array("targets" => array(), "action" => "");
860     // Filter GET with "act" attributes
861     if (isset($_GET['act'])) {
862       $key= validate($_GET['act']);
863       $target= preg_replace('/^listing_[a-zA-Z_]+_([0-9]+)$/', '$1', $key);
864       if (isset($this->entries[$target]['dn'])) {
865         $result['action']= preg_replace('/^listing_([a-zA-Z_]+)_[0-9]+$/', '$1', $key);
866         $result['targets'][]= $this->entries[$target]['dn'];
867       }
869       // Drop targets if empty
870       if (count($result['targets']) == 0) {
871         unset($result['targets']);
872       }
873       return $result;
874     }
876     // Filter POST with "listing_" attributes
877     foreach ($_POST as $key => $prop) {
879       // Capture selections
880       if (preg_match('/^listing_selected_[0-9]+$/', $key)) {
881         $target= preg_replace('/^listing_selected_([0-9]+)$/', '$1', $key);
882         if (isset($this->entries[$target]['dn'])) {
883           $result['targets'][]= $this->entries[$target]['dn'];
884         }
885         continue;
886       }
888       // Capture action with target - this is a one shot
889       if (preg_match('/^listing_[a-zA-Z_]+_[0-9]+(|_x)$/', $key)) {
890         $target= preg_replace('/^listing_[a-zA-Z_]+_([0-9]+)(|_x)$/', '$1', $key);
891         if (isset($this->entries[$target]['dn'])) {
892           $result['action']= preg_replace('/^listing_([a-zA-Z_]+)_[0-9]+(|_x)$/', '$1', $key);
893           $result['targets']= array($this->entries[$target]['dn']);
894         }
895         break;
896       }
898       // Capture action without target
899       if (preg_match('/^listing_[a-zA-Z_]+(|_x)$/', $key)) {
900         $result['action']= preg_replace('/^listing_([a-zA-Z_]+)(|_x)$/', '$1', $key);
901         continue;
902       }
903     }
905     // Filter POST with "act" attributes -> posted from action menu
906     if (isset($_POST['act']) && $_POST['act'] != '') {
907       $result['action']= validate($_POST['act']);
908     }
910     // Drop targets if empty
911     if (count($result['targets']) == 0) {
912       unset($result['targets']);
913     }
914     return $result;
915   }
918   function renderActionMenu()
919   {
920     // Don't send anything if the menu is not defined
921     if (!isset($this->xmlData['actionmenu']['action'])){
922       return "";
923     }
925     // Load shortcut
926     $actions= &$this->xmlData['actionmenu']['action'];
927     $result= "<input type='hidden' name='act' id='actionmenu' value=''>".
928              "<ul class='level1' id='root'><li><a href='#'>Aktionen&nbsp;<img ".
929              "border=0 class='center' src='images/lists/sort-down.png'></a>";
931     // Build ul/li list
932     $result.= $this->recurseActions($actions);
934     return "<div id='pulldown'>".$result."</li></ul><div>";
935   }
938   function recurseActions($actions)
939   {
940     static $level= 2;
941     $result= "<ul class='level$level'>";
942     $separator= "";
944     foreach ($actions as $action) {
946       // Skip the entry completely if there's no permission to execute it
947       if (!$this->hasActionPermission($action, $this->filter->base)) {
948         continue;
949       }
951       // Fill image if set
952       $img= "";
953       if (isset($action['image'])){
954         $img= "<img border='0' class='center' src='".$action['image']."'>&nbsp;";
955       }
957       if ($action['type'] == "separator"){
958         $separator= " style='border-top:1px solid #AAA' ";
959         continue;
960       }
962       // Dive into subs
963       if ($action['type'] == "sub" && isset($action['action'])) {
964         $level++;
965         if (isset($action['label'])){
966           $result.= "<li$separator><a href='#'>$img"._($action['label'])."&nbsp;<img border='0' src='images/forward-arrow.png'></a>";
967         }
968         $result.= $this->recurseActions($action['action'])."</li>";
969         $level--;
970         $separator= "";
971         continue;
972       }
974       // Render entry elseways
975       if (isset($action['label'])){
976         $result.= "<li$separator><a href='#' onClick='document.getElementById(\"actionmenu\").value= \"".$action['name']."\";mainform.submit();'>$img"._($action['label'])."</a></li>";
977       }
979       // Check for special types
980       switch ($action['type']) {
981         case 'copypaste':
982           $result.= $this->renderCopyPasteMenu($separator);
983           break;
985         case 'snapshot':
986           $result.= $this->renderSnapshotMenu($separator);
987           break;
989         case 'exporter':
990           $result.= $this->renderExporterMenu($separator);
991           break;
993         case 'daemon':
994           $result.= $this->renderDaemonMenu($separator);
995           break;
996       }
998       $separator= "";
999     }
1001     $result.= "</ul>";
1002     return $result;
1003   }
1006   function hasActionPermission($action, $dn)
1007   {
1008     $ui= get_userinfo();
1010     if (isset($action['acl'])) {
1011       $acls= $action['acl'];
1012       if (!is_array($acls)) {
1013         $acls= array($acls);
1014       }
1016       // Every ACL has to pass
1017       foreach ($acls as $acl) {
1018         $module= $this->module;
1019         $aclList= array();
1021         // Split for category and plugins if needed
1022         // match for "[rw]" style entries
1023         if (preg_match('/^\[([rwcdm]+)\]$/', $acl, $match)){
1024           $aclList= array($match[1]);
1025         }
1027         // match for "users[rw]" style entries
1028         if (preg_match('/^([a-zA-Z0-9]+)\[([rwcdm]+)\]$/', $acl, $match)){
1029           $module= $match[1];
1030           $aclList= array($match[2]);
1031         }
1033         // match for "users/user[rw]" style entries
1034         if (preg_match('/^([a-zA-Z0-9]+\/[a-zA-Z0-9]+)\[([rwcdm]+)\]$/', $acl, $match)){
1035           $module= $match[1];
1036           $aclList= array($match[2]);
1037         }
1039         // match "users/user[userPassword:rw(,...)*]" style entries
1040         if (preg_match('/^([a-zA-Z0-9]+\/[a-zA-Z0-9]+)\[([a-zA-Z0-9]+:[rwcdm]+(,[a-zA-Z0-9]+:[rwcdm]+)*)\]$/', $acl, $match)){
1041           $module= $match[1];
1042           $aclList= split(',', $match[2]);
1043         }
1045         // Walk thru prepared ACL by using $module
1046         foreach($aclList as $sAcl) {
1047           $checkAcl= "";
1049           // Category or detailed permission?
1050           if (strpos('/', $module) === false) {
1051             if (preg_match('/([a-zA-Z0-9]+):([rwcdm]+)/', $sAcl, $m) ) {
1052               $checkAcl= $ui->get_permissions($dn, $module, $m[1]);
1053               $sAcl= $m[2];
1054             } else {
1055               $checkAcl= $ui->get_permissions($dn, $module, '0');
1056             }
1057           } else {
1058             $checkAcl= $ui->get_category_permissions($dn, $module);
1059           }
1061           // Split up remaining part of the acl and check if it we're
1062           // allowed to do something...
1063           $parts= str_split($sAcl);
1064           foreach ($parts as $part) {
1065             if (strpos($checkAcl, $part) === false){
1066               return false;
1067             }
1068           }
1070         }
1071       }
1072     }
1074     return true;
1075   }
1078   function refreshBasesList()
1079   {
1080     global $config;
1081     $ui= get_userinfo();
1083     // Do some array munching to get it user friendly
1084     $ids= $config->idepartments;
1085     $d= $ui->get_module_departments($this->module);
1086     $k_ids= array_keys($ids);
1087     $deps= array_intersect($d,$k_ids);
1089     // Fill internal bases list
1090     $this->bases= array();
1091     foreach($k_ids as $department){
1092       $this->bases[$department] = $ids[$department];
1093     }
1094   }
1097   function getDepartments()
1098   {
1099     $departments= array();
1100     $ui= get_userinfo();
1102     // Get list of supported department types
1103     $types = departmentManagement::get_support_departments();
1105     // Load departments allowed by ACL
1106     $validDepartments = $ui->get_module_departments($this->module);
1108     // Build filter and look in the LDAP for possible sub departments
1109     // of current base
1110     $filter= "(&(objectClass=gosaDepartment)(|";
1111     $attrs= array("description", "objectClass");
1112     foreach($types as $name => $data){
1113       $filter.= "(objectClass=".$data['OC'].")";
1114       $attrs[]= $data['ATTR'];
1115     }
1116     $filter.= "))";
1117     $res= get_list($filter, $this->module, $this->base, $attrs, GL_NONE | GL_SIZELIMIT);
1119     // Analyze list of departments
1120     foreach ($res as $department) {
1121       if (!in_array($department['dn'], $validDepartments)) {
1122         continue;
1123       }
1125       // Add the attribute where we use for sorting
1126       $oc= null;
1127       foreach(array_keys($types) as $type) {
1128         if (in_array($type, $department['objectClass'])) {
1129           $oc= $type;
1130           break;
1131         }
1132       }
1133       $department['sort-attribute']= $types[$oc]['ATTR'];
1135       // Move to the result list
1136       $departments[]= $department;
1137     }
1139     return $departments;
1140   }
1143   function renderCopyPasteMenu($separator, $copy= true, $cut= true)
1144   {
1145     // We can only provide information if we've got a copypaste handler
1146     // instance
1147     if(!(isset($this->copyPasteHandler) && is_object($this->copyPasteHandler))){
1148       return "";
1149     }
1151     // Presets
1152     $result= "";
1153     $read= $paste= false;
1154     $ui= get_userinfo();
1156     // Switch flags to on if there's at least one category which allows read/paste
1157     foreach($this->categories as $category){
1158       $read= $read || preg_match('/r/', $ui->get_category_permissions($this->base, $category));
1159       $paste= $paste || $ui->is_pasteable($this->base, $category) == 1;
1160     }
1163     // Draw entries that allow copy and cut
1164     if($read){
1166       // Copy entry
1167       if($copy){
1168         $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>";
1169         $separator= "";
1170       }
1172       // Cut entry
1173       if($cut){
1174         $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>";
1175         $separator= "";
1176       }
1177     }
1179     // Draw entries that allow pasting entries
1180     if($paste){
1181       if($this->copyPasteHandler->entries_queued()){
1182         $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>";
1183       }else{
1184         $result.= "<li$separator><a href='#'><img src='images/lists/paste-grey.png' alt='' border='0' class='center'>&nbsp;"._("Paste")."</a></li>";
1185       }
1186     }
1187     
1188     return($result);
1189   }
1192   function renderCopyPasteActions($row, $dn, $category, $class, $copy= true, $cut= true)
1193   {
1194     // We can only provide information if we've got a copypaste handler
1195     // instance
1196     if(!(isset($this->copyPasteHandler) && is_object($this->copyPasteHandler))){
1197       return "";
1198     }
1200     // Presets
1201     $ui = get_userinfo();
1202     $result = "";
1204     // Render cut entries
1205     if($cut){
1206       if($ui->is_cutable($dn, $category, $class)){
1207         $result .= "<input class='center' type='image'
1208           src='images/lists/cut.png' alt='"._("Cut")."' name='listing_cut_$row' title='"._("Cut this entry")."' style='padding:1px'>";
1209       }else{
1210         $result.="<img src='images/empty.png' alt=' ' class='center' style='padding:1px'>";
1211       }
1212     }
1214     // Render copy entries
1215     if($copy){
1216       if($ui->is_copyable($dn, $category, $class)){
1217         $result.= "<input class='center' type='image'
1218           src='images/lists/copy.png' alt='"._("Copy")."' name='listing_copy_$row' title='"._("Copy this entry")."' style='padding:1px'>";
1219       }else{
1220         $result.="<img src='images/empty.png' alt=' ' class='center' style='padding:1px'>";
1221       }
1222     }
1224     return($result);
1225   }
1228   function renderSnapshotMenu($separator)
1229   {
1230     // We can only provide information if we've got a snapshot handler
1231     // instance
1232     if(!(isset($this->snapshotHandler) && is_object($this->snapshotHandler))){
1233       return "";
1234     }
1236     // Presets
1237     $result = "";
1238     $ui = get_userinfo();
1240     if($this->snapshotHandler->enabled() && $ui->allow_snapshot_restore($this->base, $this->module)){
1242       // Check if there is something to restore
1243       $restore= false;
1244       foreach($this->snapshotHandler->getSnapshotBases() as $base){
1245         $restore= $restore || count($this->snapshotHandler->getDeletedSnapshots($base)) > 0;
1246       }
1248       // Draw icons according to the restore flag
1249       if($restore){
1250         $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>";
1251       }else{
1252         $result.= "<li$separator><a href='#'><img src='images/lists/restore_grey.png' alt='' border='0' class='center'>&nbsp;"._("Restore snapshots")."</a></li>";
1253       }
1254     }
1256     return($result);
1257   }
1260   function renderExporterMenu($separator)
1261   {
1262     // Presets
1263     $result = "";
1265     // Draw entries
1266     $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'>";
1268     // Export CVS as build in exporter
1269     $result.= "<li><a href='#' onClick='document.getElementById(\"actionmenu\").value= \"exportCSV\";mainform.submit();'><img border='0' class='center' src='plugins/lists/exportCSV.png'>&nbsp;CSV</a></li>";
1271     // Finalize list
1272     $result.= "</ul></li>";
1274     return($result);
1275   }
1278   function renderSnapshotActions($row, $dn, $category, $class, $copy= true, $cut= true)
1279   {
1280     // We can only provide information if we've got a snapshot handler
1281     // instance
1282     if(!(isset($this->snapshotHandler) && is_object($this->snapshotHandler))){
1283       return "";
1284     }
1286     // Presets
1287     $result= "";
1288     $ui = get_userinfo();
1290     // Only act if enabled here
1291     if($this->snapshotHandler->enabled()){
1293       // Draw restore button
1294       if ($ui->allow_snapshot_restore($dn, $category)){
1296         // Do we have snapshots for this dn?
1297         if($this->snapshotHandler->hasSnapshots($dn)){
1298           $result.= "<input class='center' type='image' src='images/lists/restore.png' ".
1299                      "alt='"._("Restore snapshot")."' name='listing_restore_$row' title='".
1300                      _("Restore snapshot")."' style='padding:1px'>";
1301         } else {
1302           $result.= "<img src='images/lists/restore_grey.png' alt=' ' class='center' style='padding:1px'>";
1303         }
1304       }
1306       // Draw snapshot button
1307       if($ui->allow_snapshot_create($dn, $category)){
1308           $result.= "<input class='center' type='image' src='images/snapshot.png' ".
1309                      "alt='"._("Create snapshot")."' name='listing_snapshot_$row' title='".
1310                      _("Create a new snapshot from this object")."' style='padding:1px'>";
1311       }else{
1312           $result.= "<img src='images/empty.png' alt=' ' class='center' style='padding:1px'>";
1313       }
1314     }
1316     return($result);
1317   }
1320   function renderDaemonMenu($separator)
1321   {
1322     $result= "";
1324     // If there is a daemon registered, draw the menu entries
1325     if(class_available("DaemonEvent")){
1326       $events= DaemonEvent::get_event_types_by_category($this->categories);
1327       if(isset($events['BY_CLASS']) && count($events['BY_CLASS'])){
1328         foreach($events['BY_CLASS'] as $name => $event){
1329           $result.= "<li$separator><a href='#' onClick='document.getElementById(\"actionmenu\").value=\"$name\";mainform.submit();'>".$event['MenuImage']."&nbsp;".$event['s_Menu_Name']."</a></li>";
1330           $separator= "";
1331         }
1332       }
1333     }
1335     return $result;
1336   }
1340 ?>