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