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