Code

Added simple workaround for sorting of foreign values
[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 parseLayout($layout)
475   {
476     $result= array();
477     $layout= preg_replace("/^\|/", "", $layout);
478     $layout= preg_replace("/\|$/", "", $layout);
479     $cols= split("\|", $layout);
480     foreach ($cols as $index => $config) {
481       if ($config != "") {
482         $components= split(';', $config);
483         $config= "";
484         foreach ($components as $part) {
485           if (preg_match("/^r$/", $part)) {
486             $config.= "text-align:right;";
487             continue;
488           }
489           if (preg_match("/^l$/", $part)) {
490             $config.= "text-align:left;";
491             continue;
492           }
493           if (preg_match("/^c$/", $part)) {
494             $config.= "text-align:center;";
495             continue;
496           }
497           if (preg_match("/^[0-9]+(|px|%)$/", $part)) {
498             $config.= "width:$part;";
499             continue;
500           }
501         }
503         $result[$index]= " style='$config' ";
504       } else {
505         $result[$index]= null;
506       }
507     }
509     // Save number of columns for later use
510     $this->numColumns= count($cols);
512     return $result;
513   }
516   function renderCell($data, $config, $row)
517   {
518     // Replace flat attributes in data string
519     for ($i= 0; $i<$config['count']; $i++) {
520       $attr= $config[$i];
521       $value= "";
522       if (is_array($config[$attr])) {
523         $value= $config[$attr][0];
524       } else {
525         $value= $config[$attr];
526       }
527       $data= preg_replace("/%\{$attr\}/", $value, $data);
528     }
530     // Watch out for filters and prepare to execute them
531     $data= $this->processElementFilter($data, $config, $row);
533     // Replace all non replaced %{...} instances because they
534     // are non resolved attributes or filters
535     $data= preg_replace('/%{[^}]+}/', '&nbsp;', $data);
537     return $data;
538   }
541   function renderBase()
542   {
543     $result= "<select name='BASE' onChange='mainform.submit()' size='1'>";
544     $firstDN= null;
545     $found= false;
547     foreach ($this->bases as $key=>$value) {
548       // Keep first entry to fall back eventually
549       if(!$firstDN) {
550         $firstDN= $key;
551       }
553       // Prepare to render entry
554       $selected= "";
555       if ($key == $this->base) {
556         $selected= " selected";
557         $found= true;
558       }
559       $result.= "<option value='".$key."'$selected>".$value."</option>";
560     }
561     $result.= "</select>";
563     // Reset the currently used base to the first DN we found if there
564     // was no match.
565     if(!$found){
566       $this->base = $firstDN;
567     }
569     return $result;
570   }
573   function processElementFilter($data, $config, $row)
574   {
575     preg_match_all("/%\{filter:([^(]+)\((.*)\)\}/", $data, $matches, PREG_SET_ORDER);
577     foreach ($matches as $match) {
578       if (!isset($this->filters[$match[1]])) {
579         continue;
580       }
581       $cl= preg_replace('/::.*$/', '', $this->filters[$match[1]]);
582       $method= preg_replace('/^.*::/', '', $this->filters[$match[1]]);
584       // Prepare params for function call
585       $params= array();
586       preg_match_all('/"[^"]+"|[^,]+/', $match[2], $parts);
587       foreach ($parts[0] as $param) {
589         // Row is replaced by the row number
590         if ($param == "row") {
591           $params[]= $row;
592         }
594         // pid is replaced by the current PID
595         if ($param == "pid") {
596           $params[]= $this->pid;
597         }
599         // Fixie with "" is passed directly
600         if (preg_match('/^".*"$/', $param)){
601           $params[]= preg_replace('/"/', '', $param);
602         }
604         // LDAP variables get replaced by their objects
605         for ($i= 0; $i<$config['count']; $i++) {
606           if ($param == $config[$i]) {
607             $values= $config[$config[$i]];
608             if (is_array($values)){
609               unset($values['count']);
610             }
611             $params[]= $values;
612           }
613         }
615         // Move dn if needed
616         if ($param == "dn") {
617           $params[]= LDAP::fix($config["dn"]);
618         }
619       }
621       // Replace information
622       if ($cl == "listing") {
623         // Non static call - seems to result in errors
624         $data= @preg_replace('/'.preg_quote($match[0]).'/', call_user_func_array(array($this, "$method"), $params), $data);
625       } else {
626         // Static call
627         $data= preg_replace('/'.preg_quote($match[0]).'/', call_user_func_array(array($cl, $method), $params), $data);
628       }
629     }
631     return $data;
632   }
635   function getObjectType($types, $classes)
636   {
637     // Walk thru types and see if there's something matching
638     foreach ($types as $objectType) {
639       $ocs= $objectType['objectClass'];
640       if (!is_array($ocs)){
641         $ocs= array($ocs);
642       }
644       $found= true;
645       foreach ($ocs as $oc){
646         if (preg_match('/^!(.*)$/', $oc, $match)) {
647           $oc= $match[1];
648           if (in_array($oc, $classes)) {
649             $found= false;
650           }
651         } else {
652           if (!in_array($oc, $classes)) {
653             $found= false;
654           }
655         }
656       }
658       if ($found) {
659         return $objectType;
660       }
661     }
663     return null;
664   }
667   function filterObjectType($dn, $classes)
668   {
669     // Walk thru classes and return on first match
670     $result= "&nbsp;";
672     $objectType= $this->getObjectType($this->objectTypes, $classes);
673     if ($objectType) {
674       $result= "<img class='center' title='".LDAP::fix($dn)."' src='".$objectType["image"]."'>";
675       if (!isset($this->objectTypeCount[$objectType['label']])) {
676         $this->objectTypeCount[$objectType['label']]= 0;
677       }
678       $this->objectTypeCount[$objectType['label']]++;
679     }
680     return $result;
681   }
684   function filterActions($dn, $row, $classes)
685   {
686     // Do nothing if there's no menu defined
687     if (!isset($this->xmlData['actiontriggers']['action'])) {
688       return "&nbsp;";
689     }
691     // Go thru all actions
692     $result= "";
693     $actions= $this->xmlData['actiontriggers']['action'];
694     foreach($actions as $action) {
695       // Skip the entry completely if there's no permission to execute it
696       if (!$this->hasActionPermission($action, $dn)) {
697         continue;
698       }
700       // If there's an objectclass definition and we don't have it
701       // add an empty picture here.
702       if (isset($action['objectclass'])){
703         $objectclass= $action['objectclass'];
704         if (preg_match('/^!(.*)$/', $objectclass, $m)){
705           $objectclass= $m[1];
706           if(in_array($objectclass, $classes)) {
707             $result.= "<img src='images/empty.png' alt=' ' class='center' style='padding:1px'>";
708             continue;
709           }
710         } else {
711           if(!in_array($objectclass, $classes)) {
712             $result.= "<img src='images/empty.png' alt=' ' class='center' style='padding:1px'>";
713             continue;
714           }
715         }
716       }
718       // Render normal entries as usual
719       if ($action['type'] == "entry") {
720         $label= $this->processElementFilter($action['label'], $this->entries[$row], $row);
721         $image= $this->processElementFilter($action['image'], $this->entries[$row], $row);
722         $result.="<input class='center' type='image' src='$image' title='$label' ".
723                  "name='listing_".$action['name']."_$row' style='padding:1px'>";
724       }
726       // Handle special types
727       if ($action['type'] == "copypaste" || $action['type'] == "snapshot") {
729         $objectType= $this->getObjectType($this->objectTypes, $this->entries[$row]['objectClass']);
730         $category= $class= null;
731         if ($objectType) {
732           $category= $objectType['category'];
733           $class= $objectType['class'];
734         }
736         if ($action['type'] == "copypaste") {
737           $result.= $this->renderCopyPasteActions($row, $this->entries[$row]['dn'], $category, $class);
738         } else {
739           $result.= $this->renderSnapshotActions($row, $this->entries[$row]['dn'], $category, $class);
740         }
741       }
742     }
744     return $result;
745   }
748   function filterDepartmentLink($row, $dn, $description)
749   {
750     $attr= $this->departments[$row]['sort-attribute'];
751     $name= $this->departments[$row][$attr];
752     if (is_array($name)){
753       $name= $name[0];
754     }
755     $result= sprintf("%s [%s]", $name, $description[0]);
756     return("<a href='?plug=".$_GET['plug']."&amp;PID=$this->pid&amp;act=department_$row' title='$dn'>$result</a>");
757   }
760   function filterLink()
761   {
762     $result= "&nbsp;";
764     $row= func_get_arg(0);
765     $pid= $this->pid;
766     $dn= LDAP::fix(func_get_arg(1));
767     $params= array(func_get_arg(2));
769     // Collect sprintf params
770     for ($i = 3;$i < func_num_args();$i++) {
771       $val= func_get_arg($i);
772       if (is_array($val)){
773         $params[]= $val[0];
774         continue;
775       }
776       $params[]= $val;
777     }
779     $result= "&nbsp;";
780     $trans= call_user_func_array("sprintf", $params);
781     if ($trans != "") {
782       return("<a href='?plug=".$_GET['plug']."&amp;PID=$pid&amp;act=listing_edit_$row' title='$dn'>$trans</a>");
783     }
785     return $result;
786   }
789   function renderNavigation()
790   {
791     $result= array();
792     $enableBack = true;
793     $enableRoot = true;
794     $enableHome = true;
796     $ui = get_userinfo();
798     /* Check if base = first available base */
799     $deps = $ui->get_module_departments($this->module);
801     if(!count($deps) || $deps[0] == $this->filter->base){
802       $enableBack = false;
803       $enableRoot = false;
804     }
806     $listhead ="";
808     /* Check if we are in users home  department */
809     if(!count($deps) ||$this->filter->base == get_base_from_people($ui->dn)){
810       $enableHome = false;
811     }
813     /* Draw root button */
814     if($enableRoot){
815       $result["ROOT"]= "<input class='center' type='image' src='images/lists/root.png' align='middle' ".
816                        "title='"._("Go to root department")."' name='ROOT' alt='"._("Root")."'>";
817     }else{
818       $result["ROOT"]= "<img src='images/lists/root_grey.png' class='center' alt='"._("Root")."'>";
819     }
821     /* Draw back button */
822     if($enableBack){
823       $result["BACK"]= "<input class='center' type='image' align='middle' src='images/lists/back.png' ".
824                        "title='"._("Go up one department")."' alt='"._("Up")."' name='BACK'>";
825     }else{
826       $result["BACK"]= "<img src='images/lists/back_grey.png' class='center' alt='"._("Up")."'>";
827     }
829     /* Draw home button */
830     if($enableHome){
831       $result["HOME"]= "<input class='center' type='image' align='middle' src='images/lists/home.png' ".
832                        "title='"._("Go to users department")."' alt='"._("Home")."' name='HOME'>";
833     }else{
834       $result["HOME"]= "<img src='images/lists/home_grey.png' class='center' alt='"._("Home")."'>";
835     }
837     /* Draw reload button, this button is enabled everytime */
838     $result["RELOAD"]= "<input class='center' type='image' src='images/lists/reload.png' align='middle' ".
839                        "title='"._("Reload list")."' name='REFRESH' alt='"._("Submit")."'>";
841     return ($result);
842   }
845   function getAction()
846   {
847     // Do not do anything if this is not our PID
848     if(isset($_REQUEST['PID']) && $_REQUEST['PID'] != $this->pid) {
849       return;
850     }
852     $result= array("targets" => array(), "action" => "");
854     // Filter GET with "act" attributes
855     if (isset($_GET['act'])) {
856       $key= validate($_GET['act']);
857       $target= preg_replace('/^listing_[a-zA-Z_]+_([0-9]+)$/', '$1', $key);
858       if (isset($this->entries[$target]['dn'])) {
859         $result['action']= preg_replace('/^listing_([a-zA-Z_]+)_[0-9]+$/', '$1', $key);
860         $result['targets'][]= $this->entries[$target]['dn'];
861       }
863       // Drop targets if empty
864       if (count($result['targets']) == 0) {
865         unset($result['targets']);
866       }
867       return $result;
868     }
870     // Filter POST with "listing_" attributes
871     foreach ($_POST as $key => $prop) {
873       // Capture selections
874       if (preg_match('/^listing_selected_[0-9]+$/', $key)) {
875         $target= preg_replace('/^listing_selected_([0-9]+)$/', '$1', $key);
876         if (isset($this->entries[$target]['dn'])) {
877           $result['targets'][]= $this->entries[$target]['dn'];
878         }
879         continue;
880       }
882       // Capture action with target - this is a one shot
883       if (preg_match('/^listing_[a-zA-Z_]+_[0-9]+(|_x)$/', $key)) {
884         $target= preg_replace('/^listing_[a-zA-Z_]+_([0-9]+)(|_x)$/', '$1', $key);
885         if (isset($this->entries[$target]['dn'])) {
886           $result['action']= preg_replace('/^listing_([a-zA-Z_]+)_[0-9]+(|_x)$/', '$1', $key);
887           $result['targets']= array($this->entries[$target]['dn']);
888         }
889         break;
890       }
892       // Capture action without target
893       if (preg_match('/^listing_[a-zA-Z_]+(|_x)$/', $key)) {
894         $result['action']= preg_replace('/^listing_([a-zA-Z_]+)(|_x)$/', '$1', $key);
895         continue;
896       }
897     }
899     // Filter POST with "act" attributes -> posted from action menu
900     if (isset($_POST['act']) && $_POST['act'] != '') {
901       $result['action']= validate($_POST['act']);
902     }
904     // Drop targets if empty
905     if (count($result['targets']) == 0) {
906       unset($result['targets']);
907     }
908     return $result;
909   }
912   function renderActionMenu()
913   {
914     // Don't send anything if the menu is not defined
915     if (!isset($this->xmlData['actionmenu']['action'])){
916       return "";
917     }
919     // Load shortcut
920     $actions= &$this->xmlData['actionmenu']['action'];
921     $result= "<input type='hidden' name='act' id='actionmenu' value=''>".
922              "<ul class='level1' id='root'><li><a href='#'>Aktionen&nbsp;<img ".
923              "border=0 class='center' src='images/lists/sort-down.png'></a>";
925     // Build ul/li list
926     $result.= $this->recurseActions($actions);
928     return "<div id='pulldown'>".$result."</li></ul><div>";
929   }
932   function recurseActions($actions)
933   {
934     static $level= 2;
935     $result= "<ul class='level$level'>";
936     $separator= "";
938     foreach ($actions as $action) {
940       // Skip the entry completely if there's no permission to execute it
941       if (!$this->hasActionPermission($action, $this->filter->base)) {
942         continue;
943       }
945       // Fill image if set
946       $img= "";
947       if (isset($action['image'])){
948         $img= "<img border='0' class='center' src='".$action['image']."'>&nbsp;";
949       }
951       if ($action['type'] == "separator"){
952         $separator= " style='border-top:1px solid #AAA' ";
953         continue;
954       }
956       // Dive into subs
957       if ($action['type'] == "sub" && isset($action['action'])) {
958         $level++;
959         if (isset($action['label'])){
960           $result.= "<li$separator><a href='#'>$img"._($action['label'])."&nbsp;<img border='0' src='images/forward-arrow.png'></a>";
961         }
962         $result.= $this->recurseActions($action['action'])."</li>";
963         $level--;
964         $separator= "";
965         continue;
966       }
968       // Render entry elseways
969       if (isset($action['label'])){
970         $result.= "<li$separator><a href='#' onClick='document.getElementById(\"actionmenu\").value= \"".$action['name']."\";mainform.submit();'>$img"._($action['label'])."</a></li>";
971       }
973       // Check for special types
974       switch ($action['type']) {
975         case 'copypaste':
976           $result.= $this->renderCopyPasteMenu($separator);
977           break;
979         case 'snapshot':
980           $result.= $this->renderSnapshotMenu($separator);
981           break;
983         case 'daemon':
984           $result.= $this->renderDaemonMenu($separator);
985           break;
986       }
988       $separator= "";
989     }
991     $result.= "</ul>";
992     return $result;
993   }
996   function hasActionPermission($action, $dn)
997   {
998     $ui= get_userinfo();
1000     if (isset($action['acl'])) {
1001       $acls= $action['acl'];
1002       if (!is_array($acls)) {
1003         $acls= array($acls);
1004       }
1006       // Every ACL has to pass
1007       foreach ($acls as $acl) {
1008         $module= $this->module;
1009         $aclList= array();
1011         // Split for category and plugins if needed
1012         // match for "[rw]" style entries
1013         if (preg_match('/^\[([rwcdm]+)\]$/', $acl, $match)){
1014           $aclList= array($match[1]);
1015         }
1017         // match for "users[rw]" style entries
1018         if (preg_match('/^([a-zA-Z0-9]+)\[([rwcdm]+)\]$/', $acl, $match)){
1019           $module= $match[1];
1020           $aclList= array($match[2]);
1021         }
1023         // match for "users/user[rw]" style entries
1024         if (preg_match('/^([a-zA-Z0-9]+\/[a-zA-Z0-9]+)\[([rwcdm]+)\]$/', $acl, $match)){
1025           $module= $match[1];
1026           $aclList= array($match[2]);
1027         }
1029         // match "users/user[userPassword:rw(,...)*]" style entries
1030         if (preg_match('/^([a-zA-Z0-9]+\/[a-zA-Z0-9]+)\[([a-zA-Z0-9]+:[rwcdm]+(,[a-zA-Z0-9]+:[rwcdm]+)*)\]$/', $acl, $match)){
1031           $module= $match[1];
1032           $aclList= split(',', $match[2]);
1033         }
1035         // Walk thru prepared ACL by using $module
1036         foreach($aclList as $sAcl) {
1037           $checkAcl= "";
1039           // Category or detailed permission?
1040           if (strpos('/', $module) === false) {
1041             if (preg_match('/([a-zA-Z0-9]+):([rwcdm]+)/', $sAcl, $m) ) {
1042               $checkAcl= $ui->get_permissions($dn, $module, $m[1]);
1043               $sAcl= $m[2];
1044             } else {
1045               $checkAcl= $ui->get_permissions($dn, $module, '0');
1046             }
1047           } else {
1048             $checkAcl= $ui->get_category_permissions($dn, $module);
1049           }
1051           // Split up remaining part of the acl and check if it we're
1052           // allowed to do something...
1053           $parts= str_split($sAcl);
1054           foreach ($parts as $part) {
1055             if (strpos($checkAcl, $part) === false){
1056               return false;
1057             }
1058           }
1060         }
1061       }
1062     }
1064     return true;
1065   }
1068   function refreshBasesList()
1069   {
1070     global $config;
1071     $ui= get_userinfo();
1073     // Do some array munching to get it user friendly
1074     $ids= $config->idepartments;
1075     $d= $ui->get_module_departments($this->module);
1076     $k_ids= array_keys($ids);
1077     $deps= array_intersect($d,$k_ids);
1079     // Fill internal bases list
1080     $this->bases= array();
1081     foreach($k_ids as $department){
1082       $this->bases[$department] = $ids[$department];
1083     }
1084   }
1087   function getDepartments()
1088   {
1089     $departments= array();
1090     $ui= get_userinfo();
1092     // Get list of supported department types
1093     $types = departmentManagement::get_support_departments();
1095     // Load departments allowed by ACL
1096     $validDepartments = $ui->get_module_departments($this->module);
1098     // Build filter and look in the LDAP for possible sub departments
1099     // of current base
1100     $filter= "(&(objectClass=gosaDepartment)(|";
1101     $attrs= array("description", "objectClass");
1102     foreach($types as $name => $data){
1103       $filter.= "(objectClass=".$data['OC'].")";
1104       $attrs[]= $data['ATTR'];
1105     }
1106     $filter.= "))";
1107     $res= get_list($filter, $this->module, $this->base, $attrs, GL_NONE | GL_SIZELIMIT);
1109     // Analyze list of departments
1110     foreach ($res as $department) {
1111       if (!in_array($department['dn'], $validDepartments)) {
1112         continue;
1113       }
1115       // Add the attribute where we use for sorting
1116       $oc= null;
1117       foreach(array_keys($types) as $type) {
1118         if (in_array($type, $department['objectClass'])) {
1119           $oc= $type;
1120           break;
1121         }
1122       }
1123       $department['sort-attribute']= $types[$oc]['ATTR'];
1125       // Move to the result list
1126       $departments[]= $department;
1127     }
1129     return $departments;
1130   }
1133   function renderCopyPasteMenu($separator, $copy= true, $cut= true)
1134   {
1135     // We can only provide information if we've got a copypaste handler
1136     // instance
1137     if(!(isset($this->copyPasteHandler) && is_object($this->copyPasteHandler))){
1138       return "";
1139     }
1141     // Presets
1142     $result= "";
1143     $read= $paste= false;
1144     $ui= get_userinfo();
1146     // Switch flags to on if there's at least one category which allows read/paste
1147     foreach($this->categories as $category){
1148       $read= $read || preg_match('/r/', $ui->get_category_permissions($this->base, $category));
1149       $paste= $paste || $ui->is_pasteable($this->base, $category) == 1;
1150     }
1153     // Draw entries that allow copy and cut
1154     if($read){
1156       // Copy entry
1157       if($copy){
1158         $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>";
1159         $separator= "";
1160       }
1162       // Cut entry
1163       if($cut){
1164         $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>";
1165         $separator= "";
1166       }
1167     }
1169     // Draw entries that allow pasting entries
1170     if($paste){
1171       if($this->copyPasteHandler->entries_queued()){
1172         $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>";
1173       }else{
1174         $result.= "<li$separator><a href='#'><img src='images/lists/paste-grey.png' alt='' border='0' class='center'>&nbsp;"._("Paste")."</a></li>";
1175       }
1176     }
1177     
1178     return($result);
1179   }
1182   function renderCopyPasteActions($row, $dn, $category, $class, $copy= true, $cut= true)
1183   {
1184     // We can only provide information if we've got a copypaste handler
1185     // instance
1186     if(!(isset($this->copyPasteHandler) && is_object($this->copyPasteHandler))){
1187       return "";
1188     }
1190     // Presets
1191     $ui = get_userinfo();
1192     $result = "";
1194     // Render cut entries
1195     if($cut){
1196       if($ui->is_cutable($dn, $category, $class)){
1197         $result .= "<input class='center' type='image'
1198           src='images/lists/cut.png' alt='"._("Cut")."' name='listing_cut_$row' title='"._("Cut this entry")."' style='padding:1px'>";
1199       }else{
1200         $result.="<img src='images/empty.png' alt=' ' class='center' style='padding:1px'>";
1201       }
1202     }
1204     // Render copy entries
1205     if($copy){
1206       if($ui->is_copyable($dn, $category, $class)){
1207         $result.= "<input class='center' type='image'
1208           src='images/lists/copy.png' alt='"._("Copy")."' name='listing_copy_$row' title='"._("Copy this entry")."' style='padding:1px'>";
1209       }else{
1210         $result.="<img src='images/empty.png' alt=' ' class='center' style='padding:1px'>";
1211       }
1212     }
1214     return($result);
1215   }
1218   function renderSnapshotMenu($separator)
1219   {
1220     // We can only provide information if we've got a snapshot handler
1221     // instance
1222     if(!(isset($this->snapshotHandler) && is_object($this->snapshotHandler))){
1223       return "";
1224     }
1226     // Presets
1227     $result = "";
1228     $ui = get_userinfo();
1230     if($this->snapshotHandler->enabled() && $ui->allow_snapshot_restore($this->base, $this->module)){
1232       // Check if there is something to restore
1233       $restore= false;
1234       foreach($this->snapshotHandler->getSnapshotBases() as $base){
1235         $restore= $restore || count($this->snapshotHandler->getDeletedSnapshots($base)) > 0;
1236       }
1238       // Draw icons according to the restore flag
1239       if($restore){
1240         $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>";
1241       }else{
1242         $result.= "<li$separator><a href='#'><img src='images/lists/restore_grey.png' alt='' border='0' class='center'>&nbsp;"._("Restore snapshots")."</a></li>";
1243       }
1244     }
1246     return($result);
1247   }
1250   function renderSnapshotActions($row, $dn, $category, $class, $copy= true, $cut= true)
1251   {
1252     // We can only provide information if we've got a snapshot handler
1253     // instance
1254     if(!(isset($this->snapshotHandler) && is_object($this->snapshotHandler))){
1255       return "";
1256     }
1258     // Presets
1259     $result= "";
1260     $ui = get_userinfo();
1262     // Only act if enabled here
1263     if($this->snapshotHandler->enabled()){
1265       // Draw restore button
1266       if ($ui->allow_snapshot_restore($dn, $category)){
1268         // Do we have snapshots for this dn?
1269         if($this->snapshotHandler->hasSnapshots($dn)){
1270           $result.= "<input class='center' type='image' src='images/lists/restore.png' ".
1271                      "alt='"._("Restore snapshot")."' name='listing_restore_$row' title='".
1272                      _("Restore snapshot")."' style='padding:1px'>";
1273         } else {
1274           $result.= "<img src='images/lists/restore_grey.png' alt=' ' class='center' style='padding:1px'>";
1275         }
1276       }
1278       // Draw snapshot button
1279       if($ui->allow_snapshot_create($dn, $category)){
1280           $result.= "<input class='center' type='image' src='images/snapshot.png' ".
1281                      "alt='"._("Create snapshot")."' name='listing_snapshot_$row' title='".
1282                      _("Create a new snapshot from this object")."' style='padding:1px'>";
1283       }else{
1284           $result.= "<img src='images/empty.png' alt=' ' class='center' style='padding:1px'>";
1285       }
1286     }
1288     return($result);
1289   }
1292   function renderDaemonMenu($separator)
1293   {
1294     $result= "";
1296     // If there is a daemon registered, draw the menu entries
1297     if(class_available("DaemonEvent")){
1298       $events= DaemonEvent::get_event_types_by_category($this->categories);
1299       if(isset($events['BY_CLASS']) && count($events['BY_CLASS'])){
1300         foreach($events['BY_CLASS'] as $name => $event){
1301           $result.= "<li$separator><a href='#' onClick='document.getElementById(\"actionmenu\").value=\"$name\";mainform.submit();'>".$event['MenuImage']."&nbsp;".$event['s_Menu_Name']."</a></li>";
1302           $separator= "";
1303         }
1304       }
1305     }
1307     return $result;
1308   }
1312 ?>