Code

Updated sortable listing.
[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     $this->mapping= array();
105     foreach ($data as $key => $value) {
106       $this->displayData[]= $value['data'];
107       if (isset($value['mode'])) {
108         $this->modes[]= $value['mode'];
109       }
110     }
111     $this->keys= array_keys($data);
113     // Create initial mapping
114     if(count($this->keys)){
115       $this->mapping= range(0, abs(count($this->keys)-1));
116     }
117     $this->current_mapping= $this->mapping;
119     // Find the number of coluns
120     reset($this->displayData);
121     $first= current($this->displayData);
122     if (is_array($first)) {
123       $this->columns= count($first);
124     } else {
125       $this->columns= 1;
126     }
128     // Preset sort orders to 'down'
129     for ($column= 0; $column<$this->columns; $column++) {
130       $this->sortDirection[]= true;
131     }
132   }
135   public function setWidth($width)
136   {
137     $this->width= $width;
138   }
141   public function setInstantDelete($flag)
142   {
143     $this->instantDelete= $flag;
144   }
147   public function setColorAlternate($flag)
148   {
149     $this->colorAlternate= $flag;
150   }
153   public function setEditable($flag)
154   {
155     $this->editable= $flag;
156   }
159   public function setDeleteable($flag)
160   {
161     $this->deleteable= $flag;
162   }
165   public function setHeight($height)
166   {
167     $this->height= $height;
168   }
171   public function setCssClass($css)
172   {
173     $this->cssclass= $css;
174   }
177   public function setHeader($header)
178   {
179     $this->header= $header;
180   }
183   public function setColspecs($specs)
184   {
185     $this->colspecs= $specs;
186   }
189   public function render()
190   {
191     $result= "<div class='sortableListContainer' id='scroll_".$this->id."' style='min-width:".$this->width.";height: ".$this->height."'>\n";
192     $result.= "<table summary='"._("Sortable list")."' border='0' cellpadding='0' cellspacing='0' width='100%' style='width:100%' ".(!empty($this->cssclass)?" class='".$this->cssclass."'":"").">\n";
193     $action_width= 0;
194     if (strpos($this->acl, 'w') === false) {
195       $edit_image= $this->editable?image("images/lists/edit-grey.png"):"";
196     } else {
197       $edit_image= $this->editable?image('images/lists/edit.png', "%ID", _("Edit this entry")):"";
198     }
199     if (strpos($this->acl, 'd') === false) {
200       $delete_image= $this->deleteable?image('images/lists/trash-grey.png'):"";
201     } else {
202       $delete_image= $this->deleteable?image('images/lists/trash.png', "%ID", _("Delete this entry")):"";
203     }
205     // Do we need colspecs?
206     $action_width= ($this->editable?20:0) + ($this->deleteable?20:0);
207     if ($this->colspecs) {
208       $result.= " <colgroup>\n";
209       for ($i= 0; $i<$this->columns; $i++) {
210         if(isset($this->colspecs[$i]) && $this->colspecs[$i] != '*'){
211           $result.= "  <col style='width:".($this->colspecs[$i])."'>\n";
212         }else{
213           $result.= "  <col>\n";
214         }
215       }
217       // Extend by another column if we've actions specified
218       if ($action_width) {
219         $result.= "  <col style='width:".$action_width."px' >\n";
220       }
221       $result.= " </colgroup>\n";
222     }
224     // Do we need a header?
225     if ($this->header) {
226       $result.= " <thead>\n  <tr>\n";
227       $first= " style='border-left:0'";
228       for ($i= 0; $i<$this->columns; $i++) {
229         $link= "href='?plug=".$_GET['plug']."&amp;PID=".$this->id."&amp;act=SORT_$i'";
230         $sorter= "";
231         if ($i == $this->sortColumn){
232           $sorter= "&nbsp;".image("images/lists/sort-".($this->sortDirection[$i]?"up":"down").".png", null, $this->sortDirection[$i]?_("Up"):_("Down"));
233         }
235         if ($this->reorderable) {
236           $result.= "   <th$first>".(isset($this->header[$i])?$this->header[$i]:"")."</th>";
237         } else {
238           $result.= "   <th$first><a $link>".(isset($this->header[$i])?$this->header[$i]:"")."</a>$sorter</th>";
239         }
240         $first= "";
241       }
242       if ($action_width) {
243         $result.= "<th>&nbsp;</th>";
244       }
245       $result.= "\n  </tr>\n </thead>\n";
246     }
248     // Render table body if we've read permission
249     $result.= " <tbody id='".$this->id."'>\n";
250     $reorderable= $this->reorderable?"":" style='cursor:default'";
251     if (strpos($this->acl, 'r') !== false) {
252       foreach ($this->mapping as $nr => $row) {
253         $editable= $this->editable?" onClick='$(\"edit_".$this->id."_$nr\").click()'":"";
255         $id= "";
256         if (isset($this->modes[$row])) {
257           switch ($this->modes[$row]) {
258             case LIST_DISABLED:
259               $id= " sortableListItemDisabled";
260               $editable= "";
261               break;
262             case LIST_MARKED:
263               $id= " sortableListItemMarked";
264               break;
265           }
266         }
268         $result.= "  <tr class='sortableListItem".((($nr&1)||!$this->colorAlternate)?'':'Odd')."$id' id='item_".$this->id."_$nr'$reorderable>\n";
269         $first= " style='border:0'";
271         foreach ($this->displayData[$row] as $column) {
272           $result.= "   <td$editable$first>".$column."</td>\n";
273           $first= "";
274         }
276         if ($action_width) {
277           $result.= "<td>".str_replace('%ID', "edit_".$this->id."_$nr", $edit_image).
278                            str_replace('%ID', "del_".$this->id."_$nr", $delete_image)."</td>";
279         }
281         $result.= "  </tr>\n";
282       }
283     }
285     // Add spacer
286     $result.= "  <tr class='sortableListItemFill' style='height:100%'><td style='border:0'></td>";
287     $num= $action_width?$this->columns:$this->columns-1;
288     for ($i= 0; $i<$num; $i++) {
289       $result.= "<td class='sortableListItemFill'></td>";
290     }
291     $result.= "</tr>\n";
293     $result.= " </tbody>\n</table>\n</div>\n";
294     $result.= " <input type='hidden' name='PID' value='".$this->id."' id='PID'>\n";
295     $result.= " <input type='hidden' name='position_".$this->id."' id='position_".$this->id."'>\n";
296     $result.= " <input type='hidden' name='reorder_".$this->id."' id='reorder_".$this->id."'>\n";
298     // Append script stuff if needed
299     $result.= '<script type="text/javascript" language="javascript">';
300     if ($this->reorderable) {
301       $result.= ' function updateOrder(){';
302       $result.= '    var ampcharcode= \'%26\';';
303       $result.= '    var serializeOpts = Sortable.serialize(\''.$this->id.'\')+"='.$this->id.'";';
304       $result.= '    $("reorder_'.$this->id.'").value= serializeOpts;';
305       $result.= '    document.mainform.submit();';
306       $result.= ' }';
307       $result.= 'Position.includeScrollOffsets = true;';
308       $result.= ' Sortable.create(\''.$this->id.'\',{tag:\'tr\', ghosting:false, constraint:\'vertical\', scroll:\'scroll_'.$this->id.'\',onUpdate : updateOrder});';
309     }
310     $result.= '$("scroll_'.$this->id.'").scrollTop= '.$this->scrollPosition.';';
311     $result.= 'var box = $("scroll_'.$this->id.'").onscroll= function() {$("position_'.$this->id.'").value= this.scrollTop;}';
312     $result.= '</script>';
314     return $result;
315   }
318   public function update()
319   {
320     // Do not do anything if this is not our PID, or there's even no PID available...
321     if(!isset($_REQUEST['PID']) || $_REQUEST['PID'] != $this->id) {
322       return;
323     }
325     // Filter GET with "act" attributes
326     if (!$this->reorderable && isset($_GET['act'])) {
327       $key= validate($_GET['act']);
328       if (preg_match('/^SORT_([0-9]+)$/', $key, $match)) {
329         // Switch to new column or invert search order?
330         $column= $match[1];
331         if ($this->sortColumn != $column) {
332           $this->sortColumn= $column;
333         } else {
334           $this->sortDirection[$column]= !$this->sortDirection[$column];
335         }
337         // Update mapping according to sort parameters
338         $this->sortData();
339       }
340     }
341   }
344   public function save_object()
345   {
346     // Do not do anything if this is not our PID, or there's even no PID available...
347     if(!isset($_REQUEST['PID']) || $_REQUEST['PID'] != $this->id) {
348       return;
349     }
351     // Do not do anything if we're not posted - or have no permission
352     if (strpos($this->acl, 'w') !== false && isset($_POST['reorder_'.$this->id])){
354       if (isset($_POST['position_'.$this->id]) && is_numeric($_POST['position_'.$this->id])) {
355         $this->scrollPosition= $_POST['position_'.$this->id];
356       }
358       // Move requested?
359       $move= $_POST['reorder_'.$this->id];
360       if ($move != "") {
361         preg_match_all('/=([0-9]+)[&=]/', $move, $matches);
362         $this->action= "reorder";
363         $tmp= array();
364         foreach ($matches[1] as $id => $row) {
365           $tmp[$id]= $this->mapping[$row];
366         }
367         $this->mapping= $tmp;
368         $this->current_mapping= $matches[1];
369         $this->modified= true;
370         return;
371       }
372     }
374     // Delete requested?
375     $this->action = "";
376     if (strpos($this->acl, 'd') !== false){
377       foreach ($_POST as $key => $value) {
378         if (preg_match('/^del_'.$this->id.'_([0-9]+)$/', $key, $matches)) {
379           $this->active_index= $this->mapping[$matches[1]];
381           // Ignore request if mode requests it
382           if (isset($this->modes[$this->active_index]) && $this->modes[$this->active_index] == LIST_DISABLED) {
383             $this->active_index= null;
384             continue;
385           }
387           // Set action
388           $this->action= "delete";
390           // Remove value if requested
391           if ($this->instantDelete) {
392             $this->deleteEntry($this->active_index);
393           }
394         }
395       }
396     }
398     // Edit requested?
399     if (strpos($this->acl, 'w') !== false){
400       foreach ($_POST as $key => $value) {
401         if (preg_match('/^edit_'.$this->id.'_([0-9]+)$/', $key, $matches)) {
402           $this->active_index= $this->mapping[$matches[1]];
404           // Ignore request if mode requests it
405           if (isset($this->modes[$this->active_index]) && $this->modes[$this->active_index] == LIST_DISABLED) {
406             $this->active_index= null;
407             continue;
408           }
410           $this->action= "edit";
411         }
412       }
413     }
414   }
417   public function getAction()
418   {
419     // Do not do anything if we're not posted
420     if(!isset($_POST['reorder_'.$this->id])) {
421       return;
422     }
424     // For reordering, return current mapping
425     if ($this->action == 'reorder') {
426       return array("targets" => $this->current_mapping, "mapping" => $this->mapping, "action" => $this->action);
427     }
429     // Edit and delete
430     $result= array("targets" => array($this->active_index), "action" => $this->action);
432     return $result;
433   }
436   private function deleteEntry($id)
437   {
438     // Remove mapping
439     $index= array_search($id, $this->mapping);
440     if ($index !== false) {
441       unset($this->mapping[$index]);
442       $this->mapping= array_values($this->mapping);
443       $this->modified= true;
444     }
445   }
448   public function getMaintainedData()
449   {
450     $tmp= array();
451     foreach ($this->mapping as $src => $dst) {
452       $realKey  = $this->keys[$dst];
453       $tmp[$realKey] = $this->data[$realKey];
454     }
455     return $tmp;
456   }
459   public function isModified()
460   {
461     return $this->modified;
462   }
465   public function setAcl($acl)
466   {
467     $this->acl= $acl;
468   }
471   public function sortData()
472   {
473     // Extract data
474     $tmp= array();
475     foreach($this->displayData as $item) {
476       if (isset($item[$this->sortColumn])){
477         $tmp[]= $item[$this->sortColumn];
478       } else {
479         $tmp[]= "";
480       }
481     }
483     // Sort entries
484     if ($this->sortDirection[$this->sortColumn]) {
485       asort($tmp);
486     } else {
487       arsort($tmp);
488     }
490     // Adapt mapping accordingly
491     $this->mapping= array();
492     foreach ($tmp as $key => $value) {
493       $this->mapping[]= $key;
494     }
495   }
498   public function addEntry($entry, $displayEntry= null, $key= null)
499   {
500     // Only add if not already there
501     if (!$key) {
502       if (in_array($entry, $this->data)) {
503         return;
504       }
505     } else {
506       if (isset($this->data[$key])) {
507         return;
508       }
509     }
511     // Prefill with default value if not specified
512     if (!$displayEntry) {
513       $displayEntry= array('data' => array($entry));
514     }
516     // Append to data and mapping
517     if ($key) {
518       $this->data[$key]= $entry;
519       $this->keys[]= $key;
520     } else {
521       $this->data[]= $entry;
522       $this->keys[]= count($this->mapping);
523     }
524     $this->displayData[]= $displayEntry['data'];
525     $this->mapping[]= count($this->mapping);
526     $this->modified= true;
528     // Sort data after we've added stuff
529     $this->sortData();
530   }
533   public function getKey($index) {
534     return isset($this->keys[$index])?$this->keys[$index]:null;
535   }