Code

Added modes to list to mark, enable or disable entries
[gosa.git] / gosa-core / include / class_sortableListing.inc
1 <?php
2 /*
3  * This code is part of GOsa (http://www.gosa-project.org)
4  * Copyright (C) 2003-2010 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 define ('LIST_NORMAL', 0);
24 define ('LIST_MARKED', 1);
25 define ('LIST_DISABLED', 2);
27 class sortableListing {
28   private $header= null;
29   private $colspecs= null;
30   private $reorderable= true;
31   private $width= "400px";
32   private $height= "100px";
33   private $cssclass= "";
34   private $id;
36   private $data= array();
37   private $keys= array();
38   private $modes= array();
39   private $displayData= array();
40   private $columns= 0;
41   private $deleteable= false;
42   private $editable= false;
43   private $colorAlternate= false;
44   private $instantDelete= true;
45   private $action;
46   private $mapping;
47   private $current_mapping;
48   private $active_index;
49   private $scrollPosition= 0;
50   private $sortColumn= 0;
51   private $sortDirection= array();
53   private $acl= "";
54   private $modified= false;
56   public function sortableListing($data= array(), $displayData= null, $reorderable= false)
57   {
58     global $config;
60     // Save data to display
61     $this->setListData($data, $displayData);
63     // Generate instance wide unique ID
64     $tmp= gettimeofday();
65     $this->id= 'l'.md5($tmp['sec']);
67     // Set reorderable flag
68     $this->reorderable= $reorderable;
69     if (!$reorderable) {
70       $this->sortData();
71     }
72   }
75   public function setListData($data, $displayData= null)
76   {
77     // Save data to display
78     $this->setData($data);
79     if (!$displayData) {
80       $displayData= array();
81       foreach ($data as $key => $value) {
82         $displayData[$key]= array("data" => array($value));
83       }
84     }
85     $this->setDisplayData($displayData);
86   }
89   private function setData($data)
90   {
91     $this->data= $data;
92   }
95   private function setDisplayData($data)
96   {
97     if (!is_array($data)) {
98       die ("sortableList needs an array as data!");
99     }
101     // Transfer information
102     $this->displayData= array();
103     $this->modes= array();
104     foreach ($data as $key => $value) {
105       $this->displayData[]= $value['data'];
106       if (isset($value['mode'])) {
107         $this->modes[]= $value['mode'];
108       }
109     }
110     $this->keys= array_keys($data);
112     // Create initial mapping
113     $this->mapping= range(0, abs(count($this->keys)-1));
114     $this->current_mapping= $this->mapping;
116     // Find the number of coluns
117     reset($this->displayData);
118     $first= current($this->displayData);
119     if (is_array($first)) {
120       $this->columns= count($first);
121     } else {
122       $this->columns= 1;
123     }
125     // Preset sort orders to 'down'
126     for ($column= 0; $column<$this->columns; $column++) {
127       $this->sortDirection[]= true;
128     }
129   }
132   public function setWidth($width)
133   {
134     $this->width= $width;
135   }
138   public function setInstantDelete($flag)
139   {
140     $this->instantDelete= $flag;
141   }
144   public function setColorAlternate($flag)
145   {
146     $this->colorAlternate= $flag;
147   }
150   public function setEditable($flag)
151   {
152     $this->editable= $flag;
153   }
156   public function setDeleteable($flag)
157   {
158     $this->deleteable= $flag;
159   }
162   public function setHeight($height)
163   {
164     $this->height= $height;
165   }
168   public function setCssClass($css)
169   {
170     $this->cssclass= $css;
171   }
174   public function setHeader($header)
175   {
176     $this->header= $header;
177   }
180   public function setColspecs($specs)
181   {
182     $this->colspecs= $specs;
183   }
186   public function render()
187   {
188     $result= "<div class='sortableListContainer' id='scroll_".$this->id."' style='min-width:".$this->width.";height: ".$this->height."'>\n";
189     $result.= "<table border='0' cellpadding='0' cellspacing='0' width='100%' height='100%' ".(!empty($this->cssclass)?" class='".$this->cssclass."'":"").">\n";
190     $action_width= 0;
191     if (strpos($this->acl, 'w') === false) {
192       $edit_image= $this->editable?"<img class='center' src='images/lists/edit-grey.png' alt='"._("Edit")."'>":"";
193     } else {
194       $edit_image= $this->editable?"<input class='center' type='image' src='images/lists/edit.png' alt='"._("Edit")."' name='%ID' id='%ID' title='"._("Edit this entry")."'>":"";
195     }
196     if (strpos($this->acl, 'd') === false) {
197       $delete_image= $this->deleteable?"<img class='center' src='images/lists/trash-grey.png' alt='"._("Delete")."'>":"";
198     } else {
199       $delete_image= $this->deleteable?"<input class='center' type='image' src='images/lists/trash.png' alt='"._("Delete")."' name='%ID' title='"._("Delete this entry")."'>":"";
200     }
202     // Do we need colspecs?
203     $action_width= ($this->editable?20:0) + ($this->deleteable?20:0);
204     if ($this->colspecs) {
205       $result.= " <colgroup>\n";
206       for ($i= 0; $i<$this->columns; $i++) {
207         $result.= "  <col style='width:".(isset($this->colspecs[$i])?$this->colspecs[$i]:"*")."'/>\n";
208       }
210       // Extend by another column if we've actions specified
211       if ($action_width) {
212         $result.= "  <col style='width:".$action_width."px'/>\n";
213       }
214       $result.= " </colgroup>\n";
215     }
217     // Do we need a header?
218     if ($this->header) {
219       $result.= " <thead>\n  <tr>\n";
220       $first= " style='border:0'";
221       for ($i= 0; $i<$this->columns; $i++) {
222         $link= "href='?plug=".$_GET['plug']."&amp;PID=".$this->id."&amp;act=SORT_$i'";
223         $sorter= "";
224         if ($i == $this->sortColumn){
225           $sorter= "&nbsp;<img border='0' title='".($this->sortDirection[$i]?_("Up"):_("Down"))."' src='images/lists/sort-".($this->sortDirection[$i]?"up":"down").".png' align='top'>";
226         }
228         if ($this->reorderable) {
229           $result.= "   <th$first>".(isset($this->header[$i])?$this->header[$i]:"")."</th>";
230         } else {
231           $result.= "   <th$first><a $link>".(isset($this->header[$i])?$this->header[$i]:"")."$sorter</a></th>";
232         }
233         $first= "";
234       }
235       if ($action_width) {
236         $result.= "<th>&nbsp;</th>";
237       }
238       $result.= "\n  </tr>\n </thead>\n";
239     }
241     // Render table body if we've read permission
242     $result.= " <tbody id='".$this->id."'>\n";
243     $reorderable= $this->reorderable?"":" style='cursor:default'";
244     if (strpos($this->acl, 'r') !== false) {
245       foreach ($this->mapping as $nr => $row) {
246         $editable= $this->editable?" onclick='$(\"edit_".$this->id."_$nr\").click()'":"";
248         $id= "";
249         if (isset($this->modes[$row])) {
250           switch ($this->modes[$row]) {
251             case LIST_DISABLED:
252               $id= " sortableListItemDisabled";
253               $editable= "";
254               break;
255             case LIST_MARKED:
256               $id= " sortableListItemMarked";
257               break;
258           }
259         }
261         $result.= "  <tr class='sortableListItem".((($nr&1)||!$this->colorAlternate)?'':'Odd')."$id' id='item_".$this->id."_$nr'$reorderable>\n";
262         $first= " style='border:0'";
264         foreach ($this->displayData[$row] as $column) {
265           $result.= "   <td$editable$first>".$column."</td>\n";
266           $first= "";
267         }
269         if ($action_width) {
270           $result.= "<td>".str_replace('%ID', "edit_".$this->id."_$nr", $edit_image).
271                            str_replace('%ID', "del_".$this->id."_$nr", $delete_image)."</td>";
272         }
274         $result.= "  </tr>\n";
275       }
276     }
278     // Add spacer
279     $result.= "  <tr class='sortableListItemFill' style='height:100%'><td style='border:0'></td>";
280     $num= $action_width?$this->columns:$this->columns-1;
281     for ($i= 0; $i<$num; $i++) {
282       $result.= "<td class='sortableListItemFill'></td>";
283     }
284     $result.= "</tr>\n";
286     $result.= " </tbody>\n</table>\n</div>\n";
287     $result.= " <input type='hidden' name='PID' value='".$this->id."' id='PID'>\n";
288     $result.= " <input type='hidden' name='position_".$this->id."' id='position_".$this->id."'>\n";
289     $result.= " <input type='hidden' name='reorder_".$this->id."' id='reorder_".$this->id."'>\n";
291     // Append script stuff if needed
292     $result.= '<script type="text/javascript" language="javascript">';
293     if ($this->reorderable) {
294       $result.= ' function updateOrder(){';
295       $result.= '    var ampcharcode= \'%26\';';
296       $result.= '    var serializeOpts = Sortable.serialize(\''.$this->id.'\')+"='.$this->id.'";';
297       $result.= '    $("reorder_'.$this->id.'").value= serializeOpts;';
298       $result.= '    document.mainform.submit();';
299       $result.= ' }';
300       $result.= 'Position.includeScrollOffsets = true;';
301       $result.= ' Sortable.create(\''.$this->id.'\',{tag:\'tr\', ghosting:false, constraint:\'vertical\', scroll:\'scroll_'.$this->id.'\',onUpdate : updateOrder});';
302     }
303     $result.= '$("scroll_'.$this->id.'").scrollTop= '.$this->scrollPosition.';';
304     $result.= 'var box = $("scroll_'.$this->id.'").onscroll= function() {$("position_'.$this->id.'").value= this.scrollTop;}';
305     $result.= '</script>';
307     return $result;
308   }
311   public function update()
312   {
313     // Do not do anything if this is not our PID, or there's even no PID available...
314     if(!isset($_REQUEST['PID']) || $_REQUEST['PID'] != $this->id) {
315       return;
316     }
318     // Filter GET with "act" attributes
319     if (!$this->reorderable && isset($_GET['act'])) {
320       $key= validate($_GET['act']);
321       if (preg_match('/^SORT_([0-9]+)$/', $key, $match)) {
322         // Switch to new column or invert search order?
323         $column= $match[1];
324         if ($this->sortColumn != $column) {
325           $this->sortColumn= $column;
326         } else {
327           $this->sortDirection[$column]= !$this->sortDirection[$column];
328         }
330         // Update mapping according to sort parameters
331         $this->sortData();
332       }
333     }
334   }
337   public function save_object()
338   {
339     // Do not do anything if this is not our PID, or there's even no PID available...
340     if(!isset($_REQUEST['PID']) || $_REQUEST['PID'] != $this->id) {
341       return;
342     }
344     // Do not do anything if we're not posted - or have no permission
345     if (strpos($this->acl, 'w') !== false && isset($_POST['reorder_'.$this->id])){
347       if (isset($_POST['position_'.$this->id]) && is_numeric($_POST['position_'.$this->id])) {
348         $this->scrollPosition= $_POST['position_'.$this->id];
349       }
351       // Move requested?
352       $move= $_POST['reorder_'.$this->id];
353       if ($move != "") {
354         preg_match_all('/=([0-9]+)[&=]/', $move, $matches);
355         $this->action= "reorder";
356         $tmp= array();
357         foreach ($matches[1] as $id => $row) {
358           $tmp[$id]= $this->mapping[$row];
359         }
360         $this->mapping= $tmp;
361         $this->current_mapping= $matches[1];
362         $this->modified= true;
363         return;
364       }
365     }
367     // Delete requested?
368     if (strpos($this->acl, 'd') !== false){
369       foreach ($_POST as $key => $value) {
370         if (preg_match('/^del_'.$this->id.'_([0-9]+)_x.*$/', $key, $matches)) {
371           $this->active_index= $this->mapping[$matches[1]];
373           // Ignore request if mode requests it
374           if (isset($this->modes[$this->active_index]) && $this->modes[$this->active_index] == LIST_DISABLED) {
375             $this->active_index= null;
376             continue;
377           }
379           // Set action
380           $this->action= "delete";
382           // Remove value if requested
383           if ($this->instantDelete) {
384             $this->deleteEntry($this->active_index);
385           }
386         }
387       }
388     }
390     // Edit requested?
391     if (strpos($this->acl, 'w') !== false){
392       foreach ($_POST as $key => $value) {
393         if (preg_match('/^edit_'.$this->id.'_([0-9]+)_x.*$/', $key, $matches)) {
394           $this->active_index= $this->mapping[$matches[1]];
396           // Ignore request if mode requests it
397           if (isset($this->modes[$this->active_index]) && $this->modes[$this->active_index] == LIST_DISABLED) {
398             $this->active_index= null;
399             continue;
400           }
402           $this->action= "edit";
403         }
404       }
405     }
406   }
409   public function getAction()
410   {
411     // Do not do anything if we're not posted
412     if(!isset($_POST['reorder_'.$this->id])) {
413       return;
414     }
416     // For reordering, return current mapping
417     if ($this->action == 'reorder') {
418       return array("targets" => $this->current_mapping, "mapping" => $this->mapping, "action" => $this->action);
419     }
421     // Edit and delete
422     $result= array("targets" => array($this->active_index), "action" => $this->action);
424     return $result;
425   }
428   private function deleteEntry($id)
429   {
430     // Remove mapping
431     $index= array_search($id, $this->mapping);
432     if ($index !== false) {
433       unset($this->mapping[$index]);
434       $this->mapping= array_values($this->mapping);
435       $this->modified= true;
436     }
437   }
440   public function getMaintainedData()
441   {
442     $tmp= array();
444     foreach ($this->mapping as $src => $dst) {
445       $tmp[$this->keys[$dst]]= $this->data[$dst];
446     }
448     return $tmp;
449   }
452   public function isModified()
453   {
454     return $this->modified;
455   }
458   public function setAcl($acl)
459   {
460     $this->acl= $acl;
461   }
464   public function sortData()
465   {
466     // Extract data
467     $tmp= array();
468     foreach($this->displayData as $item) {
469       if (isset($item[$this->sortColumn])){
470         $tmp[]= $item[$this->sortColumn];
471       } else {
472         $tmp[]= "";
473       }
474     }
476     // Sort entries
477     if ($this->sortDirection[$this->sortColumn]) {
478       asort($tmp);
479     } else {
480       arsort($tmp);
481     }
483     // Adapt mapping accordingly
484     $this->mapping= array();
485     foreach ($tmp as $key => $value) {
486       $this->mapping[]= $key;
487     }
488   }
491   public function addEntry($entry, $displayEntry= null, $key= null)
492   {
493     // Only add if not already there
494     if (!$key) {
495       if (in_array($entry, $this->data)) {
496         return;
497       }
498     } else {
499       if (isset($this->data[$key])) {
500         return;
501       }
502     }
504     // Prefill with default value if not specified
505     if (!$displayEntry) {
506       $displayEntry= array('data' => array($entry));
507     }
509     // Append to data and mapping
510     if ($key) {
511       $this->data[$key]= $entry;
512       $this->keys[]= $key;
513     } else {
514       $this->data[]= $entry;
515       $this->keys[]= count($this->mapping);
516     }
517     $this->displayData[]= $displayEntry['data'];
518     $this->mapping[]= count($this->mapping);
519     $this->modified= true;
521     // Sort data after we've added stuff
522     $this->sortData();
523   }
526   public function getKey($index) {
527     return isset($this->keys[$index])?$this->keys[$index]:null;
528   }