Allow parenthesis before hasPerm in smarty templates
[platal.git] / classes / pltableeditor.php
index 3e35d1a..d847aab 100644 (file)
@@ -1,6 +1,6 @@
 <?php
 /***************************************************************************
- *  Copyright (C) 2003-2010 Polytechnique.org                              *
+ *  Copyright (C) 2003-2011 Polytechnique.org                              *
  *  http://opensource.polytechnique.org/                                   *
  *                                                                         *
  *  This program is free software; you can redistribute it and/or modify   *
@@ -54,6 +54,17 @@ class PLTableEditor
     public $nbfields;
     // a where clause to restrict table
     public $whereclause;
+    /** Forced values
+     * This is an associative array of (field, value) to enforce.
+     * Only rows where each of the fields has the specified value will
+     * be selected; and added values will use these values for these fields:
+     *
+     * $forced_values = array('foo', 'bar')
+     * => Selects rows with WHERE foo = 'bar'
+     * => Insertions are done with SET foo = 'bar'
+     */
+    public $forced_values = array();
+
     // the field for sorting entries
     public $sortfield;
     public $sortdesc = false;
@@ -70,11 +81,12 @@ class PLTableEditor
      * $idfield : the field of the table which is the id, ex: id
      * $editid : is the id editable or not (if not, it is considered as an int)
      */
-    public function __construct($plname, $table, $idfield, $editid=false)
+    public function __construct($plname, $table, $idfield, $editid = false, $idfield2 = false)
     {
         $this->pl = $plname;
         $this->table = $table;
         $this->idfield = $idfield;
+        $this->idfield2 = $idfield2;
         $this->sortfield = $idfield;
         $this->idfield_editable = $editid;
         $this->whereclause = '1';
@@ -83,7 +95,10 @@ class PLTableEditor
         while ($a = $r->next()) {
             // desc will be the title of the column
             $a['desc'] = $a['Field'];
-            $a['display'] = true;
+            // display_list decides whether to display the field in 'list' mode
+            $a['display_list'] = true;
+            // display_item decides whether a field is displayed in 'item edition' mode
+            $a['display_item'] = true;
 
             if (substr($a['Type'],0,8) == 'varchar(') {
                 // limit editing box size
@@ -156,6 +171,9 @@ class PLTableEditor
                 $ip = long2ip($ip);
             }
         }
+        foreach ($this->forced_values as $field => $value) {
+            $entry[$field] = $value;
+        }
         return $entry;
     }
 
@@ -166,10 +184,11 @@ class PLTableEditor
     }
 
     // change display of a field
-    public function describe($name, $desc, $display)
+    public function describe($name, $desc, $display_list, $display_item=true)
     {
         $this->vars[$name]['desc'] = $desc;
-        $this->vars[$name]['display'] = $display;
+        $this->vars[$name]['display_list'] = $display_list;
+        $this->vars[$name]['display_item'] = $display_item;
     }
 
     // add a join table, when deleting a row corresponding entries will be deleted in these tables
@@ -215,12 +234,23 @@ class PLTableEditor
         }
     }
 
+    // add a link on a field, the field value will be added at the end of the url
+    public function addLink($field, $url) {
+        $this->vars[$field]['url'] = $url;
+    }
+
+    // force the value of a field in select and add
+    public function force_field_value($field, $value)
+    {
+        $this->forced_values[$field] = $value;
+    }
+
     // add a where clause to limit table listing
     public function set_where_clause($whereclause="1")
     {
         $this->whereclause = $whereclause;
     }
-    
+
     // set an action when trying to delete row
     public function on_delete($action = NULL, $message = NULL)
     {
@@ -228,8 +258,27 @@ class PLTableEditor
         $this->delete_message = $message;
     }
 
+    /** Retrieve the 'WHERE' clause to use for this PlTableEditor.
+     * Takes into account $this->whereclause and $this->forced_values.
+     *
+     * @param $extra_clause optional extra clause to add to the WHERE
+     * @return The WHERE clause to use
+     */
+    protected function get_where_clause($extra_clause=null)
+    {
+        $parts = array();
+        $parts[] = $this->whereclause;
+        if ($extra_clause !== null) {
+            $parts[] = $extra_clause;
+        }
+        foreach ($this->forced_values as $field => $val) {
+            $parts[] = XDB::format("$field = {?}", $val);
+        }
+        return implode(' AND ', $parts);
+    }
+
     // call when done
-    public function apply(PlPage &$page, $action, $id = false)
+    public function apply(PlPage $page, $action, $id = false, $id2 = false)
     {
         $page->coreTpl('table-editor.tpl');
         $list = true;
@@ -239,8 +288,12 @@ class PLTableEditor
             if (!isset($this->delete_action)) {
                 foreach ($this->jtables as $table => $j)
                     XDB::execute("DELETE FROM {$table} WHERE {$j['joinid']} = {?}{$j['joinextra']}", $id);
-                XDB::execute("DELETE FROM {$this->table} WHERE {$this->idfield} = {?}",$id);
-                $page->trigSuccess("L'entrée ".$id." a été supprimée.");
+                $where = XDB::format("{$this->idfield} = {?}", $id);
+                if ($this->idfield2) {
+                    $where .= XDB::format(" AND {$this->idfield2} = {?}", $id2);
+                }
+                XDB::rawExecute("DELETE FROM {$this->table} WHERE " . $this->get_where_clause($where));
+                $page->trigSuccess("L'entrée " . $id . (($id2) ? '-' . $id2 : '') . ' a été supprimée.');
             } else if ($this->delete_action) {
                 XDB::execute($this->delete_action, $id);
                 if (isset($this->delete_message)) {
@@ -253,7 +306,7 @@ class PLTableEditor
             }
         }
         if ($action == 'edit' && $id !== false) {
-            $r = XDB::query("SELECT * FROM {$this->table} WHERE {$this->idfield} = {?} AND {$this->whereclause}",$id);
+            $r = XDB::query("SELECT * FROM {$this->table} WHERE {$this->idfield} = {?} AND " . $this->get_where_clause(), $id);
             $entry = $r->fetchOneAssoc();
             $page->assign('entry', $this->prepare_edit($entry));
             $page->assign('id', $id);
@@ -268,6 +321,9 @@ class PLTableEditor
                     $importer->describe($field, @$descr['desc']);
                 }
             }
+            foreach ($this->forced_values as $field => $value) {
+                $importer->forceValue($field, $value);
+            }
             $page->assign('massadd', true);
             $importer->apply($page, $this->pl . '/massadd', $fields);
             $list = false;
@@ -281,55 +337,71 @@ class PLTableEditor
         if ($action == 'update') {
             S::assert_xsrf_token();
 
-            $values = "";
             $cancel = false;
+            $values = array();
+            $new = false;
             foreach ($this->vars as $field => $descr) {
-                if ($values) $values .= ',';
-                if (($field == $this->idfield) && !$this->idfield_editable) {
-                    if ($id === false || $id === null) {
-                        $val = "'".addslashes(XDB::fetchOneCell("SELECT MAX( {$field} ) + 1 FROM {$this->table}"))."'";
+                $val = null;
+                $new = ($id === false || $id === null);
+                if ($field == $this->idfield && !$this->idfield_editable) {
+                    if ($new) {
+                        $val = XDB::fetchOneCell("SELECT MAX({$field}) + 1
+                                                    FROM {$this->table}");
                     } else {
-                        $val = "'".addslashes($id)."'";
+                        continue;
                     }
+                } elseif (array_key_exists($field, $this->forced_values)) {
+                    $val = $this->forced_values[$field];
                 } elseif ($descr['Type'] == 'set') {
-                    $val = "";
-                    if (Post::has($field)) foreach (Post::v($field) as $option) {
-                        if ($val) $val .= ',';
-                        $val .= $option;
+                    $val = new PlFlagset();
+                    if (Post::has($field)) {
+                        foreach (Post::v($field) as $option) {
+                            $val->addFlag($option);
+                        }
                     }
-                    $val = "'".addslashes($val)."'";
                 } elseif ($descr['Type'] == 'checkbox') {
-                    $val = Post::has($field)?"'".addslashes($descr['Value'])."'":"''";
+                    $val = Post::has($field)? $descr['Value'] : "";
                 } elseif (Post::has($field)) {
                     $val = Post::v($field);
                     if ($descr['Type'] == 'timestamp') {
                         $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);
-                    }
-                    elseif ($descr['Type'] == 'date') {
+                    } else if ($descr['Type'] == 'date') {
                         $val = preg_replace('/([0-9]{1,2})\/([0-9]{1,2})\/([0-9]{4})/', '\3-\2-\1', $val);
-                    }
-                    elseif ($descr['Type'] == 'ip_address') {
+                    } elseif ($descr['Type'] == 'ip_address') {
                         $val = ip2long($val);
                     }
-                    $val = "'".addslashes($val)."'";
-                } else {
+                } elseif ($descr['display_item']) {
                     $cancel = true;
                     $page->trigError("Il manque le champ ".$field);
                 }
-                $values .= $val;
+                $values[$field] = XDB::escape($val);
             }
             if (!$cancel) {
-                if ($this->idfield_editable && $id != Post::v($this->idfield))
-                    XDB::execute("UPDATE {$this->table} SET {$this->idfield} = {?} WHERE {$this->idfield} = {?} AND {$this->whereclause}", Post::v($this->idfield), $id);
-                XDB::execute("REPLACE INTO {$this->table} VALUES ($values)");
+                if (!$new) {
+                    $update = array();
+                    foreach ($values as $field => $value) {
+                        $update[] = $field . ' = ' . $value;
+                    }
+                    $update = implode(', ', $update);
+                    XDB::rawExecute("UPDATE {$this->table}
+                                        SET {$update}
+                                      WHERE {$this->idfield} = " . XDB::escape($id) . "
+                                      AND " . $this->get_where_clause());
+                } else {
+                    $fields = implode(', ', array_keys($values));
+                    $values = implode(', ', $values);
+                    XDB::rawExecute("INSERT INTO  {$this->table} ({$fields})
+                                          VALUES  ({$values})");
+                }
                 if ($id !== false && $id !== null) {
                     $page->trigSuccess("L'entrée ".$id." a été mise à jour.");
                 } else {
                     $page->trigSuccess("Une nouvelle entrée a été créée.");
                     $id = XDB::insertId();
                 }
-            } else
+            } else {
                 $page->trigError("Impossible de mettre à jour.");
+            }
             if (!$this->auto_return) {
                 return $this->apply($page, 'edit', $id);
             }
@@ -392,15 +464,15 @@ class PLTableEditor
             foreach ($this->otables as $tablename => $jointclause) {
                 $optional_joints .= ' LEFT JOIN '.$tablename.' ON ('.$jointclause.')';
             }
-            $it = XDB::iterator("SELECT t.* {$optional_fields} FROM {$this->table} AS t {$optional_joints} WHERE {$this->whereclause} $sort");
+            $it = XDB::iterator("SELECT t.* {$optional_fields} FROM {$this->table} AS t {$optional_joints} WHERE " . $this->get_where_clause() . " $sort");
             $this->nbfields = 0;
             foreach ($this->vars as $field => $descr)
-                if ($descr['display']) $this->nbfields++;
+                if ($descr['display_list']) $this->nbfields++;
             $page->assign('list', $it);
         }
         $page->assign('t', $this);
     }
 }
 
-// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
+// vim:set et sw=4 sts=4 sws=4 foldmethod=marker fenc=utf-8:
 ?>