Code

Fixed entry loading
[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         $this->entries[$row]["_sort$index"]= $renderedCell;
310       }
311       $trow.="</tr>\n";
313       // Save rendered entry
314       $this->entries[$row]['_rendered']= $trow;
316       $alt++;
317     }
319     // Complete list by sorting entries for _sort$index and appending them to the output
320     $entryIterator= new listingSortIterator($this->entries, $this->sortDirection[$this->sortColumn], "_sort".$this->sortColumn, $this->sortType);
321     foreach ($entryIterator as $row => $entry){
322       $result.= $entry['_rendered'];
323     }
325     // Need to fill the list if it's not full (nobody knows why this is 22 ;-))
326     $emptyListStyle= (count($this->entries) + $deps == 0)?"border:0;":"";
327     if ((count($this->entries) + $deps) < 22) {
328       $result.= "<tr>";
329       for ($i= 0; $i<$this->numColumns; $i++) {
330         if ($i == 0) {
331           $result.= "<td class='list1nohighlight' style='$emptyListStyle height:100%;'>&nbsp;</td>";
332           continue;
333         }
334         if ($i != $this->numColumns-1) {
335           $result.= "<td class='list1nohighlight' style='$emptyListStyle'>&nbsp;</td>";
336         } else {
337           $result.= "<td class='list1nohighlight' style='border-right:1px solid #AAA;$emptyListStyle'>&nbsp;</td>";
338         }
339       }
340       $result.= "</tr>";
341     }
343     $result.= "</table></div></td></tr>";
345     // Add the footer if requested
346     if ($this->showFooter) {
347       $result.= "<tr><td class='scrollhead'><table summary='' style='width:100%' cellspacing='0' id='t_scrollfoot'><tr><td class='listfooter' style='border-bottom:0px;'>";
349       foreach ($this->objectTypes as $objectType) {
350         if (isset($this->objectTypeCount[$objectType['label']])) {
351           $label= _($objectType['label']);
352           $result.= "<img class='center' src='".$objectType['image']."' title='$label' alt='$label'>&nbsp;".$this->objectTypeCount[$objectType['label']]."&nbsp;&nbsp;&nbsp;&nbsp;";
353         }
354       }
356       $result.= "<td class='listfooter' style='width:13px;border-right:0px;'>&nbsp;</td></table></td></tr>";
357     }
359     $result.= "</table></div>";
361     $smarty= get_smarty();
362     $smarty->assign("FILTER", $this->filter->render());
363     $smarty->assign("SIZELIMIT", print_sizelimit_warning());
364     $smarty->assign("LIST", $result);
366     // Assign navigation elements
367     $nav= $this->renderNavigation();
368     foreach ($nav as $key => $html) {
369       $smarty->assign($key, $html);
370     }
372     // Assign action menu / base
373     $smarty->assign("ACTIONS", $this->renderActionMenu());
374     $smarty->assign("BASE", $this->renderBase());
376     // Assign separator
377     $smarty->assign("SEPARATOR", "<img src='images/lists/seperator.png' alt='-' align='middle' height='16' width='1' class='center'>");
379     // Assign summary
380     $smarty->assign("HEADLINE", $this->headline);
382     return ($smarty->fetch(get_template_path($this->xmlData['definition']['template'], true)));
383   }
386   function update()
387   {
388     global $config;
389     $ui= get_userinfo();
391     // Reset object counter
392     $this->objectTypeCount= array();
394     // Do not do anything if this is not our PID
395     if(isset($_REQUEST['PID']) && $_REQUEST['PID'] != $this->pid) {
396       return;
397     }
399     // Save base
400     if (isset($_POST['BASE']) && $this->baseMode == true) {
401       $base= validate($_POST['BASE']);
402       if (isset($this->bases[$base])) {
403         $this->base= $base;
404       }
405     }
407     // Override the base if we got a message from the browser navigation
408     if ($this->departmentBrowser && isset($_GET['act'])) {
409       if (preg_match('/^department_([0-9]+)$/', validate($_GET['act']), $match)){
410         if (isset($this->departments[$match[1]])){
411           $this->base= $this->departments[$match[1]]['dn'];
412         }
413       }
414     }
416     // Filter GET with "act" attributes
417     if (isset($_GET['act'])) {
418       $key= validate($_GET['act']);
419       if (preg_match('/^SORT_([0-9]+)$/', $key, $match)) {
420         // Switch to new column or invert search order?
421         $column= $match[1];
422         if ($this->sortColumn != $column) {
423           $this->sortColumn= $column;
424         } else {
425           $this->sortDirection[$column]= !$this->sortDirection[$column];
426         }
428         // Allow header to update itself according to the new sort settings
429         $this->renderHeader();
430       }
431     }
433     // Override base if we got signals from the navigation elements
434     $action= "";
435     foreach ($_POST as $key => $value) {
436       if (preg_match('/^(ROOT|BACK|HOME)_x$/', $key, $match)) {
437         $action= $match[1];
438         break;
439       }
440     }
442     // Navigation handling
443     if ($action == 'ROOT') {
444       $deps= $ui->get_module_departments($this->module);
445       $this->base= $deps[0];
446     }
447     if ($action == 'BACK') {
448       $deps= $ui->get_module_departments($this->module);
449       $base= preg_replace("/^[^,]+,/", "", $this->base);
450       if(in_array_ics($base, $deps)){
451         $this->base= $base;
452       }
453     }
454     if ($action == 'HOME') {
455       $ui= get_userinfo();
456       $this->base= get_base_from_people($ui->dn);
457     }
459     // Reload departments
460     if ($this->departmentBrowser){
461       $this->departments= $this->getDepartments();
462     }
464     // Update filter and refresh entries
465     $this->filter->setBase($this->base);
466     $this->entries= $this->filter->query();
467   }
470   function parseLayout($layout)
471   {
472     $result= array();
473     $layout= preg_replace("/^\|/", "", $layout);
474     $layout= preg_replace("/\|$/", "", $layout);
475     $cols= split("\|", $layout);
476     foreach ($cols as $index => $config) {
477       if ($config != "") {
478         $components= split(';', $config);
479         $config= "";
480         foreach ($components as $part) {
481           if (preg_match("/^r$/", $part)) {
482             $config.= "text-align:right;";
483             continue;
484           }
485           if (preg_match("/^l$/", $part)) {
486             $config.= "text-align:left;";
487             continue;
488           }
489           if (preg_match("/^c$/", $part)) {
490             $config.= "text-align:center;";
491             continue;
492           }
493           if (preg_match("/^[0-9]+(|px|%)$/", $part)) {
494             $config.= "width:$part;";
495             continue;
496           }
497         }
499         $result[$index]= " style='$config' ";
500       } else {
501         $result[$index]= null;
502       }
503     }
505     // Save number of columns for later use
506     $this->numColumns= count($cols);
508     return $result;
509   }
512   function renderCell($data, $config, $row)
513   {
514     // Replace flat attributes in data string
515     for ($i= 0; $i<$config['count']; $i++) {
516       $attr= $config[$i];
517       $value= "";
518       if (is_array($config[$attr])) {
519         $value= $config[$attr][0];
520       } else {
521         $value= $config[$attr];
522       }
523       $data= preg_replace("/%\{$attr\}/", $value, $data);
524     }
526     // Watch out for filters and prepare to execute them
527     $data= $this->processElementFilter($data, $config, $row);
529     // Replace all non replaced %{...} instances because they
530     // are non resolved attributes or filters
531     $data= preg_replace('/%{[^}]+}/', '&nbsp;', $data);
533     return $data;
534   }
537   function renderBase()
538   {
539     $result= "<select name='BASE' onChange='mainform.submit()' size='1'>";
540     $firstDN= null;
541     $found= false;
543     foreach ($this->bases as $key=>$value) {
544       // Keep first entry to fall back eventually
545       if(!$firstDN) {
546         $firstDN= $key;
547       }
549       // Prepare to render entry
550       $selected= "";
551       if ($key == $this->base) {
552         $selected= " selected";
553         $found= true;
554       }
555       $result.= "<option value='".$key."'$selected>".$value."</option>";
556     }
557     $result.= "</select>";
559     // Reset the currently used base to the first DN we found if there
560     // was no match.
561     if(!$found){
562       $this->base = $firstDN;
563     }
565     return $result;
566   }
569   function processElementFilter($data, $config, $row)
570   {
571     preg_match_all("/%\{filter:([^(]+)\((.*)\)\}/", $data, $matches, PREG_SET_ORDER);
573     foreach ($matches as $match) {
574       if (!isset($this->filters[$match[1]])) {
575         continue;
576       }
577       $cl= preg_replace('/::.*$/', '', $this->filters[$match[1]]);
578       $method= preg_replace('/^.*::/', '', $this->filters[$match[1]]);
580       // Prepare params for function call
581       $params= array();
582       preg_match_all('/"[^"]+"|[^,]+/', $match[2], $parts);
583       foreach ($parts[0] as $param) {
585         // Row is replaced by the row number
586         if ($param == "row") {
587           $params[]= $row;
588         }
590         // pid is replaced by the current PID
591         if ($param == "pid") {
592           $params[]= $this->pid;
593         }
595         // Fixie with "" is passed directly
596         if (preg_match('/^".*"$/', $param)){
597           $params[]= preg_replace('/"/', '', $param);
598         }
600         // LDAP variables get replaced by their objects
601         for ($i= 0; $i<$config['count']; $i++) {
602           if ($param == $config[$i]) {
603             $values= $config[$config[$i]];
604             if (is_array($values)){
605               unset($values['count']);
606             }
607             $params[]= $values;
608           }
609         }
611         // Move dn if needed
612         if ($param == "dn") {
613           $params[]= LDAP::fix($config["dn"]);
614         }
615       }
617       // Replace information
618       if ($cl == "listing") {
619         // Non static call - seems to result in errors
620         $data= @preg_replace('/'.preg_quote($match[0]).'/', call_user_func_array(array($this, "$method"), $params), $data);
621       } else {
622         // Static call
623         $data= preg_replace('/'.preg_quote($match[0]).'/', call_user_func_array(array($cl, $method), $params), $data);
624       }
625     }
627     return $data;
628   }
631   function getObjectType($types, $classes)
632   {
633     // Walk thru types and see if there's something matching
634     foreach ($types as $objectType) {
635       $ocs= $objectType['objectClass'];
636       if (!is_array($ocs)){
637         $ocs= array($ocs);
638       }
640       $found= true;
641       foreach ($ocs as $oc){
642         if (preg_match('/^!(.*)$/', $oc, $match)) {
643           $oc= $match[1];
644           if (in_array($oc, $classes)) {
645             $found= false;
646           }
647         } else {
648           if (!in_array($oc, $classes)) {
649             $found= false;
650           }
651         }
652       }
654       if ($found) {
655         return $objectType;
656       }
657     }
659     return null;
660   }
663   function filterObjectType($dn, $classes)
664   {
665     // Walk thru classes and return on first match
666     $result= "&nbsp;";
668     $objectType= $this->getObjectType($this->objectTypes, $classes);
669     if ($objectType) {
670       $result= "<img class='center' title='".LDAP::fix($dn)."' src='".$objectType["image"]."'>";
671       if (!isset($this->objectTypeCount[$objectType['label']])) {
672         $this->objectTypeCount[$objectType['label']]= 0;
673       }
674       $this->objectTypeCount[$objectType['label']]++;
675     }
676     return $result;
677   }
680   function filterActions($dn, $row, $classes)
681   {
682     // Do nothing if there's no menu defined
683     if (!isset($this->xmlData['actiontriggers']['action'])) {
684       return "&nbsp;";
685     }
687     // Go thru all actions
688     $result= "";
689     $actions= $this->xmlData['actiontriggers']['action'];
690     foreach($actions as $action) {
691       // Skip the entry completely if there's no permission to execute it
692       if (!$this->hasActionPermission($action, $dn)) {
693         continue;
694       }
696       // If there's an objectclass definition and we don't have it
697       // add an empty picture here.
698       if (isset($action['objectclass'])){
699         $objectclass= $action['objectclass'];
700         if (preg_match('/^!(.*)$/', $objectclass, $m)){
701           $objectclass= $m[1];
702           if(in_array($objectclass, $classes)) {
703             $result.= "<img src='images/empty.png' alt=' ' class='center' style='padding:1px'>";
704             continue;
705           }
706         } else {
707           if(!in_array($objectclass, $classes)) {
708             $result.= "<img src='images/empty.png' alt=' ' class='center' style='padding:1px'>";
709             continue;
710           }
711         }
712       }
714       // Render normal entries as usual
715       if ($action['type'] == "entry") {
716         $label= $this->processElementFilter($action['label'], $this->entries[$row], $row);
717         $image= $this->processElementFilter($action['image'], $this->entries[$row], $row);
718         $result.="<input class='center' type='image' src='$image' title='$label' ".
719                  "name='listing_".$action['name']."_$row' style='padding:1px'>";
720       }
722       // Handle special types
723       if ($action['type'] == "copypaste" || $action['type'] == "snapshot") {
725         $objectType= $this->getObjectType($this->objectTypes, $this->entries[$row]['objectClass']);
726         $category= $class= null;
727         if ($objectType) {
728           $category= $objectType['category'];
729           $class= $objectType['class'];
730         }
732         if ($action['type'] == "copypaste") {
733           $result.= $this->renderCopyPasteActions($row, $this->entries[$row]['dn'], $category, $class);
734         } else {
735           $result.= $this->renderSnapshotActions($row, $this->entries[$row]['dn'], $category, $class);
736         }
737       }
738     }
740     return $result;
741   }
744   function filterDepartmentLink($row, $dn, $description)
745   {
746     $attr= $this->departments[$row]['sort-attribute'];
747     $name= $this->departments[$row][$attr];
748     if (is_array($name)){
749       $name= $name[0];
750     }
751     $result= sprintf("%s [%s]", $name, $description[0]);
752     return("<a href='?plug=".$_GET['plug']."&amp;PID=$this->pid&amp;act=department_$row' title='$dn'>$result</a>");
753   }
756   function filterLink()
757   {
758     $result= "&nbsp;";
760     $row= func_get_arg(0);
761     $pid= $this->pid;
762     $dn= LDAP::fix(func_get_arg(1));
763     $params= array(func_get_arg(2));
765     // Collect sprintf params
766     for ($i = 3;$i < func_num_args();$i++) {
767       $val= func_get_arg($i);
768       if (is_array($val)){
769         $params[]= $val[0];
770         continue;
771       }
772       $params[]= $val;
773     }
775     $result= "&nbsp;";
776     $trans= call_user_func_array("sprintf", $params);
777     if ($trans != "") {
778       return("<a href='?plug=".$_GET['plug']."&amp;PID=$pid&amp;act=listing_edit_$row' title='$dn'>$trans</a>");
779     }
781     return $result;
782   }
785   function renderNavigation()
786   {
787     $result= array();
788     $enableBack = true;
789     $enableRoot = true;
790     $enableHome = true;
792     $ui = get_userinfo();
794     /* Check if base = first available base */
795     $deps = $ui->get_module_departments($this->module);
797     if(!count($deps) || $deps[0] == $this->filter->base){
798       $enableBack = false;
799       $enableRoot = false;
800     }
802     $listhead ="";
804     /* Check if we are in users home  department */
805     if(!count($deps) ||$this->filter->base == get_base_from_people($ui->dn)){
806       $enableHome = false;
807     }
809     /* Draw root button */
810     if($enableRoot){
811       $result["ROOT"]= "<input class='center' type='image' src='images/lists/root.png' align='middle' ".
812                        "title='"._("Go to root department")."' name='ROOT' alt='"._("Root")."'>";
813     }else{
814       $result["ROOT"]= "<img src='images/lists/root_grey.png' class='center' alt='"._("Root")."'>";
815     }
817     /* Draw back button */
818     if($enableBack){
819       $result["BACK"]= "<input class='center' type='image' align='middle' src='images/lists/back.png' ".
820                        "title='"._("Go up one department")."' alt='"._("Up")."' name='BACK'>";
821     }else{
822       $result["BACK"]= "<img src='images/lists/back_grey.png' class='center' alt='"._("Up")."'>";
823     }
825     /* Draw home button */
826     if($enableHome){
827       $result["HOME"]= "<input class='center' type='image' align='middle' src='images/lists/home.png' ".
828                        "title='"._("Go to users department")."' alt='"._("Home")."' name='HOME'>";
829     }else{
830       $result["HOME"]= "<img src='images/lists/home_grey.png' class='center' alt='"._("Home")."'>";
831     }
833     /* Draw reload button, this button is enabled everytime */
834     $result["RELOAD"]= "<input class='center' type='image' src='images/lists/reload.png' align='middle' ".
835                        "title='"._("Reload list")."' name='REFRESH' alt='"._("Submit")."'>";
837     return ($result);
838   }
841   function getAction()
842   {
843     // Do not do anything if this is not our PID
844     if(isset($_REQUEST['PID']) && $_REQUEST['PID'] != $this->pid) {
845       return;
846     }
848     $result= array("targets" => array(), "action" => "");
850     // Filter GET with "act" attributes
851     if (isset($_GET['act'])) {
852       $key= validate($_GET['act']);
853       $target= preg_replace('/^listing_[a-zA-Z_]+_([0-9]+)$/', '$1', $key);
854       if (isset($this->entries[$target]['dn'])) {
855         $result['action']= preg_replace('/^listing_([a-zA-Z_]+)_[0-9]+$/', '$1', $key);
856         $result['targets'][]= $this->entries[$target]['dn'];
857       }
859       // Drop targets if empty
860       if (count($result['targets']) == 0) {
861         unset($result['targets']);
862       }
863       return $result;
864     }
866     // Filter POST with "listing_" attributes
867     foreach ($_POST as $key => $prop) {
869       // Capture selections
870       if (preg_match('/^listing_selected_[0-9]+$/', $key)) {
871         $target= preg_replace('/^listing_selected_([0-9]+)$/', '$1', $key);
872         if (isset($this->entries[$target]['dn'])) {
873           $result['targets'][]= $this->entries[$target]['dn'];
874         }
875         continue;
876       }
878       // Capture action with target - this is a one shot
879       if (preg_match('/^listing_[a-zA-Z_]+_[0-9]+(|_x)$/', $key)) {
880         $target= preg_replace('/^listing_[a-zA-Z_]+_([0-9]+)(|_x)$/', '$1', $key);
881         if (isset($this->entries[$target]['dn'])) {
882           $result['action']= preg_replace('/^listing_([a-zA-Z_]+)_[0-9]+(|_x)$/', '$1', $key);
883           $result['targets']= array($this->entries[$target]['dn']);
884         }
885         break;
886       }
888       // Capture action without target
889       if (preg_match('/^listing_[a-zA-Z_]+(|_x)$/', $key)) {
890         $result['action']= preg_replace('/^listing_([a-zA-Z_]+)(|_x)$/', '$1', $key);
891         continue;
892       }
893     }
895     // Filter POST with "act" attributes -> posted from action menu
896     if (isset($_POST['act']) && $_POST['act'] != '') {
897       $result['action']= validate($_POST['act']);
898     }
900     // Drop targets if empty
901     if (count($result['targets']) == 0) {
902       unset($result['targets']);
903     }
904     return $result;
905   }
908   function renderActionMenu()
909   {
910     // Don't send anything if the menu is not defined
911     if (!isset($this->xmlData['actionmenu']['action'])){
912       return "";
913     }
915     // Load shortcut
916     $actions= &$this->xmlData['actionmenu']['action'];
917     $result= "<input type='hidden' name='act' id='actionmenu' value=''>".
918              "<ul class='level1' id='root'><li><a href='#'>Aktionen&nbsp;<img ".
919              "border=0 class='center' src='images/lists/sort-down.png'></a>";
921     // Build ul/li list
922     $result.= $this->recurseActions($actions);
924     return "<div id='pulldown'>".$result."</li></ul><div>";
925   }
928   function recurseActions($actions)
929   {
930     static $level= 2;
931     $result= "<ul class='level$level'>";
932     $separator= "";
934     foreach ($actions as $action) {
936       // Skip the entry completely if there's no permission to execute it
937       if (!$this->hasActionPermission($action, $this->filter->base)) {
938         continue;
939       }
941       // Fill image if set
942       $img= "";
943       if (isset($action['image'])){
944         $img= "<img border='0' class='center' src='".$action['image']."'>&nbsp;";
945       }
947       if ($action['type'] == "separator"){
948         $separator= " style='border-top:1px solid #AAA' ";
949         continue;
950       }
952       // Dive into subs
953       if ($action['type'] == "sub" && isset($action['action'])) {
954         $level++;
955         if (isset($action['label'])){
956           $result.= "<li$separator><a href='#'>$img"._($action['label'])."&nbsp;<img border='0' src='images/forward-arrow.png'></a>";
957         }
958         $result.= $this->recurseActions($action['action'])."</li>";
959         $level--;
960         $separator= "";
961         continue;
962       }
964       // Render entry elseways
965       if (isset($action['label'])){
966         $result.= "<li$separator><a href='#' onClick='document.getElementById(\"actionmenu\").value= \"".$action['name']."\";mainform.submit();'>$img"._($action['label'])."</a></li>";
967       }
969       // Check for special types
970       switch ($action['type']) {
971         case 'copypaste':
972           $result.= $this->renderCopyPasteMenu($separator);
973           break;
975         case 'snapshot':
976           $result.= $this->renderSnapshotMenu($separator);
977           break;
979         case 'daemon':
980           $result.= $this->renderDaemonMenu($separator);
981           break;
982       }
984       $separator= "";
985     }
987     $result.= "</ul>";
988     return $result;
989   }
992   function hasActionPermission($action, $dn)
993   {
994     $ui= get_userinfo();
996     if (isset($action['acl'])) {
997       $acls= $action['acl'];
998       if (!is_array($acls)) {
999         $acls= array($acls);
1000       }
1002       // Every ACL has to pass
1003       foreach ($acls as $acl) {
1004         $module= $this->module;
1005         $aclList= array();
1007         // Split for category and plugins if needed
1008         // match for "[rw]" style entries
1009         if (preg_match('/^\[([rwcdm]+)\]$/', $acl, $match)){
1010           $aclList= array($match[1]);
1011         }
1013         // match for "users[rw]" style entries
1014         if (preg_match('/^([a-zA-Z0-9]+)\[([rwcdm]+)\]$/', $acl, $match)){
1015           $module= $match[1];
1016           $aclList= array($match[2]);
1017         }
1019         // match for "users/user[rw]" style entries
1020         if (preg_match('/^([a-zA-Z0-9]+\/[a-zA-Z0-9]+)\[([rwcdm]+)\]$/', $acl, $match)){
1021           $module= $match[1];
1022           $aclList= array($match[2]);
1023         }
1025         // match "users/user[userPassword:rw(,...)*]" style entries
1026         if (preg_match('/^([a-zA-Z0-9]+\/[a-zA-Z0-9]+)\[([a-zA-Z0-9]+:[rwcdm]+(,[a-zA-Z0-9]+:[rwcdm]+)*)\]$/', $acl, $match)){
1027           $module= $match[1];
1028           $aclList= split(',', $match[2]);
1029         }
1031         // Walk thru prepared ACL by using $module
1032         foreach($aclList as $sAcl) {
1033           $checkAcl= "";
1035           // Category or detailed permission?
1036           if (strpos('/', $module) === false) {
1037             if (preg_match('/([a-zA-Z0-9]+):([rwcdm]+)/', $sAcl, $m) ) {
1038               $checkAcl= $ui->get_permissions($dn, $module, $m[1]);
1039               $sAcl= $m[2];
1040             } else {
1041               $checkAcl= $ui->get_permissions($dn, $module, '0');
1042             }
1043           } else {
1044             $checkAcl= $ui->get_category_permissions($dn, $module);
1045           }
1047           // Split up remaining part of the acl and check if it we're
1048           // allowed to do something...
1049           $parts= str_split($sAcl);
1050           foreach ($parts as $part) {
1051             if (strpos($checkAcl, $part) === false){
1052               return false;
1053             }
1054           }
1056         }
1057       }
1058     }
1060     return true;
1061   }
1064   function refreshBasesList()
1065   {
1066     global $config;
1067     $ui= get_userinfo();
1069     // Do some array munching to get it user friendly
1070     $ids= $config->idepartments;
1071     $d= $ui->get_module_departments($this->module);
1072     $k_ids= array_keys($ids);
1073     $deps= array_intersect($d,$k_ids);
1075     // Fill internal bases list
1076     $this->bases= array();
1077     foreach($k_ids as $department){
1078       $this->bases[$department] = $ids[$department];
1079     }
1080   }
1083   function getDepartments()
1084   {
1085     $departments= array();
1086     $ui= get_userinfo();
1088     // Get list of supported department types
1089     $types = departmentManagement::get_support_departments();
1091     // Load departments allowed by ACL
1092     $validDepartments = $ui->get_module_departments($this->module);
1094     // Build filter and look in the LDAP for possible sub departments
1095     // of current base
1096     $filter= "(&(objectClass=gosaDepartment)(|";
1097     $attrs= array("description", "objectClass");
1098     foreach($types as $name => $data){
1099       $filter.= "(objectClass=".$data['OC'].")";
1100       $attrs[]= $data['ATTR'];
1101     }
1102     $filter.= "))";
1103     $res= get_list($filter, $this->module, $this->base, $attrs, GL_NONE | GL_SIZELIMIT);
1105     // Analyze list of departments
1106     foreach ($res as $department) {
1107       if (!in_array($department['dn'], $validDepartments)) {
1108         continue;
1109       }
1111       // Add the attribute where we use for sorting
1112       $oc= null;
1113       foreach(array_keys($types) as $type) {
1114         if (in_array($type, $department['objectClass'])) {
1115           $oc= $type;
1116           break;
1117         }
1118       }
1119       $department['sort-attribute']= $types[$oc]['ATTR'];
1121       // Move to the result list
1122       $departments[]= $department;
1123     }
1125     return $departments;
1126   }
1129   function renderCopyPasteMenu($separator, $copy= true, $cut= true)
1130   {
1131     // We can only provide information if we've got a copypaste handler
1132     // instance
1133     if(!(isset($this->copyPasteHandler) && is_object($this->copyPasteHandler))){
1134       return "";
1135     }
1137     // Presets
1138     $result= "";
1139     $read= $paste= false;
1140     $ui= get_userinfo();
1142     // Switch flags to on if there's at least one category which allows read/paste
1143     foreach($this->categories as $category){
1144       $read= $read || preg_match('/r/', $ui->get_category_permissions($this->base, $category));
1145       $paste= $paste || $ui->is_pasteable($this->base, $category) == 1;
1146     }
1149     // Draw entries that allow copy and cut
1150     if($read){
1152       // Copy entry
1153       if($copy){
1154         $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>";
1155         $separator= "";
1156       }
1158       // Cut entry
1159       if($cut){
1160         $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>";
1161         $separator= "";
1162       }
1163     }
1165     // Draw entries that allow pasting entries
1166     if($paste){
1167       if($this->copyPasteHandler->entries_queued()){
1168         $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>";
1169       }else{
1170         $result.= "<li$separator><a href='#'><img src='images/lists/paste-grey.png' alt='' border='0' class='center'>&nbsp;"._("Paste")."</a></li>";
1171       }
1172     }
1173     
1174     return($result);
1175   }
1178   function renderCopyPasteActions($row, $dn, $category, $class, $copy= true, $cut= true)
1179   {
1180     // We can only provide information if we've got a copypaste handler
1181     // instance
1182     if(!(isset($this->copyPasteHandler) && is_object($this->copyPasteHandler))){
1183       return "";
1184     }
1186     // Presets
1187     $ui = get_userinfo();
1188     $result = "";
1190     // Render cut entries
1191     if($cut){
1192       if($ui->is_cutable($dn, $category, $class)){
1193         $result .= "<input class='center' type='image'
1194           src='images/lists/cut.png' alt='"._("Cut")."' name='listing_cut_$row' title='"._("Cut this entry")."' style='padding:1px'>";
1195       }else{
1196         $result.="<img src='images/empty.png' alt=' ' class='center' style='padding:1px'>";
1197       }
1198     }
1200     // Render copy entries
1201     if($copy){
1202       if($ui->is_copyable($dn, $category, $class)){
1203         $result.= "<input class='center' type='image'
1204           src='images/lists/copy.png' alt='"._("Copy")."' name='listing_copy_$row' title='"._("Copy this entry")."' style='padding:1px'>";
1205       }else{
1206         $result.="<img src='images/empty.png' alt=' ' class='center' style='padding:1px'>";
1207       }
1208     }
1210     return($result);
1211   }
1214   function renderSnapshotMenu($separator)
1215   {
1216     // We can only provide information if we've got a snapshot handler
1217     // instance
1218     if(!(isset($this->snapshotHandler) && is_object($this->snapshotHandler))){
1219       return "";
1220     }
1222     // Presets
1223     $result = "";
1224     $ui = get_userinfo();
1226     if($this->snapshotHandler->enabled() && $ui->allow_snapshot_restore($this->base, $this->module)){
1228       // Check if there is something to restore
1229       $restore= false;
1230       foreach($this->snapshotHandler->getSnapshotBases() as $base){
1231         $restore= $restore || count($this->snapshotHandler->getDeletedSnapshots($base)) > 0;
1232       }
1234       // Draw icons according to the restore flag
1235       if($restore){
1236         $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>";
1237       }else{
1238         $result.= "<li$separator><a href='#'><img src='images/lists/restore_grey.png' alt='' border='0' class='center'>&nbsp;"._("Restore snapshots")."</a></li>";
1239       }
1240     }
1242     return($result);
1243   }
1246   function renderSnapshotActions($row, $dn, $category, $class, $copy= true, $cut= true)
1247   {
1248     // We can only provide information if we've got a snapshot handler
1249     // instance
1250     if(!(isset($this->snapshotHandler) && is_object($this->snapshotHandler))){
1251       return "";
1252     }
1254     // Presets
1255     $result= "";
1256     $ui = get_userinfo();
1258     // Only act if enabled here
1259     if($this->snapshotHandler->enabled()){
1261       // Draw restore button
1262       if ($ui->allow_snapshot_restore($dn, $category)){
1264         // Do we have snapshots for this dn?
1265         if($this->snapshotHandler->hasSnapshots($dn)){
1266           $result.= "<input class='center' type='image' src='images/lists/restore.png' ".
1267                      "alt='"._("Restore snapshot")."' name='listing_restore_$row' title='".
1268                      _("Restore snapshot")."' style='padding:1px'>";
1269         } else {
1270           $result.= "<img src='images/lists/restore_grey.png' alt=' ' class='center' style='padding:1px'>";
1271         }
1272       }
1274       // Draw snapshot button
1275       if($ui->allow_snapshot_create($dn, $category)){
1276           $result.= "<input class='center' type='image' src='images/snapshot.png' ".
1277                      "alt='"._("Create snapshot")."' name='listing_snapshot_$row' title='".
1278                      _("Create a new snapshot from this object")."' style='padding:1px'>";
1279       }else{
1280           $result.= "<img src='images/empty.png' alt=' ' class='center' style='padding:1px'>";
1281       }
1282     }
1284     return($result);
1285   }
1288   function renderDaemonMenu($separator)
1289   {
1290     $result= "";
1292     // If there is a daemon registered, draw the menu entries
1293     if(class_available("DaemonEvent")){
1294       $events= DaemonEvent::get_event_types_by_category($this->categories);
1295       if(isset($events['BY_CLASS']) && count($events['BY_CLASS'])){
1296         foreach($events['BY_CLASS'] as $name => $event){
1297           $result.= "<li$separator><a href='#' onClick='document.getElementById(\"actionmenu\").value=\"$name\";mainform.submit();'>".$event['MenuImage']."&nbsp;".$event['s_Menu_Name']."</a></li>";
1298           $separator= "";
1299         }
1300       }
1301     }
1303     return $result;
1304   }
1308 ?>