Add sort_name to pluser.
[platal.git] / classes / pltableeditor.php
1 <?php
2 /***************************************************************************
3 * Copyright (C) 2003-2011 Polytechnique.org *
4 * http://opensource.polytechnique.org/ *
5 * *
6 * This program is free software; you can redistribute it and/or modify *
7 * it under the terms of the GNU General Public License as published by *
8 * the Free Software Foundation; either version 2 of the License, or *
9 * (at your option) any later version. *
10 * *
11 * This program is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU General Public License for more details. *
15 * *
16 * You should have received a copy of the GNU General Public License *
17 * along with this program; if not, write to the Free Software *
18 * Foundation, Inc., *
19 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
20 ***************************************************************************/
21
22 class PLTableEditor
23 {
24 // the plat/al name of the page
25 public $pl;
26 // the table name
27 public $table;
28 // joint tables to delete when deleting an entry
29 public $jtables = array();
30 /** joint tables to add optional infos
31 * associative array : keys are the tables names, values are the joint
32 * clauses
33 * @see add_option_fields
34 */
35 public $otables = array();
36 /** optional fields
37 * These fields are used to display additionnal infos in listing (an only
38 * there). The additionnal infos are retreived from other tables. This var
39 * is an associative array : keys are the sql name of the fields
40 * (table.field) where table must be in $otables, values are a list of the
41 * name used in $vars, the description and the type of the field, and the
42 * var it should precede.
43 */
44 public $ofields = array();
45 // sorting field
46 public $sort = array();
47 // the id field
48 public $idfield;
49 // possibility to edit the field
50 public $idfield_editable;
51 // vars
52 public $vars;
53 // number of displayed fields
54 public $nbfields;
55 // a where clause to restrict table
56 public $whereclause;
57 /** Forced values
58 * This is an associative array of (field, value) to enforce.
59 * Only rows where each of the fields has the specified value will
60 * be selected; and added values will use these values for these fields:
61 *
62 * $forced_values = array('foo', 'bar')
63 * => Selects rows with WHERE foo = 'bar'
64 * => Insertions are done with SET foo = 'bar'
65 */
66 public $forced_values = array();
67
68 // the field for sorting entries
69 public $sortfield;
70 public $sortdesc = false;
71 // action to do to delete row:
72 // null => delete effectively, false => no deletion, SQL
73 public $delete_action;
74 public $delete_message;
75 // Should "Save" button return to the list view
76 public $auto_return = true;
77
78 /* table editor for platal
79 * $plname : the PLname of the page, ex: admin/payments
80 * $table : the table to edit, ex: profile_medals
81 * $idfield : the field of the table which is the id, ex: id
82 * $editid : is the id editable or not (if not, it is considered as an int)
83 */
84 public function __construct($plname, $table, $idfield, $editid = false, $idfield2 = false)
85 {
86 $this->pl = $plname;
87 $this->table = $table;
88 $this->idfield = $idfield;
89 $this->idfield2 = $idfield2;
90 $this->sortfield = $idfield;
91 $this->idfield_editable = $editid;
92 $this->whereclause = '1';
93 $r = XDB::iterator("SHOW FULL COLUMNS FROM $table");
94 $this->vars = array();
95 while ($a = $r->next()) {
96 // desc will be the title of the column
97 $a['desc'] = $a['Field'];
98 // display_list decides whether to display the field in 'list' mode
99 $a['display_list'] = true;
100 // display_item decides whether a field is displayed in 'item edition' mode
101 $a['display_item'] = true;
102
103 if (substr($a['Type'],0,8) == 'varchar(') {
104 // limit editing box size
105 $a['Size'] = $a['Maxlength'] = substr($a['Type'], 8, strlen($a['Type']) - 9);
106 if ($a['Size'] > 40) $a['Size'] = 40;
107 // if too big, put a textarea
108 $a['Type'] = ($a['Maxlength']<200)?'varchar':'varchar200';
109 }
110 elseif ($a['Type'] == 'text' || $a['Type'] == 'mediumtext')
111 $a['Type'] = 'textarea';
112 elseif (substr($a['Type'],0,4) == 'set(') {
113 // get the list of options
114 $a['List'] = explode('§',str_replace("','","§",substr($a['Type'], 5, strlen($a['Type']) - 7)));
115 if (count($a['List']) == 1) {
116 $a['Type'] = 'checkbox';
117 $a['Value'] = $a['List'][0];
118 } else {
119 $a['Type'] = 'set';
120 }
121 }
122 elseif (substr($a['Type'],0,5) == 'enum(') {
123 // get the list of options
124 $a['List'] = explode('§',str_replace("','","§",substr($a['Type'], 6, strlen($a['Type']) - 8)));
125 $a['Type'] = 'enum';
126 }
127 elseif (substr($a['Type'],0,10) == 'timestamp(' || $a['Type'] == 'datetime') {
128 $a['Type'] = 'timestamp';
129 }
130 elseif ($a['Comment'] == 'ip_address') {
131 $a['Type']='ip_address';
132 }
133
134 $this->vars[$a['Field']] = $a;
135 }
136 $this->vars[$idfield]['desc'] = 'id';
137 }
138
139 // called before creating a new entry
140 private function prepare_new()
141 {
142 $entry = array();
143 foreach ($this->vars as $field => $descr) {
144 $entry[$field] = $descr['Default'];
145 }
146 return $this->prepare_edit($entry);
147 }
148
149 // called before editing $entry
150 private function prepare_edit(&$entry)
151 {
152 foreach ($this->vars as $field => $descr) {
153 if ($descr['Type'] == 'set') {
154 // get the list of options selected
155 $selected = explode(',', $entry[$field]);
156 $entry[$field] = array();
157 foreach ($selected as $option)
158 $entry[$field][$option] = 1;
159 }
160 if ($descr['Type'] == 'timestamp') {
161 // set readable timestamp
162 $date =& $entry[$field];
163 $date = preg_replace('/([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})/', '\3/\2/\1 \4:\5:\6', $date);
164 }
165 if ($descr['Type'] == 'date') {
166 $date =& $entry[$field];
167 $date = preg_replace('/([0-9]{4})-?([0-9]{2})-?([0-9]{2})/', '\3/\2/\1', $date);
168 }
169 if ($descr['Type'] == 'ip_address') {
170 $ip = & $entry[$field];
171 $ip = long2ip($ip);
172 }
173 }
174 foreach ($this->forced_values as $field => $value) {
175 $entry[$field] = $value;
176 }
177 return $entry;
178 }
179
180 // set whether the save button show redirect to list view or edit view
181 public function list_on_edit($var)
182 {
183 $this->auto_return = $var;
184 }
185
186 // change display of a field
187 public function describe($name, $desc, $display_list, $display_item=true)
188 {
189 $this->vars[$name]['desc'] = $desc;
190 $this->vars[$name]['display_list'] = $display_list;
191 $this->vars[$name]['display_item'] = $display_item;
192 }
193
194 // add a join table, when deleting a row corresponding entries will be deleted in these tables
195 public function add_join_table($name,$joinid,$joindel,$joinextra="")
196 {
197 if ($joindel)
198 $this->jtables[$name] = array("joinid" => $joinid,"joinextra" => $joinextra?(" AND ".$joinextra):"");
199 }
200
201 /** Add optional table
202 * @see add_option_field
203 * @param $name the table sql name
204 * @param $jointclause the full joint clause. Use t as main table alias
205 * name.
206 */
207 public function add_option_table($name, $jointclause)
208 {
209 $this->otables[$name] = $jointclause;
210 }
211
212 /** Add optional field
213 * These fields are used to display additionnal infos in listing (and only
214 * there). The additionnal infos are retreived from other tables.
215 * @param $sqlname is the full sql name (table.field) where table must be
216 * added with add_option_table
217 * @param $name the name used for sort (please make it different from
218 * other fields in main table or subtables)
219 * @param $desc the description displayed as column header
220 * @param $type the typed used for display
221 */
222 public function add_option_field($sqlname, $name, $desc, $type = null, $nextvar = null)
223 {
224 $this->ofields[$sqlname] = array($name, $desc, $type, $nextvar);
225 }
226
227 // add a sort key
228 public function add_sort_field($key, $desc = false, $default = false)
229 {
230 if ($default) {
231 $this->sortfield = $key . ($desc ? ' DESC' : '');
232 } else {
233 $this->sort[] = $key . ($desc ? ' DESC' : '');
234 }
235 }
236
237 // add a link on a field, the field value will be added at the end of the url
238 public function addLink($field, $url) {
239 $this->vars[$field]['url'] = $url;
240 }
241
242 // force the value of a field in select and add
243 public function force_field_value($field, $value)
244 {
245 $this->forced_values[$field] = $value;
246 }
247
248 // add a where clause to limit table listing
249 public function set_where_clause($whereclause="1")
250 {
251 $this->whereclause = $whereclause;
252 }
253
254 // set an action when trying to delete row
255 public function on_delete($action = NULL, $message = NULL)
256 {
257 $this->delete_action = $action;
258 $this->delete_message = $message;
259 }
260
261 /** Retrieve the 'WHERE' clause to use for this PlTableEditor.
262 * Takes into account $this->whereclause and $this->forced_values.
263 *
264 * @param $extra_clause optional extra clause to add to the WHERE
265 * @return The WHERE clause to use
266 */
267 protected function get_where_clause($extra_clause=null)
268 {
269 $parts = array();
270 $parts[] = $this->whereclause;
271 if ($extra_clause !== null) {
272 $parts[] = $extra_clause;
273 }
274 foreach ($this->forced_values as $field => $val) {
275 $parts[] = XDB::format("$field = {?}", $val);
276 }
277 return implode(' AND ', $parts);
278 }
279
280 // call when done
281 public function apply(PlPage $page, $action, $id = false, $id2 = false)
282 {
283 $page->coreTpl('table-editor.tpl');
284 $list = true;
285 if ($action == 'delete' && $id !== false) {
286 S::assert_xsrf_token();
287
288 if (!isset($this->delete_action)) {
289 foreach ($this->jtables as $table => $j)
290 XDB::execute("DELETE FROM {$table} WHERE {$j['joinid']} = {?}{$j['joinextra']}", $id);
291 $where = XDB::format("{$this->idfield} = {?}", $id);
292 if ($this->idfield2) {
293 $where .= XDB::format(" AND {$this->idfield2} = {?}", $id2);
294 }
295 XDB::rawExecute("DELETE FROM {$this->table} WHERE " . $this->get_where_clause($where));
296 $page->trigSuccess("L'entrée " . $id . (($id2) ? '-' . $id2 : '') . ' a été supprimée.');
297 } else if ($this->delete_action) {
298 XDB::execute($this->delete_action, $id);
299 if (isset($this->delete_message)) {
300 $page->trigSuccess($this->delete_message);
301 } else {
302 $page->trigSuccess("L'entrée ".$id." a été supprimée.");
303 }
304 } else {
305 $page->trigError("Impossible de supprimer l'entrée.");
306 }
307 }
308 if ($action == 'edit' && $id !== false) {
309 $r = XDB::query("SELECT * FROM {$this->table} WHERE {$this->idfield} = {?} AND " . $this->get_where_clause(), $id);
310 $entry = $r->fetchOneAssoc();
311 $page->assign('entry', $this->prepare_edit($entry));
312 $page->assign('id', $id);
313 $list = false;
314 }
315 if ($action == 'massadd') {
316 $importer = new CSVImporter($this->table, $this->idfield_editable ? $this->idfield : null);
317 $fields = array();
318 foreach ($this->vars as $field=>$descr) {
319 if ($this->idfield_editable || $field != $this->idfield) {
320 $fields[] = $field;
321 $importer->describe($field, @$descr['desc']);
322 }
323 }
324 foreach ($this->forced_values as $field => $value) {
325 $importer->forceValue($field, $value);
326 }
327 $page->assign('massadd', true);
328 $importer->apply($page, $this->pl . '/massadd', $fields);
329 $list = false;
330 }
331 if ($action == 'new') {
332 if (!$this->idfield_editable) {
333 $page->assign('entry', $this->prepare_new());
334 }
335 $list = false;
336 }
337 if ($action == 'update') {
338 S::assert_xsrf_token();
339
340 $cancel = false;
341 $values = array();
342 $new = false;
343 foreach ($this->vars as $field => $descr) {
344 $val = null;
345 $new = ($id === false || $id === null);
346 if ($field == $this->idfield && !$this->idfield_editable) {
347 if ($new) {
348 $val = XDB::fetchOneCell("SELECT MAX({$field}) + 1
349 FROM {$this->table}");
350 } else {
351 continue;
352 }
353 } elseif (array_key_exists($field, $this->forced_values)) {
354 $val = $this->forced_values[$field];
355 } elseif ($descr['Type'] == 'set') {
356 $val = new PlFlagset();
357 if (Post::has($field)) {
358 foreach (Post::v($field) as $option) {
359 $val->addFlag($option);
360 }
361 }
362 } elseif ($descr['Type'] == 'checkbox') {
363 $val = Post::has($field)? $descr['Value'] : "";
364 } elseif (Post::has($field)) {
365 $val = Post::v($field);
366 if ($descr['Type'] == 'timestamp') {
367 $val = preg_replace('/([0-9]{1,2})\/([0-9]{1,2})\/([0-9]{4}) ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})/', '\3\2\1\4\5\6', $val);
368 } else if ($descr['Type'] == 'date') {
369 $val = preg_replace('/([0-9]{1,2})\/([0-9]{1,2})\/([0-9]{4})/', '\3-\2-\1', $val);
370 } elseif ($descr['Type'] == 'ip_address') {
371 $val = ip2long($val);
372 }
373 } elseif ($descr['display_item']) {
374 $cancel = true;
375 $page->trigError("Il manque le champ ".$field);
376 }
377 $values[$field] = XDB::escape($val);
378 }
379 if (!$cancel) {
380 if (!$new) {
381 $update = array();
382 foreach ($values as $field => $value) {
383 $update[] = $field . ' = ' . $value;
384 }
385 $update = implode(', ', $update);
386 XDB::rawExecute("UPDATE {$this->table}
387 SET {$update}
388 WHERE {$this->idfield} = " . XDB::escape($id) . "
389 AND " . $this->get_where_clause());
390 } else {
391 $fields = implode(', ', array_keys($values));
392 $values = implode(', ', $values);
393 XDB::rawExecute("INSERT INTO {$this->table} ({$fields})
394 VALUES ({$values})");
395 }
396 if ($id !== false && $id !== null) {
397 $page->trigSuccess("L'entrée ".$id." a été mise à jour.");
398 } else {
399 $page->trigSuccess("Une nouvelle entrée a été créée.");
400 $id = XDB::insertId();
401 }
402 } else {
403 $page->trigError("Impossible de mettre à jour.");
404 }
405 if (!$this->auto_return) {
406 return $this->apply($page, 'edit', $id);
407 }
408 }
409 if ($action == 'sort') {
410 $this->sortfield = $id;
411 }
412 if ($action == 'sortdesc') {
413 $this->sortfield = $id.' DESC';
414 }
415 if ($list) {
416 // user can sort by field by clicking the title of the column
417 if (isset($this->sortfield)) {
418 // add this sort order after the others (chosen by dev)
419 $this->add_sort_field($this->sortfield);
420 if (substr($this->sortfield,-5) == ' DESC') {
421 $this->sortfield = substr($this->sortfield,0,-5);
422 $this->sortdesc = true;
423 }
424 }
425 if (count($this->sort) > 0) {
426 $sort = 'ORDER BY ' . join($this->sort, ',');
427 }
428 // optional infos columns
429 $optional_fields = '';
430 if (count($this->ofields)) {
431 $order = array();
432 foreach ($this->vars as $i => $aliasname) {
433 $order[sprintf('%f',count($order))] = $i;
434 }
435 // delta for indexing optional columns between existing ones
436 $changeorder = 0.5;
437 foreach ($this->ofields as $sqlname => $ofieldvalues) {
438 list($aliasname, $desc, $type, $nextvar) = $ofieldvalues;
439 $optional_fields .= ', '.$sqlname.' AS '.$aliasname;
440 $this->describe($aliasname, $desc, true);
441 $this->vars[$aliasname]['optional'] = true;
442 if (isset($type)) {
443 $this->vars[$aliasname]['Type'] = $type;
444 }
445 if (isset($nextvar) && isset($this->vars[$nextvar]) && $nextvar != $aliasname) {
446 $nextkey = array_search($nextvar, $order);
447 $order[sprintf('%f',$nextkey - $changeorder)] = $aliasname;
448 $changeorder = $changeorder / 2;
449 } else {
450 $order[sprintf('%f',count($order))] = $aliasname;
451 }
452 $this->vars[$aliasname]['Field'] = $aliasname;
453 }
454 if ($changeorder != 0.5) {
455 ksort($order);
456 $orderedvars = array();
457 foreach ($order as $aliasname) {
458 $orderedvars[$aliasname] = $this->vars[$aliasname];
459 }
460 $this->vars = $orderedvars;
461 }
462 }
463 $optional_joints = '';
464 foreach ($this->otables as $tablename => $jointclause) {
465 $optional_joints .= ' LEFT JOIN '.$tablename.' ON ('.$jointclause.')';
466 }
467 $it = XDB::iterator("SELECT t.* {$optional_fields} FROM {$this->table} AS t {$optional_joints} WHERE " . $this->get_where_clause() . " $sort");
468 $this->nbfields = 0;
469 foreach ($this->vars as $field => $descr)
470 if ($descr['display_list']) $this->nbfields++;
471 $page->assign('list', $it);
472 }
473 $page->assign('t', $this);
474 }
475 }
476
477 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker fenc=utf-8:
478 ?>