Code

Added timeout to GOsa::log mysql connections.
[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'>";
231     $result.= "<div class='contentboxb' id='listing_container' style='border-top:1px solid #B0B0B0;'>";
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'>";
234     $this->numColumns= count($this->colprops) + ($this->multiSelect?1:0);
236     // Build list header
237     $result.= "<tr>";
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>";
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>";
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'>";
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     $entryIterator= new listingSortIterator($this->entries, $this->sortDirection[$this->sortColumn], $this->sortAttribute, $this->sortType);
297     foreach ($entryIterator as $row => $entry){
298       $result.="<tr class='rowxp".($alt&1)."'>";
300       // Render multi select if needed
301       if ($this->multiSelect) {
302         $result.="<td style='text-align:center;width:20px;' class='list0'><input type='checkbox' id='listing_selected_$row' name='listing_selected_$row'></td>";
303       }
305       foreach ($this->xmlData['table']['column'] as $index => $config) {
306         $result.="<td ".$this->colprops[$index]." class='list0'>".$this->renderCell($config['value'], $entry, $row)."</td>";
307       }
308       $result.="</tr>";
310       $alt++;
311     }
313     // Need to fill the list if it's not full (nobody knows why this is 22 ;-))
314     $emptyListStyle= (count($this->entries) + $deps == 0)?"border:0;":"";
315     if ((count($this->entries) + $deps) < 22) {
316       $result.= "<tr>";
317       for ($i= 0; $i<$this->numColumns; $i++) {
318         if ($i == 0) {
319           $result.= "<td class='list1nohighlight' style='$emptyListStyle height:100%;'>&nbsp;</td>";
320           continue;
321         }
322         if ($i != $this->numColumns-1) {
323           $result.= "<td class='list1nohighlight' style='$emptyListStyle'>&nbsp;</td>";
324         } else {
325           $result.= "<td class='list1nohighlight' style='border-right:1px solid #AAA;$emptyListStyle'>&nbsp;</td>";
326         }
327       }
328       $result.= "</tr>";
329     }
331     $result.= "</table></div></td></tr>";
333     // Add the footer if requested
334     if ($this->showFooter) {
335       $result.= "<tr><td class='scrollhead'><table summary='' style='width:100%' cellspacing='0' id='t_scrollfoot'><tr><td class='listfooter' style='border-bottom:0px;'>";
337       foreach ($this->objectTypes as $objectType) {
338         if (isset($this->objectTypeCount[$objectType['label']])) {
339           $label= _($objectType['label']);
340           $result.= "<img class='center' src='".$objectType['image']."' title='$label' alt='$label'>&nbsp;".$this->objectTypeCount[$objectType['label']]."&nbsp;&nbsp;&nbsp;&nbsp;";
341         }
342       }
344       $result.= "<td class='listfooter' style='width:13px;border-right:0px;'>&nbsp;</td></table></td></tr>";
345     }
347     $result.= "</table></div>";
349     $smarty= get_smarty();
350     $smarty->assign("FILTER", $this->filter->render());
351     $smarty->assign("SIZELIMIT", print_sizelimit_warning());
352     $smarty->assign("LIST", $result);
354     // Assign navigation elements
355     $nav= $this->renderNavigation();
356     foreach ($nav as $key => $html) {
357       $smarty->assign($key, $html);
358     }
360     // Assign action menu / base
361     $smarty->assign("ACTIONS", $this->renderActionMenu());
362     $smarty->assign("BASE", $this->renderBase());
364     // Assign separator
365     $smarty->assign("SEPARATOR", "<img src='images/lists/seperator.png' alt='-' align='middle' height='16' width='1' class='center'>");
367     // Assign summary
368     $smarty->assign("HEADLINE", $this->headline);
370     return ($smarty->fetch(get_template_path($this->xmlData['definition']['template'], true)));
371   }
374   function update()
375   {
376     global $config;
377     $ui= get_userinfo();
379     // Reset object counter
380     $this->objectTypeCount= array();
382     // Do not do anything if this is not our PID
383     if(isset($_REQUEST['PID']) && $_REQUEST['PID'] != $this->pid) {
384       return;
385     }
387     // Save base
388     if (isset($_POST['BASE']) && $this->baseMode == true) {
389       $base= validate($_POST['BASE']);
390       if (isset($this->bases[$base])) {
391         $this->base= $base;
392       }
393     }
395     // Override the base if we got a message from the browser navigation
396     if ($this->departmentBrowser && isset($_GET['act'])) {
397       if (preg_match('/^department_([0-9]+)$/', validate($_GET['act']), $match)){
398         if (isset($this->departments[$match[1]])){
399           $this->base= $this->departments[$match[1]]['dn'];
400         }
401       }
402     }
404     // Filter GET with "act" attributes
405     if (isset($_GET['act'])) {
406       $key= validate($_GET['act']);
407       if (preg_match('/^SORT_([0-9]+)$/', $key, $match)) {
408         // Switch to new column or invert search order?
409         $column= $match[1];
410         if ($this->sortColumn != $column) {
411           $this->sortColumn= $column;
412         } else {
413           $this->sortDirection[$column]= !$this->sortDirection[$column];
414         }
416         // Allow header to update itself according to the new sort settings
417         $this->renderHeader();
418       }
419     }
421     // Override base if we got signals from the navigation elements
422     $action= "";
423     foreach ($_POST as $key => $value) {
424       if (preg_match('/^(ROOT|BACK|HOME)_x$/', $key, $match)) {
425         $action= $match[1];
426         break;
427       }
428     }
430     // Navigation handling
431     if ($action == 'ROOT') {
432       $deps= $ui->get_module_departments($this->module);
433       $this->base= $deps[0];
434     }
435     if ($action == 'BACK') {
436       $deps= $ui->get_module_departments($this->module);
437       $base= preg_replace("/^[^,]+,/", "", $this->base);
438       if(in_array_ics($base, $deps)){
439         $this->base= $base;
440       }
441     }
442     if ($action == 'HOME') {
443       $ui= get_userinfo();
444       $this->base= get_base_from_people($ui->dn);
445     }
447     // Reload departments
448     if ($this->departmentBrowser){
449       $this->departments= $this->getDepartments();
450     }
452     // Update filter and refresh entries
453     $this->filter->setBase($this->base);
454     $this->entries= $this->filter->query();
455   }
458   function parseLayout($layout)
459   {
460     $result= array();
461     $layout= preg_replace("/^\|/", "", $layout);
462     $layout= preg_replace("/\|$/", "", $layout);
463     $cols= split("\|", $layout);
464     foreach ($cols as $index => $config) {
465       if ($config != "") {
466         $components= split(';', $config);
467         $config= "";
468         foreach ($components as $part) {
469           if (preg_match("/^r$/", $part)) {
470             $config.= "text-align:right;";
471             continue;
472           }
473           if (preg_match("/^l$/", $part)) {
474             $config.= "text-align:left;";
475             continue;
476           }
477           if (preg_match("/^c$/", $part)) {
478             $config.= "text-align:center;";
479             continue;
480           }
481           if (preg_match("/^[0-9]+(|px|%)$/", $part)) {
482             $config.= "width:$part;";
483             continue;
484           }
485         }
487         $result[$index]= " style='$config' ";
488       } else {
489         $result[$index]= null;
490       }
491     }
493     // Save number of columns for later use
494     $this->numColumns= count($cols);
496     return $result;
497   }
500   function renderCell($data, $config, $row)
501   {
502     // Replace flat attributes in data string
503     for ($i= 0; $i<$config['count']; $i++) {
504       $attr= $config[$i];
505       $value= "";
506       if (is_array($config[$attr])) {
507         $value= $config[$attr][0];
508       } else {
509         $value= $config[$attr];
510       }
511       $data= preg_replace("/%\{$attr\}/", $value, $data);
512     }
514     // Watch out for filters and prepare to execute them
515     $data= $this->processElementFilter($data, $config, $row);
517     // Replace all non replaced %{...} instances because they
518     // are non resolved attributes or filters
519     $data= preg_replace('/%{[^}]+}/', '&nbsp;', $data);
521     return $data;
522   }
525   function renderBase()
526   {
527     $result= "<select name='BASE' onChange='mainform.submit()' size='1'>";
528     $firstDN= null;
529     $found= false;
531     foreach ($this->bases as $key=>$value) {
532       // Keep first entry to fall back eventually
533       if(!$firstDN) {
534         $firstDN= $key;
535       }
537       // Prepare to render entry
538       $selected= "";
539       if ($key == $this->base) {
540         $selected= " selected";
541         $found= true;
542       }
543       $result.= "<option value='".$key."'$selected>".$value."</option>";
544     }
545     $result.= "</select>";
547     // Reset the currently used base to the first DN we found if there
548     // was no match.
549     if(!$found){
550       $this->base = $firstDN;
551     }
553     return $result;
554   }
557   function processElementFilter($data, $config, $row)
558   {
559     preg_match_all("/%\{filter:([^(]+)\((.*)\)\}/", $data, $matches, PREG_SET_ORDER);
561     foreach ($matches as $match) {
562       if (!isset($this->filters[$match[1]])) {
563         continue;
564       }
565       $cl= preg_replace('/::.*$/', '', $this->filters[$match[1]]);
566       $method= preg_replace('/^.*::/', '', $this->filters[$match[1]]);
568       // Prepare params for function call
569       $params= array();
570       preg_match_all('/"[^"]+"|[^,]+/', $match[2], $parts);
571       foreach ($parts[0] as $param) {
573         // Row is replaced by the row number
574         if ($param == "row") {
575           $params[]= $row;
576         }
578         // pid is replaced by the current PID
579         if ($param == "pid") {
580           $params[]= $this->pid;
581         }
583         // Fixie with "" is passed directly
584         if (preg_match('/^".*"$/', $param)){
585           $params[]= preg_replace('/"/', '', $param);
586         }
588         // LDAP variables get replaced by their objects
589         for ($i= 0; $i<$config['count']; $i++) {
590           if ($param == $config[$i]) {
591             $values= $config[$config[$i]];
592             if (is_array($values)){
593               unset($values['count']);
594             }
595             $params[]= $values;
596           }
597         }
599         // Move dn if needed
600         if ($param == "dn") {
601           $params[]= LDAP::fix($config["dn"]);
602         }
603       }
605       // Replace information
606       if ($cl == "listing") {
607         // Non static call - seems to result in errors
608         $data= @preg_replace('/'.preg_quote($match[0]).'/', call_user_func_array(array($this, "$method"), $params), $data);
609       } else {
610         // Static call
611         $data= preg_replace('/'.preg_quote($match[0]).'/', call_user_func_array(array($cl, $method), $params), $data);
612       }
613     }
615     return $data;
616   }
619   function getObjectType($types, $classes)
620   {
621     // Walk thru types and see if there's something matching
622     foreach ($types as $objectType) {
623       $ocs= $objectType['objectClass'];
624       if (!is_array($ocs)){
625         $ocs= array($ocs);
626       }
628       $found= true;
629       foreach ($ocs as $oc){
630         if (preg_match('/^!(.*)$/', $oc, $match)) {
631           $oc= $match[1];
632           if (in_array($oc, $classes)) {
633             $found= false;
634           }
635         } else {
636           if (!in_array($oc, $classes)) {
637             $found= false;
638           }
639         }
640       }
642       if ($found) {
643         return $objectType;
644       }
645     }
647     return null;
648   }
651   function filterObjectType($dn, $classes)
652   {
653     // Walk thru classes and return on first match
654     $result= "&nbsp;";
656     $objectType= $this->getObjectType($this->objectTypes, $classes);
657     if ($objectType) {
658       $result= "<img class='center' title='".LDAP::fix($dn)."' src='".$objectType["image"]."'>";
659       if (!isset($this->objectTypeCount[$objectType['label']])) {
660         $this->objectTypeCount[$objectType['label']]= 0;
661       }
662       $this->objectTypeCount[$objectType['label']]++;
663     }
664     return $result;
665   }
668   function filterActions($dn, $row, $classes)
669   {
670     // Do nothing if there's no menu defined
671     if (!isset($this->xmlData['actiontriggers']['action'])) {
672       return "&nbsp;";
673     }
675     // Go thru all actions
676     $result= "";
677     $actions= $this->xmlData['actiontriggers']['action'];
678     foreach($actions as $action) {
679       // Skip the entry completely if there's no permission to execute it
680       if (!$this->hasActionPermission($action, $dn)) {
681         continue;
682       }
684       // If there's an objectclass definition and we don't have it
685       // add an empty picture here.
686       if (isset($action['objectclass'])){
687         $objectclass= $action['objectclass'];
688         if (preg_match('/^!(.*)$/', $objectclass, $m)){
689           $objectclass= $m[1];
690           if(in_array($objectclass, $classes)) {
691             $result.= "<img src='images/empty.png' alt=' ' class='center' style='padding:1px'>";
692             continue;
693           }
694         } else {
695           if(!in_array($objectclass, $classes)) {
696             $result.= "<img src='images/empty.png' alt=' ' class='center' style='padding:1px'>";
697             continue;
698           }
699         }
700       }
702       // Render normal entries as usual
703       if ($action['type'] == "entry") {
704         $label= $this->processElementFilter($action['label'], $this->entries[$row], $row);
705         $image= $this->processElementFilter($action['image'], $this->entries[$row], $row);
706         $result.="<input class='center' type='image' src='$image' title='$label' ".
707                  "name='listing_".$action['name']."_$row' style='padding:1px'>";
708       }
710       // Handle special types
711       if ($action['type'] == "copypaste" || $action['type'] == "snapshot") {
713         $objectType= $this->getObjectType($this->objectTypes, $this->entries[$row]['objectClass']);
714         $category= $class= null;
715         if ($objectType) {
716           $category= $objectType['category'];
717           $class= $objectType['class'];
718         }
720         if ($action['type'] == "copypaste") {
721           $result.= $this->renderCopyPasteActions($row, $this->entries[$row]['dn'], $category, $class);
722         } else {
723           $result.= $this->renderSnapshotActions($row, $this->entries[$row]['dn'], $category, $class);
724         }
725       }
726     }
728     return $result;
729   }
732   function filterDepartmentLink($row, $dn, $description)
733   {
734     $attr= $this->departments[$row]['sort-attribute'];
735     $name= $this->departments[$row][$attr];
736     if (is_array($name)){
737       $name= $name[0];
738     }
739     $result= sprintf("%s [%s]", $name, $description[0]);
740     return("<a href='?plug=".$_GET['plug']."&amp;PID=$this->pid&amp;act=department_$row' title='$dn'>$result</a>");
741   }
744   function filterLink()
745   {
746     $result= "&nbsp;";
748     $row= func_get_arg(0);
749     $pid= $this->pid;
750     $dn= LDAP::fix(func_get_arg(1));
751     $params= array(func_get_arg(2));
753     // Collect sprintf params
754     for ($i = 3;$i < func_num_args();$i++) {
755       $val= func_get_arg($i);
756       if (is_array($val)){
757         $params[]= $val[0];
758         continue;
759       }
760       $params[]= $val;
761     }
763     $result= "&nbsp;";
764     $trans= call_user_func_array("sprintf", $params);
765     if ($trans != "") {
766       return("<a href='?plug=".$_GET['plug']."&amp;PID=$pid&amp;act=listing_edit_$row' title='$dn'>$trans</a>");
767     }
769     return $result;
770   }
773   function renderNavigation()
774   {
775     $result= array();
776     $enableBack = true;
777     $enableRoot = true;
778     $enableHome = true;
780     $ui = get_userinfo();
782     /* Check if base = first available base */
783     $deps = $ui->get_module_departments($this->module);
785     if(!count($deps) || $deps[0] == $this->filter->base){
786       $enableBack = false;
787       $enableRoot = false;
788     }
790     $listhead ="";
792     /* Check if we are in users home  department */
793     if(!count($deps) ||$this->filter->base == get_base_from_people($ui->dn)){
794       $enableHome = false;
795     }
797     /* Draw root button */
798     if($enableRoot){
799       $result["ROOT"]= "<input class='center' type='image' src='images/lists/root.png' align='middle' ".
800                        "title='"._("Go to root department")."' name='ROOT' alt='"._("Root")."'>";
801     }else{
802       $result["ROOT"]= "<img src='images/lists/root_grey.png' class='center' alt='"._("Root")."'>";
803     }
805     /* Draw back button */
806     if($enableBack){
807       $result["BACK"]= "<input class='center' type='image' align='middle' src='images/lists/back.png' ".
808                        "title='"._("Go up one department")."' alt='"._("Up")."' name='BACK'>";
809     }else{
810       $result["BACK"]= "<img src='images/lists/back_grey.png' class='center' alt='"._("Up")."'>";
811     }
813     /* Draw home button */
814     if($enableHome){
815       $result["HOME"]= "<input class='center' type='image' align='middle' src='images/lists/home.png' ".
816                        "title='"._("Go to users department")."' alt='"._("Home")."' name='HOME'>";
817     }else{
818       $result["HOME"]= "<img src='images/lists/home_grey.png' class='center' alt='"._("Home")."'>";
819     }
821     /* Draw reload button, this button is enabled everytime */
822     $result["RELOAD"]= "<input class='center' type='image' src='images/lists/reload.png' align='middle' ".
823                        "title='"._("Reload list")."' name='REFRESH' alt='"._("Submit")."'>";
825     return ($result);
826   }
829   function getAction()
830   {
831     // Do not do anything if this is not our PID
832     if(isset($_REQUEST['PID']) && $_REQUEST['PID'] != $this->pid) {
833       return;
834     }
836     $result= array("targets" => array(), "action" => "");
838     // Filter GET with "act" attributes
839     if (isset($_GET['act'])) {
840       $key= validate($_GET['act']);
841       $target= preg_replace('/^listing_[a-zA-Z_]+_([0-9]+)$/', '$1', $key);
842       if (isset($this->entries[$target]['dn'])) {
843         $result['action']= preg_replace('/^listing_([a-zA-Z_]+)_[0-9]+$/', '$1', $key);
844         $result['targets'][]= $this->entries[$target]['dn'];
845       }
847       // Drop targets if empty
848       if (count($result['targets']) == 0) {
849         unset($result['targets']);
850       }
851       return $result;
852     }
854     // Filter POST with "listing_" attributes
855     foreach ($_POST as $key => $prop) {
857       // Capture selections
858       if (preg_match('/^listing_selected_[0-9]+$/', $key)) {
859         $target= preg_replace('/^listing_selected_([0-9]+)$/', '$1', $key);
860         if (isset($this->entries[$target]['dn'])) {
861           $result['targets'][]= $this->entries[$target]['dn'];
862         }
863         continue;
864       }
866       // Capture action with target - this is a one shot
867       if (preg_match('/^listing_[a-zA-Z_]+_[0-9]+(|_x)$/', $key)) {
868         $target= preg_replace('/^listing_[a-zA-Z_]+_([0-9]+)(|_x)$/', '$1', $key);
869         if (isset($this->entries[$target]['dn'])) {
870           $result['action']= preg_replace('/^listing_([a-zA-Z_]+)_[0-9]+(|_x)$/', '$1', $key);
871           $result['targets']= array($this->entries[$target]['dn']);
872         }
873         break;
874       }
876       // Capture action without target
877       if (preg_match('/^listing_[a-zA-Z_]+(|_x)$/', $key)) {
878         $result['action']= preg_replace('/^listing_([a-zA-Z_]+)(|_x)$/', '$1', $key);
879         continue;
880       }
881     }
883     // Filter POST with "act" attributes -> posted from action menu
884     if (isset($_POST['act']) && $_POST['act'] != '') {
885       $result['action']= validate($_POST['act']);
886     }
888     // Drop targets if empty
889     if (count($result['targets']) == 0) {
890       unset($result['targets']);
891     }
892     return $result;
893   }
896   function renderActionMenu()
897   {
898     // Don't send anything if the menu is not defined
899     if (!isset($this->xmlData['actionmenu']['action'])){
900       return "";
901     }
903     // Load shortcut
904     $actions= &$this->xmlData['actionmenu']['action'];
905     $result= "<input type='hidden' name='act' id='actionmenu' value=''>".
906              "<ul class='level1' id='root'><li><a href='#'>Aktionen&nbsp;<img ".
907              "border=0 class='center' src='images/lists/sort-down.png'></a>";
909     // Build ul/li list
910     $result.= $this->recurseActions($actions);
912     return "<div id='pulldown'>".$result."</li></ul><div>";
913   }
916   function recurseActions($actions)
917   {
918     static $level= 2;
919     $result= "<ul class='level$level'>";
920     $separator= "";
922     foreach ($actions as $action) {
924       // Skip the entry completely if there's no permission to execute it
925       if (!$this->hasActionPermission($action, $this->filter->base)) {
926         continue;
927       }
929       // Fill image if set
930       $img= "";
931       if (isset($action['image'])){
932         $img= "<img border='0' class='center' src='".$action['image']."'>&nbsp;";
933       }
935       if ($action['type'] == "separator"){
936         $separator= " style='border-top:1px solid #AAA' ";
937         continue;
938       }
940       // Dive into subs
941       if ($action['type'] == "sub" && isset($action['action'])) {
942         $level++;
943         if (isset($action['label'])){
944           $result.= "<li$separator><a href='#'>$img"._($action['label'])."&nbsp;<img border='0' src='images/forward-arrow.png'></a>";
945         }
946         $result.= $this->recurseActions($action['action'])."</li>";
947         $level--;
948         $separator= "";
949         continue;
950       }
952       // Render entry elseways
953       if (isset($action['label'])){
954         $result.= "<li$separator><a href='#' onClick='document.getElementById(\"actionmenu\").value= \"".$action['name']."\";mainform.submit();'>$img"._($action['label'])."</a></li>";
955       }
957       // Check for special types
958       switch ($action['type']) {
959         case 'copypaste':
960           $result.= $this->renderCopyPasteMenu($separator);
961           break;
963         case 'snapshot':
964           $result.= $this->renderSnapshotMenu($separator);
965           break;
967         case 'daemon':
968           $result.= $this->renderDaemonMenu($separator);
969           break;
970       }
972       $separator= "";
973     }
975     $result.= "</ul>";
976     return $result;
977   }
980   function hasActionPermission($action, $dn)
981   {
982     $ui= get_userinfo();
984     if (isset($action['acl'])) {
985       $acls= $action['acl'];
986       if (!is_array($acls)) {
987         $acls= array($acls);
988       }
990       // Every ACL has to pass
991       foreach ($acls as $acl) {
992         $module= $this->module;
993         $aclList= array();
995         // Split for category and plugins if needed
996         // match for "[rw]" style entries
997         if (preg_match('/^\[([rwcdm]+)\]$/', $acl, $match)){
998           $aclList= array($match[1]);
999         }
1001         // match for "users[rw]" style entries
1002         if (preg_match('/^([a-zA-Z0-9]+)\[([rwcdm]+)\]$/', $acl, $match)){
1003           $module= $match[1];
1004           $aclList= array($match[2]);
1005         }
1007         // match for "users/user[rw]" style entries
1008         if (preg_match('/^([a-zA-Z0-9]+\/[a-zA-Z0-9]+)\[([rwcdm]+)\]$/', $acl, $match)){
1009           $module= $match[1];
1010           $aclList= array($match[2]);
1011         }
1013         // match "users/user[userPassword:rw(,...)*]" style entries
1014         if (preg_match('/^([a-zA-Z0-9]+\/[a-zA-Z0-9]+)\[([a-zA-Z0-9]+:[rwcdm]+(,[a-zA-Z0-9]+:[rwcdm]+)*)\]$/', $acl, $match)){
1015           $module= $match[1];
1016           $aclList= split(',', $match[2]);
1017         }
1019         // Walk thru prepared ACL by using $module
1020         foreach($aclList as $sAcl) {
1021           $checkAcl= "";
1023           // Category or detailed permission?
1024           if (strpos('/', $module) === false) {
1025             if (preg_match('/([a-zA-Z0-9]+):([rwcdm]+)/', $sAcl, $m) ) {
1026               $checkAcl= $ui->get_permissions($dn, $module, $m[1]);
1027               $sAcl= $m[2];
1028             } else {
1029               $checkAcl= $ui->get_permissions($dn, $module, '0');
1030             }
1031           } else {
1032             $checkAcl= $ui->get_category_permissions($dn, $module);
1033           }
1035           // Split up remaining part of the acl and check if it we're
1036           // allowed to do something...
1037           $parts= str_split($sAcl);
1038           foreach ($parts as $part) {
1039             if (strpos($checkAcl, $part) === false){
1040               return false;
1041             }
1042           }
1044         }
1045       }
1046     }
1048     return true;
1049   }
1052   function refreshBasesList()
1053   {
1054     global $config;
1055     $ui= get_userinfo();
1057     // Do some array munching to get it user friendly
1058     $ids= $config->idepartments;
1059     $d= $ui->get_module_departments($this->module);
1060     $k_ids= array_keys($ids);
1061     $deps= array_intersect($d,$k_ids);
1063     // Fill internal bases list
1064     $this->bases= array();
1065     foreach($k_ids as $department){
1066       $this->bases[$department] = $ids[$department];
1067     }
1068   }
1071   function getDepartments()
1072   {
1073     $departments= array();
1074     $ui= get_userinfo();
1076     // Get list of supported department types
1077     $types = departmentManagement::get_support_departments();
1079     // Load departments allowed by ACL
1080     $validDepartments = $ui->get_module_departments($this->module);
1082     // Build filter and look in the LDAP for possible sub departments
1083     // of current base
1084     $filter= "(&(objectClass=gosaDepartment)(|";
1085     $attrs= array("description", "objectClass");
1086     foreach($types as $name => $data){
1087       $filter.= "(objectClass=".$data['OC'].")";
1088       $attrs[]= $data['ATTR'];
1089     }
1090     $filter.= "))";
1091     $res= get_list($filter, $this->module, $this->base, $attrs, GL_NONE | GL_SIZELIMIT);
1093     // Analyze list of departments
1094     foreach ($res as $department) {
1095       if (!in_array($department['dn'], $validDepartments)) {
1096         continue;
1097       }
1099       // Add the attribute where we use for sorting
1100       $oc= null;
1101       foreach(array_keys($types) as $type) {
1102         if (in_array($type, $department['objectClass'])) {
1103           $oc= $type;
1104           break;
1105         }
1106       }
1107       $department['sort-attribute']= $types[$oc]['ATTR'];
1109       // Move to the result list
1110       $departments[]= $department;
1111     }
1113     return $departments;
1114   }
1117   function renderCopyPasteMenu($separator, $copy= true, $cut= true)
1118   {
1119     // We can only provide information if we've got a copypaste handler
1120     // instance
1121     if(!(isset($this->copyPasteHandler) && is_object($this->copyPasteHandler))){
1122       return "";
1123     }
1125     // Presets
1126     $result= "";
1127     $read= $paste= false;
1128     $ui= get_userinfo();
1130     // Switch flags to on if there's at least one category which allows read/paste
1131     foreach($this->categories as $category){
1132       $read= $read || preg_match('/r/', $ui->get_category_permissions($this->base, $category));
1133       $paste= $paste || $ui->is_pasteable($this->base, $category) == 1;
1134     }
1137     // Draw entries that allow copy and cut
1138     if($read){
1140       // Copy entry
1141       if($copy){
1142         $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>";
1143         $separator= "";
1144       }
1146       // Cut entry
1147       if($cut){
1148         $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>";
1149         $separator= "";
1150       }
1151     }
1153     // Draw entries that allow pasting entries
1154     if($paste){
1155       if($this->copyPasteHandler->entries_queued()){
1156         $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>";
1157       }else{
1158         $result.= "<li$separator><a href='#'><img src='images/lists/paste-grey.png' alt='' border='0' class='center'>&nbsp;"._("Paste")."</a></li>";
1159       }
1160     }
1161     
1162     return($result);
1163   }
1166   function renderCopyPasteActions($row, $dn, $category, $class, $copy= true, $cut= true)
1167   {
1168     // We can only provide information if we've got a copypaste handler
1169     // instance
1170     if(!(isset($this->copyPasteHandler) && is_object($this->copyPasteHandler))){
1171       return "";
1172     }
1174     // Presets
1175     $ui = get_userinfo();
1176     $result = "";
1178     // Render cut entries
1179     if($cut){
1180       if($ui->is_cutable($dn, $category, $class)){
1181         $result .= "<input class='center' type='image'
1182           src='images/lists/cut.png' alt='"._("Cut")."' name='listing_cut_$row' title='"._("Cut this entry")."' style='padding:1px'>";
1183       }else{
1184         $result.="<img src='images/empty.png' alt=' ' class='center' style='padding:1px'>";
1185       }
1186     }
1188     // Render copy entries
1189     if($copy){
1190       if($ui->is_copyable($dn, $category, $class)){
1191         $result.= "<input class='center' type='image'
1192           src='images/lists/copy.png' alt='"._("Copy")."' name='listing_copy_$row' title='"._("Copy this entry")."' style='padding:1px'>";
1193       }else{
1194         $result.="<img src='images/empty.png' alt=' ' class='center' style='padding:1px'>";
1195       }
1196     }
1198     return($result);
1199   }
1202   function renderSnapshotMenu($separator)
1203   {
1204     // We can only provide information if we've got a snapshot handler
1205     // instance
1206     if(!(isset($this->snapshotHandler) && is_object($this->snapshotHandler))){
1207       return "";
1208     }
1210     // Presets
1211     $result = "";
1212     $ui = get_userinfo();
1214     if($this->snapshotHandler->enabled() && $ui->allow_snapshot_restore($this->base, $this->module)){
1216       // Check if there is something to restore
1217       $restore= false;
1218       foreach($this->snapshotHandler->getSnapshotBases() as $base){
1219         $restore= $restore || count($this->snapshotHandler->getDeletedSnapshots($base)) > 0;
1220       }
1222       // Draw icons according to the restore flag
1223       if($restore){
1224         $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>";
1225       }else{
1226         $result.= "<li$separator><a href='#'><img src='images/lists/restore_grey.png' alt='' border='0' class='center'>&nbsp;"._("Restore snapshots")."</a></li>";
1227       }
1228     }
1230     return($result);
1231   }
1234   function renderSnapshotActions($row, $dn, $category, $class, $copy= true, $cut= true)
1235   {
1236     // We can only provide information if we've got a snapshot handler
1237     // instance
1238     if(!(isset($this->snapshotHandler) && is_object($this->snapshotHandler))){
1239       return "";
1240     }
1242     // Presets
1243     $result= "";
1244     $ui = get_userinfo();
1246     // Only act if enabled here
1247     if($this->snapshotHandler->enabled()){
1249       // Draw restore button
1250       if ($ui->allow_snapshot_restore($dn, $category)){
1252         // Do we have snapshots for this dn?
1253         if($this->snapshotHandler->hasSnapshots($dn)){
1254           $result.= "<input class='center' type='image' src='images/lists/restore.png' ".
1255                      "alt='"._("Restore snapshot")."' name='listing_restore_$row' title='".
1256                      _("Restore snapshot")."' style='padding:1px'>";
1257         } else {
1258           $result.= "<img src='images/lists/restore_grey.png' alt=' ' class='center' style='padding:1px'>";
1259         }
1260       }
1262       // Draw snapshot button
1263       if($ui->allow_snapshot_create($dn, $category)){
1264           $result.= "<input class='center' type='image' src='images/snapshot.png' ".
1265                      "alt='"._("Create snapshot")."' name='listing_snapshot_$row' title='".
1266                      _("Create a new snapshot from this object")."' style='padding:1px'>";
1267       }else{
1268           $result.= "<img src='images/empty.png' alt=' ' class='center' style='padding:1px'>";
1269       }
1270     }
1272     return($result);
1273   }
1276   function renderDaemonMenu($separator)
1277   {
1278     $result= "";
1280     // If there is a daemon registered, draw the menu entries
1281     if(class_available("DaemonEvent")){
1282       $events= DaemonEvent::get_event_types_by_category($this->categories);
1283       if(isset($events['BY_CLASS']) && count($events['BY_CLASS'])){
1284         foreach($events['BY_CLASS'] as $name => $event){
1285           $result.= "<li$separator><a href='#' onClick='document.getElementById(\"actionmenu\").value=\"$name\";mainform.submit();'>".$event['MenuImage']."&nbsp;".$event['s_Menu_Name']."</a></li>";
1286           $separator= "";
1287         }
1288       }
1289     }
1291     return $result;
1292   }
1296 ?>