Move the templates required by the core module in the core.
[platal.git] / classes / pltableeditor.php
CommitLineData
e7ae7df9 1<?php
2/***************************************************************************
179afa7f 3 * Copyright (C) 2003-2008 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();
2e7b5921 30 // sorting field
2b1ee50b 31 public $sort = array();
e7ae7df9 32 // the id field
2b1ee50b 33 public $idfield;
e7ae7df9 34 // possibility to edit the field
2b1ee50b 35 public $idfield_editable;
e7ae7df9 36 // vars
2b1ee50b 37 public $vars;
e7ae7df9 38 // number of displayed fields
2b1ee50b 39 public $nbfields;
c57685e7
PC
40 // a where clause to restrict table
41 public $whereclause;
a3828787 42 // the field for sorting entries
2b1ee50b 43 public $sortfield;
44 public $sortdesc = false;
de61dbcf 45 // action to do to delete row:
2b1ee50b 46 // null => delete effectively, false => no deletion, SQL
47 public $delete_action;
48 public $delete_message;
3851b0a6 49 // Should "Save" button return to the list view
2b1ee50b 50 public $auto_return = true;
3851b0a6 51
e7ae7df9 52 /* table editor for platal
53 * $plname : the PLname of the page, ex: admin/payments
54 * $table : the table to edit, ex: profile_medals
55 * $idfield : the field of the table which is the id, ex: id
56 * $editid : is the id editable or not (if not, it is considered as an int)
57 */
2b1ee50b 58 public function __construct($plname, $table, $idfield, $editid=false)
1d10d3fd 59 {
e7ae7df9 60 $this->pl = $plname;
61 $this->table = $table;
62 $this->idfield = $idfield;
a3828787 63 $this->sortfield = $idfield;
e7ae7df9 64 $this->idfield_editable = $editid;
c57685e7 65 $this->whereclause = '1';
669cb0e0 66 $r = XDB::iterator("SHOW FULL COLUMNS FROM $table");
e7ae7df9 67 $this->vars = array();
68 while ($a = $r->next()) {
69 // desc will be the title of the column
70 $a['desc'] = $a['Field'];
71 $a['display'] = true;
6682f91d 72
e7ae7df9 73 if (substr($a['Type'],0,8) == 'varchar(') {
74 // limit editing box size
75 $a['Size'] = $a['Maxlength'] = substr($a['Type'], 8, strlen($a['Type']) - 9);
76 if ($a['Size'] > 40) $a['Size'] = 40;
77 // if too big, put a textarea
78 $a['Type'] = ($a['Maxlength']<200)?'varchar':'varchar200';
79 }
80 elseif ($a['Type'] == 'text' || $a['Type'] == 'mediumtext')
81 $a['Type'] = 'textarea';
82 elseif (substr($a['Type'],0,4) == 'set(') {
83 // get the list of options
a7de4ef7 84 $a['List'] = explode('§',str_replace("','","§",substr($a['Type'], 5, strlen($a['Type']) - 7)));
987f1bd2 85 if (count($a['List']) == 1) {
86 $a['Type'] = 'checkbox';
87 $a['Value'] = $a['List'][0];
88 } else {
89 $a['Type'] = 'set';
eaf30d86 90 }
e7ae7df9 91 }
92 elseif (substr($a['Type'],0,5) == 'enum(') {
93 // get the list of options
a7de4ef7 94 $a['List'] = explode('§',str_replace("','","§",substr($a['Type'], 6, strlen($a['Type']) - 8)));
e7ae7df9 95 $a['Type'] = 'enum';
96 }
b9cd8008 97 elseif (substr($a['Type'],0,10) == 'timestamp(' || $a['Type'] == 'datetime') {
e7ae7df9 98 $a['Type'] = 'timestamp';
99 }
669cb0e0 100 elseif ($a['Comment'] == 'ip_address') {
101 $a['Type']='ip_address';
102 }
e7ae7df9 103
104 $this->vars[$a['Field']] = $a;
105 }
106 $this->vars[$idfield]['desc'] = 'id';
107 }
2b1ee50b 108
1d10d3fd 109 // called before creating a new entry
2b1ee50b 110 private function prepare_new()
1d10d3fd 111 {
112 $entry = array();
113 foreach ($this->vars as $field => $descr) {
114 $entry[$field] = $descr['Default'];
115 }
116 return $this->prepare_edit($entry);
117 }
2b1ee50b 118
e7ae7df9 119 // called before editing $entry
eaf30d86 120 private function prepare_edit(&$entry)
2b1ee50b 121 {
e7ae7df9 122 foreach ($this->vars as $field => $descr) {
123 if ($descr['Type'] == 'set') {
124 // get the list of options selected
125 $selected = explode(',', $entry[$field]);
126 $entry[$field] = array();
127 foreach ($selected as $option)
128 $entry[$field][$option] = 1;
129 }
130 if ($descr['Type'] == 'timestamp') {
131 // set readable timestamp
132 $date =& $entry[$field];
6682f91d 133 $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 134 }
b9cd8008 135 if ($descr['Type'] == 'date') {
136 $date =& $entry[$field];
137 $date = preg_replace('/([0-9]{4})-?([0-9]{2})-?([0-9]{2})/', '\3/\2/\1', $date);
138 }
669cb0e0 139 if ($descr['Type'] == 'ip_address') {
140 $ip = & $entry[$field];
141 $ip = long2ip($ip);
142 }
e7ae7df9 143 }
144 return $entry;
145 }
eaf30d86 146
3851b0a6 147 // set whether the save button show redirect to list view or edit view
2b1ee50b 148 public function list_on_edit($var)
3851b0a6 149 {
150 $this->auto_return = $var;
151 }
2b1ee50b 152
e7ae7df9 153 // change display of a field
2b1ee50b 154 public function describe($name, $desc, $display)
155 {
e7ae7df9 156 $this->vars[$name]['desc'] = $desc;
157 $this->vars[$name]['display'] = $display;
158 }
eaf30d86 159
6682f91d 160 // add a join table, when deleting a row corresponding entries will be deleted in these tables
2b1ee50b 161 public function add_join_table($name,$joinid,$joindel,$joinextra="")
162 {
e7ae7df9 163 if ($joindel)
164 $this->jtables[$name] = array("joinid" => $joinid,"joinextra" => $joinextra?(" AND ".$joinextra):"");
165 }
eaf30d86 166
2e7b5921 167 // add a sort key
2b1ee50b 168 public function add_sort_field($key, $desc = false, $default = false)
2e7b5921 169 {
2b1ee50b 170 if ($default) {
171 $this->sortfield = $key . ($desc ? ' DESC' : '');
172 } else {
173 $this->sort[] = $key . ($desc ? ' DESC' : '');
de61dbcf 174 }
175 }
2b1ee50b 176
c57685e7
PC
177 // add a where clause to limit table listing
178 public function set_where_clause($whereclause="1")
179 {
180 $this->whereclause = $whereclause;
181 }
182
de61dbcf 183 // set an action when trying to delete row
2b1ee50b 184 public function on_delete($action = NULL, $message = NULL)
de61dbcf 185 {
2b1ee50b 186 $this->delete_action = $action;
187 $this->delete_message = $message;
2e7b5921 188 }
2b1ee50b 189
e7ae7df9 190 // call when done
04334c61 191 public function apply(PlPage &$page, $action, $id = false)
2b1ee50b 192 {
7cb40d85 193 $page->coreTpl('table-editor.tpl');
e7ae7df9 194 $list = true;
40d428d8
VZ
195 if ($action == 'delete') {
196 S::assert_xsrf_token();
e61326ed 197
2b1ee50b 198 if (!isset($this->delete_action)) {
199 foreach ($this->jtables as $table => $j)
200 XDB::execute("DELETE FROM {$table} WHERE {$j['joinid']} = {?}{$j['joinextra']}", $id);
201 XDB::execute("DELETE FROM {$this->table} WHERE {$this->idfield} = {?}",$id);
a7d35093 202 $page->trigSuccess("L'entrée ".$id." a été supprimée.");
2b1ee50b 203 } else if ($this->delete_action) {
204 XDB::execute($this->delete_action, $id);
205 if (isset($this->delete_message)) {
a7d35093 206 $page->trigSuccess($this->delete_message);
2b1ee50b 207 } else {
a7d35093 208 $page->trigSuccess("L'entrée ".$id." a été supprimée.");
669cb0e0 209 }
2b1ee50b 210 } else {
a7d35093 211 $page->trigError("Impossible de supprimer l'entrée.");
2b1ee50b 212 }
e7ae7df9 213 }
214 if ($action == 'edit') {
c57685e7 215 $r = XDB::query("SELECT * FROM {$this->table} WHERE {$this->idfield} = {?} AND {$this->whereclause}",$id);
e7ae7df9 216 $entry = $r->fetchOneAssoc();
217 $page->assign('entry', $this->prepare_edit($entry));
218 $page->assign('id', $id);
219 $list = false;
220 }
a6613b2e 221 if ($action == 'massadd') {
222 $importer = new CSVImporter($this->table, $this->idfield_editable ? $this->idfield : null);
223 $fields = array();
224 foreach ($this->vars as $field=>$descr) {
225 if ($this->idfield_editable || $field != $this->idfield) {
226 $fields[] = $field;
227 $importer->describe($field, @$descr['desc']);
228 }
229 }
230 $page->assign('massadd', true);
231 $importer->apply($page, $this->pl . '/massadd', $fields);
232 $list = false;
233 }
e7ae7df9 234 if ($action == 'new') {
235 if (!$this->idfield_editable) {
236 $r = XDB::query("SELECT MAX({$this->idfield})+1 FROM {$this->table}");
237 $page->assign('id', $r->fetchOneCell());
1d10d3fd 238 $page->assign('entry', $this->prepare_new());
e7ae7df9 239 }
240 $list = false;
241 }
40d428d8
VZ
242 if ($action == 'update') {
243 S::assert_xsrf_token();
244
e7ae7df9 245 $values = "";
246 $cancel = false;
247 foreach ($this->vars as $field => $descr) {
248 if ($values) $values .= ',';
249 if (($field == $this->idfield) && !$this->idfield_editable)
250 $val = "'".addslashes($id)."'";
251 elseif ($descr['Type'] == 'set') {
252 $val = "";
253 if (Post::has($field)) foreach (Post::v($field) as $option) {
254 if ($val) $val .= ',';
255 $val .= $option;
256 }
257 $val = "'".addslashes($val)."'";
987f1bd2 258 } elseif ($descr['Type'] == 'checkbox') {
259 $val = Post::has($field)?"'".addslashes($descr['Value'])."'":"''";
e7ae7df9 260 } elseif (Post::has($field)) {
6682f91d 261 $val = Post::v($field);
e7ae7df9 262 if ($descr['Type'] == 'timestamp') {
6682f91d 263 $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);
b9cd8008 264 }
265 elseif ($descr['Type'] == 'date') {
266 $val = preg_replace('/([0-9]{1,2})\/([0-9]{1,2})\/([0-9]{4})/', '\3-\2-\1', $val);
e7ae7df9 267 }
669cb0e0 268 elseif ($descr['Type'] == 'ip_address') {
269 $val = ip2long($val);
270 }
e7ae7df9 271 $val = "'".addslashes($val)."'";
272 } else {
273 $cancel = true;
a7d35093 274 $page->trigError("Il manque le champ ".$field);
e7ae7df9 275 }
276 $values .= $val;
277 }
278 if (!$cancel) {
279 if ($this->idfield_editable && ($id != Post::v($this->idfield)) && $action != 'new')
c57685e7 280 XDB::execute("UPDATE {$this->table} SET {$this->idfield} = {?} WHERE {$this->idfield} = {?} AND {$this->whereclause}", Post::v($this->idfield), $id);
e7ae7df9 281 XDB::execute("REPLACE INTO {$this->table} VALUES ($values)");
282 if ($id !== false)
a7d35093 283 $page->trigSuccess("L'entrée ".$id." a été mise à jour.");
3851b0a6 284 else {
a7d35093 285 $page->trigSuccess("Une nouvelle entrée a été créée.");
3851b0a6 286 $id = XDB::insertId();
287 }
e7ae7df9 288 } else
a7d35093 289 $page->trigError("Impossible de mettre à jour.");
3851b0a6 290 if (!$this->auto_return) {
291 return $this->apply($page, 'edit', $id);
292 }
e7ae7df9 293 }
de61dbcf 294 if ($action == 'sort') {
2b1ee50b 295 $this->sortfield = $id;
de61dbcf 296 }
297 if ($action == 'sortdesc') {
2b1ee50b 298 $this->sortfield = $id.' DESC';
de61dbcf 299 }
e7ae7df9 300 if ($list) {
a3828787 301 // user can sort by field by clicking the title of the column
de61dbcf 302 if (isset($this->sortfield)) {
303 // add this sort order after the others (chosen by dev)
304 $this->add_sort_field($this->sortfield);
386b75ea 305 if (substr($this->sortfield,-5) == ' DESC') {
306 $this->sortfield = substr($this->sortfield,0,-5);
307 $this->sortdesc = true;
308 }
a3828787 309 }
2e7b5921 310 if (count($this->sort) > 0) {
311 $sort = 'ORDER BY ' . join($this->sort, ',');
312 }
c57685e7 313 $it = XDB::iterator("SELECT * FROM {$this->table} WHERE {$this->whereclause} $sort");
e7ae7df9 314 $this->nbfields = 0;
315 foreach ($this->vars as $field => $descr)
316 if ($descr['display']) $this->nbfields++;
317 $page->assign('list', $it);
318 }
319 $page->assign('t', $this);
320 }
321}
322
a7de4ef7 323// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
e7ae7df9 324?>