Code

Do not reset the sorting direction and column when new listData is added
[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(microtime().$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       trigger_error ("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         if(!isset($this->sortDirection[$column])){
131             $this->sortDirection[$column]= true;
132         }
133     }
134   }
137   public function setWidth($width)
138   {
139     $this->width= $width;
140   }
143   public function setInstantDelete($flag)
144   {
145     $this->instantDelete= $flag;
146   }
149   public function setColorAlternate($flag)
150   {
151     $this->colorAlternate= $flag;
152   }
155   public function setEditable($flag)
156   {
157     $this->editable= $flag;
158   }
161   public function setDeleteable($flag)
162   {
163     $this->deleteable= $flag;
164   }
167   public function setHeight($height)
168   {
169     $this->height= $height;
170   }
173   public function setCssClass($css)
174   {
175     $this->cssclass= $css;
176   }
179   public function setHeader($header)
180   {
181     $this->header= $header;
182   }
185   public function setColspecs($specs)
186   {
187     $this->colspecs= $specs;
188   }
191   public function render()
192   {
193     $result= "<div class='sortableListContainer' id='scroll_".$this->id."' style='min-width:".$this->width.";height: ".$this->height."'>\n";
194     $result.= "<table summary='"._("Sortable list")."' border='0' cellpadding='0' cellspacing='0' width='100%' style='width:100%' ".(!empty($this->cssclass)?" class='".$this->cssclass."'":"").">\n";
195     $action_width= 0;
196     if (strpos($this->acl, 'w') === false) {
197       $edit_image= $this->editable?image("images/lists/edit-grey.png"):"";
198     } else {
199       $edit_image= $this->editable?image('images/lists/edit.png', "%ID", _("Edit this entry")):"";
200     }
201     if (strpos($this->acl, 'd') === false) {
202       $delete_image= $this->deleteable?image('images/lists/trash-grey.png'):"";
203     } else {
204       $delete_image= $this->deleteable?image('images/lists/trash.png', "%ID", _("Delete this entry")):"";
205     }
207     // Do we need colspecs?
208     $action_width= ($this->editable?20:0) + ($this->deleteable?20:0);
209     if ($this->colspecs) {
210       $result.= " <colgroup>\n";
211       for ($i= 0; $i<$this->columns; $i++) {
212         if(isset($this->colspecs[$i]) && $this->colspecs[$i] != '*'){
213           $result.= "  <col style='width:".($this->colspecs[$i])."'>\n";
214         }else{
215           $result.= "  <col>\n";
216         }
217       }
219       // Extend by another column if we've actions specified
220       if ($action_width) {
221         $result.= "  <col style='width:".$action_width."px' >\n";
222       }
223       $result.= " </colgroup>\n";
224     }
226     // Do we need a header?
227     if ($this->header) {
228       $result.= " <thead>\n  <tr>\n";
229       $first= " style='border-left:0'";
230       for ($i= 0; $i<$this->columns; $i++) {
231         $link= "href='?plug=".$_GET['plug']."&amp;PID=".$this->id."&amp;act=SORT_$i'";
232         $sorter= "";
233         if ($i == $this->sortColumn){
234           $sorter= "&nbsp;".image("images/lists/sort-".($this->sortDirection[$i]?"up":"down").".png", null, $this->sortDirection[$i]?_("Up"):_("Down"));
235         }
237         if ($this->reorderable) {
238           $result.= "   <th$first>".(isset($this->header[$i])?$this->header[$i]:"")."</th>";
239         } else {
240           $result.= "   <th$first><a $link>".(isset($this->header[$i])?$this->header[$i]:"")."</a>$sorter</th>";
241         }
242         $first= "";
243       }
244       if ($action_width) {
245         $result.= "<th>&nbsp;</th>";
246       }
247       $result.= "\n  </tr>\n </thead>\n";
248     }
250     // Render table body if we've read permission
251     $result.= " <tbody id='".$this->id."'>\n";
252     $reorderable= $this->reorderable?"":" style='cursor:default'";
253     if (strpos($this->acl, 'r') !== false) {
254       foreach ($this->mapping as $nr => $row) {
255         $editable= $this->editable?" onClick='$(\"edit_".$this->id."_$nr\").click()'":"";
257         $id= "";
258         if (isset($this->modes[$row])) {
259           switch ($this->modes[$row]) {
260             case LIST_DISABLED:
261               $id= " sortableListItemDisabled";
262               $editable= "";
263               break;
264             case LIST_MARKED:
265               $id= " sortableListItemMarked";
266               break;
267           }
268         }
270         $result.= "  <tr class='sortableListItem".((($nr&1)||!$this->colorAlternate)?'':'Odd')."$id' id='item_".$this->id."_$nr'$reorderable>\n";
271         $first= " style='border:0'";
273         foreach ($this->displayData[$row] as $column) {
274           $result.= "   <td$editable$first>".$column."</td>\n";
275           $first= "";
276         }
278         if ($action_width) {
279           $result.= "<td>".str_replace('%ID', "edit_".$this->id."_$nr", $edit_image).
280                            str_replace('%ID', "del_".$this->id."_$nr", $delete_image)."</td>";
281         }
283         $result.= "  </tr>\n";
284       }
285     }
287     // Add spacer
288     $result.= "  <tr class='sortableListItemFill' style='height:100%'><td style='border:0'></td>";
289     $num= $action_width?$this->columns:$this->columns-1;
290     for ($i= 0; $i<$num; $i++) {
291       $result.= "<td class='sortableListItemFill'></td>";
292     }
293     $result.= "</tr>\n";
295     $result.= " </tbody>\n</table>\n</div>\n";
296 #    $result.= " <input type='hidden' name='PID' value='".$this->id."' id='PID'>\n";
297     $result.= " <input type='hidden' name='position_".$this->id."' id='position_".$this->id."'>\n";
298     $result.= " <input type='hidden' name='reorder_".$this->id."' id='reorder_".$this->id."'>\n";
300     // Append script stuff if needed
301     $result.= '<script type="text/javascript" language="javascript">';
302     if ($this->reorderable) {
303       $result.= ' function updateOrder(){';
304       $result.= '    var ampcharcode= \'%26\';';
305       $result.= '    var serializeOpts = Sortable.serialize(\''.$this->id.'\')+"='.$this->id.'";';
306       $result.= '    $("reorder_'.$this->id.'").value= serializeOpts;';
307       $result.= '    document.mainform.submit();';
308       $result.= ' }';
309       $result.= 'Position.includeScrollOffsets = true;';
310       $result.= ' Sortable.create(\''.$this->id.'\',{tag:\'tr\', ghosting:false, constraint:\'vertical\', scroll:\'scroll_'.$this->id.'\',onUpdate : updateOrder});';
311     }
312     $result.= '$("scroll_'.$this->id.'").scrollTop= '.$this->scrollPosition.';';
313     $result.= 'var box = $("scroll_'.$this->id.'").onscroll= function() {$("position_'.$this->id.'").value= this.scrollTop;}';
314     $result.= '</script>';
316     return $result;
317   }
320   public function update()
321   {
322     // Do not do anything if this is not our PID, or there's even no PID available...
323     if(isset($_REQUEST['PID']) && $_REQUEST['PID'] != $this->id) {
324       return;
325     }
327     // Filter GET with "act" attributes
328     if (!$this->reorderable){
329       if(isset($_GET['act'])) {
330         $key= validate($_GET['act']);
331         if (preg_match('/^SORT_([0-9]+)$/', $key, $match)) {
332           // Switch to new column or invert search order?
333           $column= $match[1];
334           if ($this->sortColumn != $column) {
335             $this->sortColumn= $column;
336           } else {
337             $this->sortDirection[$column]= !$this->sortDirection[$column];
338           }
340         }
341       }
343       // Update mapping according to sort parameters
344       $this->sortData();
345     }
346   }
349   public function save_object()
350   {
351     // Do not do anything if this is not our PID, or there's even no PID available...
352     if(isset($_REQUEST['PID']) && $_REQUEST['PID'] != $this->id) {
353       return;
354     }
356     // Do not do anything if we're not posted - or have no permission
357     if (strpos($this->acl, 'w') !== false && isset($_POST['reorder_'.$this->id])){
359       if (isset($_POST['position_'.$this->id]) && is_numeric($_POST['position_'.$this->id])) {
360         $this->scrollPosition= $_POST['position_'.$this->id];
361       }
363       // Move requested?
364       $move= $_POST['reorder_'.$this->id];
365       if ($move != "") {
366         preg_match_all('/=([0-9]+)[&=]/', $move, $matches);
367         $this->action= "reorder";
368         $tmp= array();
369         foreach ($matches[1] as $id => $row) {
370           $tmp[$id]= $this->mapping[$row];
371         }
372         $this->mapping= $tmp;
373         $this->current_mapping= $matches[1];
374         $this->modified= true;
375         return;
376       }
377     }
379     // Delete requested?
380     $this->action = "";
381     if (strpos($this->acl, 'd') !== false){
382       foreach ($_POST as $key => $value) {
383         if (preg_match('/^del_'.$this->id.'_([0-9]+)$/', $key, $matches)) {
384           $this->active_index= $this->mapping[$matches[1]];
386           // Ignore request if mode requests it
387           if (isset($this->modes[$this->active_index]) && $this->modes[$this->active_index] == LIST_DISABLED) {
388             $this->active_index= null;
389             continue;
390           }
392           // Set action
393           $this->action= "delete";
395           // Remove value if requested
396           if ($this->instantDelete) {
397             $this->deleteEntry($this->active_index);
398           }
399         }
400       }
401     }
403     // Edit requested?
404     if (strpos($this->acl, 'w') !== false){
405       foreach ($_POST as $key => $value) {
406         if (preg_match('/^edit_'.$this->id.'_([0-9]+)$/', $key, $matches)) {
407           $this->active_index= $this->mapping[$matches[1]];
409           // Ignore request if mode requests it
410           if (isset($this->modes[$this->active_index]) && $this->modes[$this->active_index] == LIST_DISABLED) {
411             $this->active_index= null;
412             continue;
413           }
415           $this->action= "edit";
416         }
417       }
418     }
419   }
422   public function getAction()
423   {
424     // Do not do anything if we're not posted
425     if(!isset($_POST['reorder_'.$this->id])) {
426       return;
427     }
429     // For reordering, return current mapping
430     if ($this->action == 'reorder') {
431       return array("targets" => $this->current_mapping, "mapping" => $this->mapping, "action" => $this->action);
432     }
434     // Edit and delete
435     $result= array("targets" => array($this->active_index), "action" => $this->action);
437     return $result;
438   }
441   private function deleteEntry($id)
442   {
443     // Remove mapping
444     $index= array_search($id, $this->mapping);
445     if ($index !== false) {
446       unset($this->mapping[$index]);
447       $this->mapping= array_values($this->mapping);
448       $this->modified= true;
449     }
450   }
453   public function getMaintainedData()
454   {
455     $tmp= array();
456     foreach ($this->mapping as $src => $dst) {
457       $realKey  = $this->keys[$dst];
458       $tmp[$realKey] = $this->data[$realKey];
459     }
460     return $tmp;
461   }
464   public function isModified()
465   {
466     return $this->modified;
467   }
470   public function setAcl($acl)
471   {
472     $this->acl= $acl;
473   }
476   public function sortData()
477   {
478     // Extract data
479     $tmp= array();
480     foreach($this->displayData as $item) {
481       if (isset($item[$this->sortColumn])){
482         $tmp[]= $item[$this->sortColumn];
483       } else {
484         $tmp[]= "";
485       }
486     }
488     // Sort entries
489     if ($this->sortDirection[$this->sortColumn]) {
490       asort($tmp);
491     } else {
492       arsort($tmp);
493     }
495     // Adapt mapping accordingly
496     $this->mapping= array();
497     foreach ($tmp as $key => $value) {
498       $this->mapping[]= $key;
499     }
500   }
503   public function addEntry($entry, $displayEntry= null, $key= null)
504   {
505     // Only add if not already there
506     if (!$key) {
507       if (in_array($entry, $this->data)) {
508         return;
509       }
510     } else {
511       if (isset($this->data[$key])) {
512         return;
513       }
514     }
516     // Prefill with default value if not specified
517     if (!$displayEntry) {
518       $displayEntry= array('data' => array($entry));
519     }
521     // Append to data and mapping
522     if ($key) {
523       $this->data[$key]= $entry;
524       $this->keys[]= $key;
525     } else {
526       $this->data[]= $entry;
527       $this->keys[]= count($this->mapping);
528     }
529     $this->displayData[]= $displayEntry['data'];
530     $this->mapping[]= count($this->mapping);
531     $this->modified= true;
533     // Sort data after we've added stuff
534     $this->sortData();
535   }
538   public function getKey($index) {
539     return isset($this->keys[$index])?$this->keys[$index]:null;
540   }
542   public function getData($index) {
543     $realkey = $this->keys[$index];
544     return($this->data[$realkey]);
545   }