Code

b0539c2029bdd44afafb947aade2339d0eff0466
[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     foreach ($data as $key => $value) {
104       $this->displayData[]= $value['data'];
105     }
106     $this->keys= array_keys($data);
108     // Create initial mapping
109     $this->mapping= range(0, abs(count($this->keys)-1));
110     $this->current_mapping= $this->mapping;
112     // Find the number of coluns
113     reset($this->displayData);
114     $first= current($this->displayData);
115     if (is_array($first)) {
116       $this->columns= count($first);
117     } else {
118       $this->columns= 1;
119     }
121     // Preset sort orders to 'down'
122     for ($column= 0; $column<$this->columns; $column++) {
123       $this->sortDirection[]= true;
124     }
125   }
128   public function setWidth($width)
129   {
130     $this->width= $width;
131   }
134   public function setInstantDelete($flag)
135   {
136     $this->instantDelete= $flag;
137   }
140   public function setColorAlternate($flag)
141   {
142     $this->colorAlternate= $flag;
143   }
146   public function setEditable($flag)
147   {
148     $this->editable= $flag;
149   }
152   public function setDeleteable($flag)
153   {
154     $this->deleteable= $flag;
155   }
158   public function setHeight($height)
159   {
160     $this->height= $height;
161   }
164   public function setCssClass($css)
165   {
166     $this->cssclass= $css;
167   }
170   public function setHeader($header)
171   {
172     $this->header= $header;
173   }
176   public function setColspecs($specs)
177   {
178     $this->colspecs= $specs;
179   }
182   public function render()
183   {
184     $result= "<div class='sortableListContainer' id='scroll_".$this->id."' style='min-width:".$this->width.";height: ".$this->height."'>\n";
185     $result.= "<table border='0' cellpadding='0' cellspacing='0' width='100%' height='100%' ".(!empty($this->cssclass)?" class='".$this->cssclass."'":"").">\n";
186     $action_width= 0;
187     if (strpos($this->acl, 'w') === false) {
188       $edit_image= $this->editable?"<img class='center' src='images/lists/edit-grey.png' alt='"._("Edit")."'>":"";
189     } else {
190       $edit_image= $this->editable?"<input class='center' type='image' src='images/lists/edit.png' alt='"._("Edit")."' name='%ID' id='%ID' title='"._("Edit this entry")."'>":"";
191     }
192     if (strpos($this->acl, 'd') === false) {
193       $delete_image= $this->deleteable?"<img class='center' src='images/lists/trash-grey.png' alt='"._("Delete")."'>":"";
194     } else {
195       $delete_image= $this->deleteable?"<input class='center' type='image' src='images/lists/trash.png' alt='"._("Delete")."' name='%ID' title='"._("Delete this entry")."'>":"";
196     }
198     // Do we need colspecs?
199     $action_width= ($this->editable?20:0) + ($this->deleteable?20:0);
200     if ($this->colspecs) {
201       $result.= " <colgroup>\n";
202       for ($i= 0; $i<$this->columns; $i++) {
203         $result.= "  <col style='width:".(isset($this->colspecs[$i])?$this->colspecs[$i]:"*")."'/>\n";
204       }
206       // Extend by another column if we've actions specified
207       if ($action_width) {
208         $result.= "  <col style='width:".$action_width."px'/>\n";
209       }
210       $result.= " </colgroup>\n";
211     }
213     // Do we need a header?
214     if ($this->header) {
215       $result.= " <thead>\n  <tr>\n";
216       $first= " style='border:0'";
217       for ($i= 0; $i<$this->columns; $i++) {
218         $link= "href='?plug=".$_GET['plug']."&amp;PID=".$this->id."&amp;act=SORT_$i'";
219         $sorter= "";
220         if ($i == $this->sortColumn){
221           $sorter= "&nbsp;<img border='0' title='".($this->sortDirection[$i]?_("Up"):_("Down"))."' src='images/lists/sort-".($this->sortDirection[$i]?"up":"down").".png' align='top'>";
222         }
224         if ($this->reorderable) {
225           $result.= "   <th$first>".(isset($this->header[$i])?$this->header[$i]:"")."</th>";
226         } else {
227           $result.= "   <th$first><a $link>".(isset($this->header[$i])?$this->header[$i]:"")."$sorter</a></th>";
228         }
229         $first= "";
230       }
231       if ($action_width) {
232         $result.= "<th>&nbsp;</th>";
233       }
234       $result.= "\n  </tr>\n </thead>\n";
235     }
237     // Render table body if we've read permission
238     $result.= " <tbody id='".$this->id."'>\n";
239     $reorderable= $this->reorderable?"":" style='cursor:default'";
240     if (strpos($this->acl, 'r') !== false) {
241       foreach ($this->mapping as $nr => $row) {
242         $editable= $this->editable?" onclick='$(\"edit_".$this->id."_$nr\").click()'":"";
244         $id= "";
245         if (isset($this->modes[$row])) {
246           switch ($this->modes[$row]) {
247             case LIST_DISABLED:
248               $id= " sortableListItemDisabled";
249               $editable= false;
250               break;
251             case LIST_MARKED:
252               $id= " sortableListItemMarked";
253               break;
254           }
255         }
257         $result.= "  <tr class='sortableListItem".((($nr&1)||!$this->colorAlternate)?'':'Odd')."$id' id='item_".$this->id."_$nr'$reorderable>\n";
258         $first= " style='border:0'";
260         foreach ($this->displayData[$row] as $column) {
261           $result.= "   <td$editable$first>".$column."</td>\n";
262           $first= "";
263         }
265         if ($action_width) {
266           $result.= "<td>".str_replace('%ID', "edit_".$this->id."_$nr", $edit_image).
267                            str_replace('%ID', "del_".$this->id."_$nr", $delete_image)."</td>";
268         }
270         $result.= "  </tr>\n";
271       }
272     }
274     // Add spacer
275     $result.= "  <tr class='sortableListItemFill' style='height:100%'><td style='border:0'></td>";
276     $num= $action_width?$this->columns:$this->columns-1;
277     for ($i= 0; $i<$num; $i++) {
278       $result.= "<td class='sortableListItemFill'></td>";
279     }
280     $result.= "</tr>\n";
282     $result.= " </tbody>\n</table>\n</div>\n";
283     $result.= " <input type='hidden' name='PID' value='".$this->id."' id='PID'>\n";
284     $result.= " <input type='hidden' name='position_".$this->id."' id='position_".$this->id."'>\n";
285     $result.= " <input type='hidden' name='reorder_".$this->id."' id='reorder_".$this->id."'>\n";
287     // Append script stuff if needed
288     $result.= '<script type="text/javascript" language="javascript">';
289     if ($this->reorderable) {
290       $result.= ' function updateOrder(){';
291       $result.= '    var ampcharcode= \'%26\';';
292       $result.= '    var serializeOpts = Sortable.serialize(\''.$this->id.'\')+"='.$this->id.'";';
293       $result.= '    $("reorder_'.$this->id.'").value= serializeOpts;';
294       $result.= '    document.mainform.submit();';
295       $result.= ' }';
296       $result.= 'Position.includeScrollOffsets = true;';
297       $result.= ' Sortable.create(\''.$this->id.'\',{tag:\'tr\', ghosting:false, constraint:\'vertical\', scroll:\'scroll_'.$this->id.'\',onUpdate : updateOrder});';
298     }
299     $result.= '$("scroll_'.$this->id.'").scrollTop= '.$this->scrollPosition.';';
300     $result.= 'var box = $("scroll_'.$this->id.'").onscroll= function() {$("position_'.$this->id.'").value= this.scrollTop;}';
301     $result.= '</script>';
303     return $result;
304   }
307   public function update()
308   {
309     // Do not do anything if this is not our PID, or there's even no PID available...
310     if(!isset($_REQUEST['PID']) || $_REQUEST['PID'] != $this->id) {
311       return;
312     }
314     // Filter GET with "act" attributes
315     if (!$this->reorderable && isset($_GET['act'])) {
316       $key= validate($_GET['act']);
317       if (preg_match('/^SORT_([0-9]+)$/', $key, $match)) {
318         // Switch to new column or invert search order?
319         $column= $match[1];
320         if ($this->sortColumn != $column) {
321           $this->sortColumn= $column;
322         } else {
323           $this->sortDirection[$column]= !$this->sortDirection[$column];
324         }
326         // Update mapping according to sort parameters
327         $this->sortData();
328       }
329     }
330   }
333   public function save_object()
334   {
335     // Do not do anything if this is not our PID, or there's even no PID available...
336     if(!isset($_REQUEST['PID']) || $_REQUEST['PID'] != $this->id) {
337       return;
338     }
340     // Do not do anything if we're not posted - or have no permission
341     if (strpos($this->acl, 'w') !== false && isset($_POST['reorder_'.$this->id])){
343       if (isset($_POST['position_'.$this->id]) && is_numeric($_POST['position_'.$this->id])) {
344         $this->scrollPosition= $_POST['position_'.$this->id];
345       }
347       // Move requested?
348       $move= $_POST['reorder_'.$this->id];
349       if ($move != "") {
350         preg_match_all('/=([0-9]+)[&=]/', $move, $matches);
351         $this->action= "reorder";
352         $tmp= array();
353         foreach ($matches[1] as $id => $row) {
354           $tmp[$id]= $this->mapping[$row];
355         }
356         $this->mapping= $tmp;
357         $this->current_mapping= $matches[1];
358         $this->modified= true;
359         return;
360       }
361     }
363     // Delete requested?
364     if (strpos($this->acl, 'd') !== false){
365       foreach ($_POST as $key => $value) {
366         if (preg_match('/^del_'.$this->id.'_([0-9]+)_x.*$/', $key, $matches)) {
367           $this->active_index= $this->mapping[$matches[1]];
368           $this->action= "delete";
369           if ($this->instantDelete) {
370             $this->deleteEntry($this->active_index);
371           }
372         }
373       }
374     }
376     // Edit requested?
377     if (strpos($this->acl, 'w') !== false){
378       foreach ($_POST as $key => $value) {
379         if (preg_match('/^edit_'.$this->id.'_([0-9]+)_x.*$/', $key, $matches)) {
380           $this->active_index= $this->mapping[$matches[1]];
381           $this->action= "edit";
382         }
383       }
384     }
385   }
388   public function getAction()
389   {
390     // Do not do anything if we're not posted
391     if(!isset($_POST['reorder_'.$this->id])) {
392       return;
393     }
395     // For reordering, return current mapping
396     if ($this->action == 'reorder') {
397       return array("targets" => $this->current_mapping, "mapping" => $this->mapping, "action" => $this->action);
398     }
400     // Edit and delete
401     $result= array("targets" => array($this->active_index), "action" => $this->action);
403     return $result;
404   }
407   private function deleteEntry($id)
408   {
409     // Remove mapping
410     $index= array_search($id, $this->mapping);
411     if ($index !== false) {
412       unset($this->mapping[$index]);
413       $this->mapping= array_values($this->mapping);
414       $this->modified= true;
415     }
416   }
419   public function getMaintainedData()
420   {
421     $tmp= array();
423     foreach ($this->mapping as $src => $dst) {
424       $tmp[$this->keys[$dst]]= $this->data[$dst];
425     }
427     return $tmp;
428   }
431   public function isModified()
432   {
433     return $this->modified;
434   }
437   public function setAcl($acl)
438   {
439     $this->acl= $acl;
440   }
443   public function sortData()
444   {
445     // Extract data
446     $tmp= array();
447     foreach($this->displayData as $item) {
448       if (isset($item[$this->sortColumn])){
449         $tmp[]= $item[$this->sortColumn];
450       } else {
451         $tmp[]= "";
452       }
453     }
455     // Sort entries
456     if ($this->sortDirection[$this->sortColumn]) {
457       asort($tmp);
458     } else {
459       arsort($tmp);
460     }
462     // Adapt mapping accordingly
463     $this->mapping= array();
464     foreach ($tmp as $key => $value) {
465       $this->mapping[]= $key;
466     }
467   }
470   public function addEntry($entry, $displayEntry= null, $key= null)
471   {
472     // Only add if not already there
473     if (!$key) {
474       if (in_array($entry, $this->data)) {
475         return;
476       }
477     } else {
478       if (isset($this->data[$key])) {
479         return;
480       }
481     }
483     // Prefill with default value if not specified
484     if (!$displayEntry) {
485       $displayEntry= array('data' => array($entry));
486     }
488     // Append to data and mapping
489     if ($key) {
490       $this->data[$key]= $entry;
491       $this->keys[]= $key;
492     } else {
493       $this->data[]= $entry;
494       $this->keys[]= count($this->mapping);
495     }
496     $this->displayData[]= $displayEntry['data'];
497     $this->mapping[]= count($this->mapping);
498     $this->modified= true;
500     // Sort data after we've added stuff
501     $this->sortData();
502   }
505   public function getKey($index) {
506     return isset($this->keys[$index])?$this->keys[$index]:null;
507   }