Code

96b27f9ad136a6a82872ca26867372be40c1a23e
[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       foreach ($this->xmlData['definition']['objectType'] as $index => $otype) {
144         $this->objectTypes[]= $this->xmlData['definition']['objectType'][$index];
145         if (isset($this->xmlData['definition']['objectType'][$index]['category'])){
146           $this->categories[]= $this->xmlData['definition']['objectType'][$index]['category'];
147         }
148       }
149     }
151     // Parse layout per column
152     $this->colprops= $this->parseLayout($this->xmlData['table']['layout']);
154     // Prepare table headers
155     $this->renderHeader();
157     // Assign headline/module
158     $this->headline= _($this->xmlData['definition']['label']);
159     $this->module= $this->xmlData['definition']['module'];
160     if (!is_array($this->categories)){
161       $this->categories= array($this->categories);
162     }
164     return true;  
165   }
168   function renderHeader()
169   {
170     $this->header= array();
172     // Initialize sort?
173     $sortInit= false;
174     if (!$this->sortDirection) {
175       $this->sortColumn= 0;
176       if (isset($this->xmlData['definition']['defaultSortColumn'])){
177         $this->sortColumn= $this->xmlData['definition']['defaultSortColumn'];
178       } else {
179         $this->sortAttribute= "";
180       }
181       $this->sortDirection= array();
182       $sortInit= true;
183     }
185     if (isset($this->xmlData['table']['column'])){
186       foreach ($this->xmlData['table']['column'] as $index => $config) {
187         // Initialize everything to one direction
188         if ($sortInit) {
189           $this->sortDirection[$index]= false;
190         }
192         $sorter= "";
193         if ($index == $this->sortColumn && isset($config['sortAttribute']) &&
194             isset($config['sortType'])) {
195           $this->sortAttribute= $config['sortAttribute'];
196           $this->sortType= $config['sortType'];
197           $sorter= "&nbsp;<img border='0' title='".($this->sortDirection[$index]?_("Up"):_("Down"))."' src='images/lists/sort-".($this->sortDirection[$index]?"up":"down").".png' align='top'>";
198         }
199         $sortable= (isset($config['sortAttribute']));
201         $link= "href='?plug=".$_GET['plug']."&amp;PID=".$this->pid."&amp;act=SORT_$index'";
202         if (isset($config['label'])) {
203           if ($sortable) {
204             $this->header[$index]= "<td class='listheader' ".$this->colprops[$index]."><a $link>"._($config['label'])."$sorter</a></td>";
205           } else {
206             $this->header[$index]= "<td class='listheader' ".$this->colprops[$index].">"._($config['label'])."</td>";
207           }
208         } else {
209           if ($sortable) {
210             $this->header[$index]= "<td class='listheader' ".$this->colprops[$index]."><a $link>&nbsp;$sorter</a></td>";
211           } else {
212             $this->header[$index]= "<td class='listheader' ".$this->colprops[$index].">&nbsp;</td>";
213           }
214         }
215       }
216     }
217   }
219   function render()
220   {
221     // Check for exeeded sizelimit
222     if (($message= check_sizelimit()) != ""){
223       return($message);
224     }
226     // Initialize list
227     $result= "<input type='hidden' value='$this->pid' name='PID'>";
228     $result.= "<div class='contentboxb' id='listing_container' style='border-top:1px solid #B0B0B0;'>";
229     $result.= "<table summary='$this->headline' style='width:600px;height:450px;' cellspacing='0' id='t_scrolltable'>
230 <tr><td class='scrollhead'><table summary='' style='width:100%;' cellspacing='0' id='t_scrollhead'>";
231     $this->numColumns= count($this->colprops) + ($this->multiSelect?1:0);
233     // Build list header
234     $result.= "<tr>";
235     if ($this->multiSelect) {
236       $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>";
237     }
238     foreach ($this->header as $header) {
239       $result.= $header;
240     }
242     // Add 13px for scroller
243     $result.= "<td class='listheader' style='width:13px;border-right:0px;'>&nbsp;</td></table></td></tr>";
245     // New table for the real list contents
246     $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'>";
248     // No results? Just take an empty colspanned row
249     if (count($this->entries) + count($this->departments) == 0) {
250       $result.= "<tr class='rowxp0'><td class='list1nohighlight' colspan='$this->numColumns' style='height:100%;border-right:0px;width:100%;'>&nbsp;</td></tr>";
251     }
253     // Line color alternation
254     $alt= 0;
255     $deps= 0;
257     // Draw department browser if configured and we're not in sub mode
258     if ($this->departmentBrowser && $this->filter->scope != "sub") {
259       // Fill with department browser if configured this way
260       $departmentIterator= new departmentSortIterator($this->departments, $this->sortDirection[$this->sortColumn]);
261       foreach ($departmentIterator as $row => $entry){
262         $result.="<tr class='rowxp".($alt&1)."'>";
264         // Render multi select if needed
265         if ($this->multiSelect) {
266           $result.="<td style='text-align:center;width:20px;' class='list1'>&nbsp;</td>";
267         }
269         // Render defined department columns, fill the rest with some stuff
270         $rest= $this->numColumns - 1;
271         foreach ($this->xmlData['table']['department'] as $index => $config) {
272           $colspan= 1;
273           if (isset($config['span'])){
274             $colspan= $config['span'];
275           }
276           $result.="<td colspan='$colspan' ".$this->colprops[$index]." class='list1'>".$this->renderCell($config['value'], $entry, $row)."</td>";
277           $rest-= $colspan;
278         }
280         // Fill remaining cols with nothing
281         $last= $this->numColumns - $rest;
282         for ($i= 0; $i<$rest; $i++){
283           $result.= "<td ".$this->colprops[$last+$i-1]." class='list1'>&nbsp;</td>";
284         }
285         $result.="</tr>";
287         $alt++;
288       }
289       $deps= $alt;
290     }
292     // Fill with contents, sort as configured
293     $entryIterator= new listingSortIterator($this->entries, $this->sortDirection[$this->sortColumn], $this->sortAttribute, $this->sortType);
294     foreach ($entryIterator as $row => $entry){
295       $result.="<tr class='rowxp".($alt&1)."'>";
297       // Render multi select if needed
298       if ($this->multiSelect) {
299         $result.="<td style='text-align:center;width:20px;' class='list0'><input type='checkbox' id='listing_selected_$row' name='listing_selected_$row'></td>";
300       }
302       foreach ($this->xmlData['table']['column'] as $index => $config) {
303         $result.="<td ".$this->colprops[$index]." class='list0'>".$this->renderCell($config['value'], $entry, $row)."</td>";
304       }
305       $result.="</tr>";
307       $alt++;
308     }
310     // Need to fill the list if it's not full (nobody knows why this is 22 ;-))
311     $emptyListStyle= (count($this->entries) + $deps == 0)?"border:0;":"";
312     if ((count($this->entries) + $deps) < 22) {
313       $result.= "<tr>";
314       for ($i= 0; $i<$this->numColumns; $i++) {
315         if ($i == 0) {
316           $result.= "<td class='list1nohighlight' style='$emptyListStyle height:100%;'>&nbsp;</td>";
317           continue;
318         }
319         if ($i != $this->numColumns-1) {
320           $result.= "<td class='list1nohighlight' style='$emptyListStyle'>&nbsp;</td>";
321         } else {
322           $result.= "<td class='list1nohighlight' style='border-right:1px solid #AAA;$emptyListStyle'>&nbsp;</td>";
323         }
324       }
325       $result.= "</tr>";
326     }
328     $result.= "</table></div></td></tr>";
330     // Add the footer if requested
331     if ($this->showFooter) {
332       $result.= "<tr><td class='scrollhead'><table summary='' style='width:100%' cellspacing='0' id='t_scrollfoot'><tr><td class='listfooter' style='border-bottom:0px;'>";
334       foreach ($this->objectTypes as $objectType) {
335         if (isset($this->objectTypeCount[$objectType['label']])) {
336           $label= _($objectType['label']);
337           $result.= "<img class='center' src='".$objectType['image']."' title='$label' alt='$label'>&nbsp;".$this->objectTypeCount[$objectType['label']]."&nbsp;&nbsp;&nbsp;&nbsp;";
338         }
339       }
341       $result.= "<td class='listfooter' style='width:13px;border-right:0px;'>&nbsp;</td></table></td></tr>";
342     }
344     $result.= "</table></div>";
346     $smarty= get_smarty();
347     $smarty->assign("FILTER", $this->filter->render());
348     $smarty->assign("SIZELIMIT", print_sizelimit_warning());
349     $smarty->assign("LIST", $result);
351     // Assign navigation elements
352     $nav= $this->renderNavigation();
353     foreach ($nav as $key => $html) {
354       $smarty->assign($key, $html);
355     }
357     // Assign action menu / base
358     $smarty->assign("ACTIONS", $this->renderActionMenu());
359     $smarty->assign("BASE", $this->renderBase());
361     // Assign separator
362     $smarty->assign("SEPARATOR", "<img src='images/lists/seperator.png' alt='-' align='middle' height='16' width='1' class='center'>");
364     // Assign summary
365     $smarty->assign("HEADLINE", $this->headline);
367     return ($smarty->fetch(get_template_path($this->xmlData['definition']['template'], true)));
368   }
371   function update()
372   {
373     global $config;
374     $ui= get_userinfo();
376     // Reset object counter
377     $this->objectTypeCount= array();
379     // Do not do anything if this is not our PID
380     if(isset($_REQUEST['PID']) && $_REQUEST['PID'] != $this->pid) {
381       return;
382     }
384     // Save base
385     if (isset($_POST['BASE']) && $this->baseMode == true) {
386       $base= validate($_POST['BASE']);
387       if (isset($this->bases[$base])) {
388         $this->base= $base;
389       }
390     }
392     // Override the base if we got a message from the browser navigation
393     if ($this->departmentBrowser && isset($_GET['act'])) {
394       if (preg_match('/^department_([0-9]+)$/', validate($_GET['act']), $match)){
395         if (isset($this->departments[$match[1]])){
396           $this->base= $this->departments[$match[1]]['dn'];
397         }
398       }
399     }
401     // Filter GET with "act" attributes
402     if (isset($_GET['act'])) {
403       $key= validate($_GET['act']);
404       if (preg_match('/^SORT_([0-9]+)$/', $key, $match)) {
405         // Switch to new column or invert search order?
406         $column= $match[1];
407         if ($this->sortColumn != $column) {
408           $this->sortColumn= $column;
409         } else {
410           $this->sortDirection[$column]= !$this->sortDirection[$column];
411         }
413         // Allow header to update itself according to the new sort settings
414         $this->renderHeader();
415       }
416     }
418     // Override base if we got signals from the navigation elements
419     $action= "";
420     foreach ($_POST as $key => $value) {
421       if (preg_match('/^(ROOT|BACK|HOME)_x$/', $key, $match)) {
422         $action= $match[1];
423         break;
424       }
425     }
427     // Navigation handling
428     if ($action == 'ROOT') {
429       $deps= $ui->get_module_departments($this->module);
430       $this->base= $deps[0];
431     }
432     if ($action == 'BACK') {
433       $deps= $ui->get_module_departments($this->module);
434       $base= preg_replace("/^[^,]+,/", "", $this->base);
435       if(in_array_ics($base, $deps)){
436         $this->base= $base;
437       }
438     }
439     if ($action == 'HOME') {
440       $ui= get_userinfo();
441       $this->base= get_base_from_people($ui->dn);
442     }
444     // Reload departments
445     if ($this->departmentBrowser){
446       $this->departments= $this->getDepartments();
447     }
449     // Update filter and refresh entries
450     $this->filter->setBase($this->base);
451     $this->entries= $this->filter->query();
452   }
455   function parseLayout($layout)
456   {
457     $result= array();
458     $layout= preg_replace("/^\|/", "", $layout);
459     $layout= preg_replace("/\|$/", "", $layout);
460     $cols= split("\|", $layout);
461     foreach ($cols as $index => $config) {
462       if ($config != "") {
463         $components= split(';', $config);
464         $config= "";
465         foreach ($components as $part) {
466           if (preg_match("/^r$/", $part)) {
467             $config.= "text-align:right;";
468             continue;
469           }
470           if (preg_match("/^l$/", $part)) {
471             $config.= "text-align:left;";
472             continue;
473           }
474           if (preg_match("/^c$/", $part)) {
475             $config.= "text-align:center;";
476             continue;
477           }
478           if (preg_match("/^[0-9]+(|px|%)$/", $part)) {
479             $config.= "width:$part;";
480             continue;
481           }
482         }
484         $result[$index]= " style='$config' ";
485       } else {
486         $result[$index]= null;
487       }
488     }
490     // Save number of columns for later use
491     $this->numColumns= count($cols);
493     return $result;
494   }
497   function renderCell($data, $config, $row)
498   {
499     // Replace flat attributes in data string
500     for ($i= 0; $i<$config['count']; $i++) {
501       $attr= $config[$i];
502       $value= "";
503       if (is_array($config[$attr])) {
504         $value= $config[$attr][0];
505       } else {
506         $value= $config[$attr];
507       }
508       $data= preg_replace("/%\{$attr\}/", $value, $data);
509     }
511     // Watch out for filters and prepare to execute them
512     $data= $this->processElementFilter($data, $config, $row);
514     return $data;
515   }
518   function renderBase()
519   {
520     $result= "<select name='BASE' onChange='mainform.submit()' size='1'>";
521     $firstDN= null;
522     $found= false;
524     foreach ($this->bases as $key=>$value) {
525       // Keep first entry to fall back eventually
526       if(!$firstDN) {
527         $firstDN= $key;
528       }
530       // Prepare to render entry
531       $selected= "";
532       if ($key == $this->base) {
533         $selected= " selected";
534         $found= true;
535       }
536       $result.= "<option value='".$key."'$selected>".$value."</option>";
537     }
538     $result.= "</select>";
540     // Reset the currently used base to the first DN we found if there
541     // was no match.
542     if(!$found){
543       $this->base = $firstDN;
544     }
546     return $result;
547   }
550   function processElementFilter($data, $config, $row)
551   {
552     preg_match_all("/%\{filter:([^(]+)\((.*)\)\}/", $data, $matches, PREG_SET_ORDER);
554     foreach ($matches as $match) {
555       if (!isset($this->filters[$match[1]])) {
556         continue;
557       }
558       $cl= preg_replace('/::.*$/', '', $this->filters[$match[1]]);
559       $method= preg_replace('/^.*::/', '', $this->filters[$match[1]]);
561       // Prepare params for function call
562       $params= array();
563       preg_match_all('/"[^"]+"|[^,]+/', $match[2], $parts);
564       foreach ($parts[0] as $param) {
566         // Row is replaced by the row number
567         if ($param == "row") {
568           $params[]= $row;
569         }
571         // pid is replaced by the current PID
572         if ($param == "pid") {
573           $params[]= $this->pid;
574         }
576         // Fixie with "" is passed directly
577         if (preg_match('/^".*"$/', $param)){
578           $params[]= preg_replace('/"/', '', $param);
579         }
581         // LDAP variables get replaced by their objects
582         for ($i= 0; $i<$config['count']; $i++) {
583           if ($param == $config[$i]) {
584             $values= $config[$config[$i]];
585             if (is_array($values)){
586               unset($values['count']);
587             }
588             $params[]= $values;
589           }
590         }
592         // Move dn if needed
593         if ($param == "dn") {
594           $params[]= LDAP::fix($config["dn"]);
595         }
596       }
598       // Replace information
599       if ($cl == "listing") {
600         // Non static call - seems to result in errors
601         $data= @preg_replace('/'.preg_quote($match[0]).'/', call_user_func_array(array($this, "$method"), $params), $data);
602       } else {
603         // Static call
604         $data= preg_replace('/'.preg_quote($match[0]).'/', call_user_func_array(array($cl, $method), $params), $data);
605       }
606     }
608     return $data;
609   }
612   function getObjectType($types, $classes)
613   {
614     // Walk thru types and see if there's something matching
615     foreach ($types as $objectType) {
616       $ocs= $objectType['objectClass'];
617       if (!is_array($ocs)){
618         $ocs= array($ocs);
619       }
621       $found= true;
622       foreach ($ocs as $oc){
623         if (preg_match('/^!(.*)$/', $oc, $match)) {
624           $oc= $match[1];
625           if (in_array($oc, $classes)) {
626             $found= false;
627           }
628         } else {
629           if (!in_array($oc, $classes)) {
630             $found= false;
631           }
632         }
633       }
635       if ($found) {
636         return $objectType;
637       }
638     }
640     return null;
641   }
644   function filterObjectType($dn, $classes)
645   {
646     // Walk thru classes and return on first match
647     $result= "&nbsp;";
649     $objectType= $this->getObjectType($this->objectTypes, $classes);
650     if ($objectType) {
651       $result= "<img class='center' title='".LDAP::fix($dn)."' src='".$objectType["image"]."'>";
652       if (!isset($this->objectTypeCount[$objectType['label']])) {
653         $this->objectTypeCount[$objectType['label']]= 0;
654       }
655       $this->objectTypeCount[$objectType['label']]++;
656     }
657     return $result;
658   }
661   function filterActions($dn, $row, $classes)
662   {
663     // Do nothing if there's no menu defined
664     if (!isset($this->xmlData['actiontriggers']['action'])) {
665       return "&nbsp;";
666     }
668     // Go thru all actions
669     $result= "";
670     $actions= $this->xmlData['actiontriggers']['action'];
671     foreach($actions as $action) {
672       // Skip the entry completely if there's no permission to execute it
673       if (!$this->hasActionPermission($action, $dn)) {
674         continue;
675       }
677       // If there's an objectclass definition and we don't have it
678       // add an empty picture here.
679       if (isset($action['objectclass'])){
680         $objectclass= $action['objectclass'];
681         if (preg_match('/^!(.*)$/', $objectclass, $m)){
682           $objectclass= $m[1];
683           if(in_array($objectclass, $classes)) {
684             $result.= "<img src='images/empty.png' alt=' ' class='center' style='padding:1px'>";
685             continue;
686           }
687         } else {
688           if(!in_array($objectclass, $classes)) {
689             $result.= "<img src='images/empty.png' alt=' ' class='center' style='padding:1px'>";
690             continue;
691           }
692         }
693       }
695       // Render normal entries as usual
696       if ($action['type'] == "entry") {
697         $label= $this->processElementFilter($action['label'], $this->entries[$row], $row);
698         $image= $this->processElementFilter($action['image'], $this->entries[$row], $row);
699         $result.="<input class='center' type='image' src='$image' title='$label' ".
700                  "name='listing_".$action['name']."_$row' style='padding:1px'>";
701       }
703       // Handle special types
704       if ($action['type'] == "copypaste" || $action['type'] == "snapshot") {
706         $objectType= $this->getObjectType($this->objectTypes, $this->entries[$row]['objectClass']);
707         $category= $class= null;
708         if ($objectType) {
709           $category= $objectType['category'];
710           $class= $objectType['class'];
711         }
713         if ($action['type'] == "copypaste") {
714           $result.= $this->renderCopyPasteActions($row, $this->entries[$row]['dn'], $category, $class);
715         } else {
716           $result.= $this->renderSnapshotActions($row, $this->entries[$row]['dn'], $category, $class);
717         }
718       }
719     }
721     return $result;
722   }
725   function filterDepartmentLink($row, $dn, $description)
726   {
727     $attr= $this->departments[$row]['sort-attribute'];
728     $name= $this->departments[$row][$attr];
729     if (is_array($name)){
730       $name= $name[0];
731     }
732     $result= sprintf("%s [%s]", $name, $description[0]);
733     return("<a href='?plug=".$_GET['plug']."&amp;PID=$this->pid&amp;act=department_$row' title='$dn'>$result</a>");
734   }
737   function filterLink()
738   {
739     $result= "&nbsp;";
741     $row= func_get_arg(0);
742     $pid= $this->pid;
743     $dn= LDAP::fix(func_get_arg(1));
744     $params= array(func_get_arg(2));
746     // Collect sprintf params
747     for ($i = 3;$i < func_num_args();$i++) {
748       $val= func_get_arg($i);
749       if (is_array($val)){
750         $params[]= $val[0];
751         continue;
752       }
753       $params[]= $val;
754     }
756     $result= "&nbsp;";
757     $trans= call_user_func_array("sprintf", $params);
758     if ($trans != "") {
759       return("<a href='?plug=".$_GET['plug']."&amp;PID=$pid&amp;act=listing_edit_$row' title='$dn'>$trans</a>");
760     }
762     return $result;
763   }
766   function renderNavigation()
767   {
768     $result= array();
769     $enableBack = true;
770     $enableRoot = true;
771     $enableHome = true;
773     $ui = get_userinfo();
775     /* Check if base = first available base */
776     $deps = $ui->get_module_departments($this->module);
778     if(!count($deps) || $deps[0] == $this->filter->base){
779       $enableBack = false;
780       $enableRoot = false;
781     }
783     $listhead ="";
785     /* Check if we are in users home  department */
786     if(!count($deps) ||$this->filter->base == get_base_from_people($ui->dn)){
787       $enableHome = false;
788     }
790     /* Draw root button */
791     if($enableRoot){
792       $result["ROOT"]= "<input class='center' type='image' src='images/lists/root.png' align='middle' ".
793                        "title='"._("Go to root department")."' name='ROOT' alt='"._("Root")."'>";
794     }else{
795       $result["ROOT"]= "<img src='images/lists/root_grey.png' class='center' alt='"._("Root")."'>";
796     }
798     /* Draw back button */
799     if($enableBack){
800       $result["BACK"]= "<input class='center' type='image' align='middle' src='images/lists/back.png' ".
801                        "title='"._("Go up one department")."' alt='"._("Up")."' name='BACK'>";
802     }else{
803       $result["BACK"]= "<img src='images/lists/back_grey.png' class='center' alt='"._("Up")."'>";
804     }
806     /* Draw home button */
807     if($enableHome){
808       $result["HOME"]= "<input class='center' type='image' align='middle' src='images/lists/home.png' ".
809                        "title='"._("Go to users department")."' alt='"._("Home")."' name='HOME'>";
810     }else{
811       $result["HOME"]= "<img src='images/lists/home_grey.png' class='center' alt='"._("Home")."'>";
812     }
814     /* Draw reload button, this button is enabled everytime */
815     $result["RELOAD"]= "<input class='center' type='image' src='images/lists/reload.png' align='middle' ".
816                        "title='"._("Reload list")."' name='REFRESH' alt='"._("Submit")."'>";
818     return ($result);
819   }
822   function getAction()
823   {
824     // Do not do anything if this is not our PID
825     if(isset($_REQUEST['PID']) && $_REQUEST['PID'] != $this->pid) {
826       return;
827     }
829     $result= array("targets" => array(), "action" => "");
831     // Filter GET with "act" attributes
832     if (isset($_GET['act'])) {
833       $key= validate($_GET['act']);
834       $target= preg_replace('/^listing_[a-zA-Z_]+_([0-9]+)$/', '$1', $key);
835       if (isset($this->entries[$target]['dn'])) {
836         $result['action']= preg_replace('/^listing_([a-zA-Z_]+)_[0-9]+$/', '$1', $key);
837         $result['targets'][]= $this->entries[$target]['dn'];
838       }
840       // Drop targets if empty
841       if (count($result['targets']) == 0) {
842         unset($result['targets']);
843       }
844       return $result;
845     }
847     // Filter POST with "listing_" attributes
848     foreach ($_POST as $key => $prop) {
850       // Capture selections
851       if (preg_match('/^listing_selected_[0-9]+$/', $key)) {
852         $target= preg_replace('/^listing_selected_([0-9]+)$/', '$1', $key);
853         if (isset($this->entries[$target]['dn'])) {
854           $result['targets'][]= $this->entries[$target]['dn'];
855         }
856         continue;
857       }
859       // Capture action with target - this is a one shot
860       if (preg_match('/^listing_[a-zA-Z_]+_[0-9]+(|_x)$/', $key)) {
861         $target= preg_replace('/^listing_[a-zA-Z_]+_([0-9]+)(|_x)$/', '$1', $key);
862         if (isset($this->entries[$target]['dn'])) {
863           $result['action']= preg_replace('/^listing_([a-zA-Z_]+)_[0-9]+(|_x)$/', '$1', $key);
864           $result['targets']= array($this->entries[$target]['dn']);
865         }
866         break;
867       }
869       // Capture action without target
870       if (preg_match('/^listing_[a-zA-Z_]+(|_x)$/', $key)) {
871         $result['action']= preg_replace('/^listing_([a-zA-Z_]+)(|_x)$/', '$1', $key);
872         continue;
873       }
874     }
876     // Filter POST with "act" attributes -> posted from action menu
877     if (isset($_POST['act']) && $_POST['act'] != '') {
878       $result['action']= validate($_POST['act']);
879     }
881     // Drop targets if empty
882     if (count($result['targets']) == 0) {
883       unset($result['targets']);
884     }
885     return $result;
886   }
889   function renderActionMenu()
890   {
891     // Don't send anything if the menu is not defined
892     if (!isset($this->xmlData['actionmenu']['action'])){
893       return "";
894     }
896     // Load shortcut
897     $actions= &$this->xmlData['actionmenu']['action'];
898     $result= "<input type='hidden' name='act' id='actionmenu' value=''>".
899              "<ul class='level1' id='root'><li><a href='#'>Aktionen&nbsp;<img ".
900              "border=0 src='images/lists/sort-down.png'></a>";
902     // Build ul/li list
903     $result.= $this->recurseActions($actions);
905     return "<div id='pulldown'>".$result."</li></ul><div>";
906   }
909   function recurseActions($actions)
910   {
911     static $level= 2;
912     $result= "<ul class='level$level'>";
913     $separator= "";
915     foreach ($actions as $action) {
917       // Skip the entry completely if there's no permission to execute it
918       if (!$this->hasActionPermission($action, $this->filter->base)) {
919         continue;
920       }
922       // Fill image if set
923       $img= "";
924       if (isset($action['image'])){
925         $img= "<img border=0 src='".$action['image']."'>&nbsp;";
926       }
928       if ($action['type'] == "separator"){
929         $separator= " style='border-top:1px solid #AAA' ";
930         continue;
931       }
933       // Dive into subs
934       if ($action['type'] == "sub" && isset($action['action'])) {
935         $level++;
936         if (isset($action['label'])){
937           $result.= "<li$separator><a href='#'>$img"._($action['label'])."&nbsp;<img border='0' src='images/forward-arrow.png'></a>";
938         }
939         $result.= $this->recurseActions($action['action'])."</li>";
940         $level--;
941         $separator= "";
942         continue;
943       }
945       // Render entry elseways
946       if (isset($action['label'])){
947         $result.= "<li$separator><a href='#' onClick='document.getElementById(\"actionmenu\").value= \"".$action['name']."\";mainform.submit();'>$img"._($action['label'])."</a></li>";
948       }
950       // Check for special types
951       switch ($action['type']) {
952         case 'copypaste':
953           $result.= $this->renderCopyPasteMenu($separator);
954           break;
956         case 'snapshot':
957           $result.= $this->renderSnapshotMenu($separator);
958           break;
960         case 'daemon':
961           $result.= $this->renderDaemonMenu($separator);
962           break;
963       }
965       $separator= "";
966     }
968     $result.= "</ul>";
969     return $result;
970   }
973   function hasActionPermission($action, $dn)
974   {
975     $ui= get_userinfo();
977     if (isset($action['acl'])) {
978       $acls= $action['acl'];
979       if (!is_array($acls)) {
980         $acls= array($acls);
981       }
983       // Every ACL has to pass
984       foreach ($acls as $acl) {
985         $module= $this->module;
986         $aclList= array();
988         // Split for category and plugins if needed
989         // match for "[rw]" style entries
990         if (preg_match('/^\[([rwcdm]+)\]$/', $acl, $match)){
991           $aclList= array($match[1]);
992         }
994         // match for "users[rw]" style entries
995         if (preg_match('/^([a-zA-Z0-9]+)\[([rwcdm]+)\]$/', $acl, $match)){
996           $module= $match[1];
997           $aclList= array($match[2]);
998         }
1000         // match for "users/user[rw]" style entries
1001         if (preg_match('/^([a-zA-Z0-9]+\/[a-zA-Z0-9]+)\[([rwcdm]+)\]$/', $acl, $match)){
1002           $module= $match[1];
1003           $aclList= array($match[2]);
1004         }
1006         // match "users/user[userPassword:rw(,...)*]" style entries
1007         if (preg_match('/^([a-zA-Z0-9]+\/[a-zA-Z0-9]+)\[([a-zA-Z0-9]+:[rwcdm]+(,[a-zA-Z0-9]+:[rwcdm]+)*)\]$/', $acl, $match)){
1008           $module= $match[1];
1009           $aclList= split(',', $match[2]);
1010         }
1012         // Walk thru prepared ACL by using $module
1013         foreach($aclList as $sAcl) {
1014           $checkAcl= "";
1016           // Category or detailed permission?
1017           if (strpos('/', $module) === false) {
1018             if (preg_match('/([a-zA-Z0-9]+):([rwcdm]+)/', $sAcl, $m) ) {
1019               $checkAcl= $ui->get_permissions($dn, $module, $m[1]);
1020               $sAcl= $m[2];
1021             } else {
1022               $checkAcl= $ui->get_permissions($dn, $module, '0');
1023             }
1024           } else {
1025             $checkAcl= $ui->get_category_permissions($dn, $module);
1026           }
1028           // Split up remaining part of the acl and check if it we're
1029           // allowed to do something...
1030           $parts= str_split($sAcl);
1031           foreach ($parts as $part) {
1032             if (strpos($checkAcl, $part) === false){
1033               return false;
1034             }
1035           }
1037         }
1038       }
1039     }
1041     return true;
1042   }
1045   function refreshBasesList()
1046   {
1047     global $config;
1048     $ui= get_userinfo();
1050     // Do some array munching to get it user friendly
1051     $ids= $config->idepartments;
1052     $d= $ui->get_module_departments($this->module);
1053     $k_ids= array_keys($ids);
1054     $deps= array_intersect($d,$k_ids);
1056     // Fill internal bases list
1057     $this->bases= array();
1058     foreach($k_ids as $department){
1059       $this->bases[$department] = $ids[$department];
1060     }
1061   }
1064   function getDepartments()
1065   {
1066     $departments= array();
1067     $ui= get_userinfo();
1069     // Get list of supported department types
1070     $types = departmentManagement::get_support_departments();
1072     // Load departments allowed by ACL
1073     $validDepartments = $ui->get_module_departments($this->module);
1075     // Build filter and look in the LDAP for possible sub departments
1076     // of current base
1077     $filter= "(&(objectClass=gosaDepartment)(|";
1078     $attrs= array("description", "objectClass");
1079     foreach($types as $name => $data){
1080       $filter.= "(objectClass=".$data['OC'].")";
1081       $attrs[]= $data['ATTR'];
1082     }
1083     $filter.= "))";
1084     $res= get_list($filter, $this->module, $this->base, $attrs, GL_NONE | GL_SIZELIMIT);
1086     // Analyze list of departments
1087     foreach ($res as $department) {
1088       if (!in_array($department['dn'], $validDepartments)) {
1089         continue;
1090       }
1092       // Add the attribute where we use for sorting
1093       $oc= null;
1094       foreach(array_keys($types) as $type) {
1095         if (in_array($type, $department['objectClass'])) {
1096           $oc= $type;
1097           break;
1098         }
1099       }
1100       $department['sort-attribute']= $types[$oc]['ATTR'];
1102       // Move to the result list
1103       $departments[]= $department;
1104     }
1106     return $departments;
1107   }
1110   function renderCopyPasteMenu($separator, $copy= true, $cut= true)
1111   {
1112     // We can only provide information if we've got a copypaste handler
1113     // instance
1114     if(!(isset($this->copyPasteHandler) && is_object($this->copyPasteHandler))){
1115       return "";
1116     }
1118     // Presets
1119     $result= "";
1120     $read= $paste= false;
1121     $ui= get_userinfo();
1123     // Switch flags to on if there's at least one category which allows read/paste
1124     foreach($this->categories as $category){
1125       $read= $read || preg_match('/r/', $ui->get_category_permissions($this->base, $category));
1126       $paste= $paste || $ui->is_pasteable($this->base, $category) == 1;
1127     }
1130     // Draw entries that allow copy and cut
1131     if($read){
1133       // Copy entry
1134       if($copy){
1135         $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>";
1136         $separator= "";
1137       }
1139       // Cut entry
1140       if($cut){
1141         $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>";
1142         $separator= "";
1143       }
1144     }
1146     // Draw entries that allow pasting entries
1147     if($paste){
1148       if($this->copyPasteHandler->entries_queued()){
1149         $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>";
1150       }else{
1151         $result.= "<li$separator><a href='#'><img src='images/lists/paste-grey.png' alt='' border='0' class='center'>&nbsp;"._("Paste")."</a></li>";
1152       }
1153     }
1154     
1155     return($result);
1156   }
1159   function renderCopyPasteActions($row, $dn, $category, $class, $copy= true, $cut= true)
1160   {
1161     // We can only provide information if we've got a copypaste handler
1162     // instance
1163     if(!(isset($this->copyPasteHandler) && is_object($this->copyPasteHandler))){
1164       return "";
1165     }
1167     // Presets
1168     $ui = get_userinfo();
1169     $result = "";
1171     // Render cut entries
1172     if($cut){
1173       if($ui->is_cutable($dn, $category, $class)){
1174         $result .= "<input class='center' type='image'
1175           src='images/lists/cut.png' alt='"._("Cut")."' name='listing_cut_$row' title='"._("Cut this entry")."' style='padding:1px'>";
1176       }else{
1177         $result.="<img src='images/empty.png' alt=' ' class='center' style='padding:1px'>";
1178       }
1179     }
1181     // Render copy entries
1182     if($copy){
1183       if($ui->is_copyable($dn, $category, $class)){
1184         $result.= "<input class='center' type='image'
1185           src='images/lists/copy.png' alt='"._("Copy")."' name='listing_copy_$row' title='"._("Copy this entry")."' style='padding:1px'>";
1186       }else{
1187         $result.="<img src='images/empty.png' alt=' ' class='center' style='padding:1px'>";
1188       }
1189     }
1191     return($result);
1192   }
1195   function renderSnapshotMenu($separator)
1196   {
1197     // We can only provide information if we've got a snapshot handler
1198     // instance
1199     if(!(isset($this->snapshotHandler) && is_object($this->snapshotHandler))){
1200       return "";
1201     }
1203     // Presets
1204     $result = "";
1205     $ui = get_userinfo();
1207     if($this->snapshotHandler->enabled() && $ui->allow_snapshot_restore($this->base, $this->module)){
1209       // Check if there is something to restore
1210       $restore= false;
1211       foreach($this->snapshotHandler->getSnapshotBases() as $base){
1212         $restore= $restore || count($this->snapshotHandler->getDeletedSnapshots($base)) > 0;
1213       }
1215       // Draw icons according to the restore flag
1216       if($restore){
1217         $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>";
1218       }else{
1219         $result.= "<li$separator><a href='#'><img src='images/lists/restore_grey.png' alt='' border='0' class='center'>&nbsp;"._("Restore snapshots")."</a></li>";
1220       }
1221     }
1223     return($result);
1224   }
1227   function renderSnapshotActions($row, $dn, $category, $class, $copy= true, $cut= true)
1228   {
1229     // We can only provide information if we've got a snapshot handler
1230     // instance
1231     if(!(isset($this->snapshotHandler) && is_object($this->snapshotHandler))){
1232       return "";
1233     }
1235     // Presets
1236     $result= "";
1237     $ui = get_userinfo();
1239     // Only act if enabled here
1240     if($this->snapshotHandler->enabled()){
1242       // Draw restore button
1243       if ($ui->allow_snapshot_restore($dn, $category)){
1245         // Do we have snapshots for this dn?
1246         if($this->snapshotHandler->hasSnapshots($dn)){
1247           $result.= "<input class='center' type='image' src='images/lists/restore.png' ".
1248                      "alt='"._("Restore snapshot")."' name='listing_restore_$row' title='".
1249                      _("Restore snapshot")."' style='padding:1px'>";
1250         } else {
1251           $result.= "<img src='images/lists/restore_grey.png' alt=' ' class='center' style='padding:1px'>";
1252         }
1253       }
1255       // Draw snapshot button
1256       if($ui->allow_snapshot_create($dn, $category)){
1257           $result.= "<input class='center' type='image' src='images/snapshot.png' ".
1258                      "alt='"._("Create snapshot")."' name='listing_snapshot_$row' title='".
1259                      _("Create a new snapshot from this object")."' style='padding:1px'>";
1260       }else{
1261           $result.= "<img src='images/empty.png' alt=' ' class='center' style='padding:1px'>";
1262       }
1263     }
1265     return($result);
1266   }
1269   function renderDaemonMenu($separator)
1270   {
1271     $result= "";
1273     // If there is a daemon registered, draw the menu entries
1274     if(class_available("DaemonEvent")){
1275       $events= DaemonEvent::get_event_types_by_category($this->categories);
1276       if(isset($events['BY_CLASS']) && count($events['BY_CLASS'])){
1277         foreach($events['BY_CLASS'] as $name => $event){
1278           $result.= "<li$separator><a href='#' onClick='document.getElementById(\"actionmenu\").value= \"$name\";mainform.submit();'><img src='".$event['MenuImage']."' alt='' border='0' class='center'>&nbsp;".$event['s_Menu_Name']."</a></li>";
1279           $separator= "";
1280         }
1281       }
1282     }
1284     return $result;
1285   }
1289 ?>