Add forced values to PlTableEditor.
[platal.git] / classes / pltableeditor.php
index c849f37..c114a02 100644 (file)
@@ -1,6 +1,6 @@
 <?php
 /***************************************************************************
- *  Copyright (C) 2003-2006 Polytechnique.org                              *
+ *  Copyright (C) 2003-2011 Polytechnique.org                              *
  *  http://opensource.polytechnique.org/                                   *
  *                                                                         *
  *  This program is free software; you can redistribute it and/or modify   *
  *  59 Temple Place, Suite 330, Boston, MA  02111-1307  USA                *
  ***************************************************************************/
 
-class PLTableEditor {
+class PLTableEditor
+{
     // the plat/al name of the page
-    var $pl;
+    public $pl;
     // the table name
-    var $table;
+    public $table;
     // joint tables to delete when deleting an entry
-    var $jtables = array();
+    public $jtables = array();
+    /** joint tables to add optional infos
+     * associative array : keys are the tables names, values are the joint
+     * clauses
+     * @see add_option_fields
+     */
+    public $otables = array();
+    /** optional fields
+     * These fields are used to display additionnal infos in listing (an only
+     * there). The additionnal infos are retreived from other tables. This var
+     * is an associative array : keys are the sql name of the fields
+     * (table.field) where table must be in $otables, values are a list of the
+     * name used in $vars, the description and the type of the field, and the
+     * var it should precede.
+     */
+    public $ofields = array();
     // sorting field
-    var $sort = array();
+    public $sort = array();
     // the id field
-    var $idfield;
+    public $idfield;
     // possibility to edit the field
-    var $idfield_editable;
+    public $idfield_editable;
     // vars
-    var $vars;
+    public $vars;
     // number of displayed fields
-    var $nbfields;
+    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
-    var $sortfield;
-    var $sortdesc = false;
+    public $sortfield;
+    public $sortdesc = false;
     // action to do to delete row:
-       // null => delete effectively, false => no deletion, SQL
-    var $delete_action;
-    var $delete_message;
+    // null => delete effectively, false => no deletion, SQL
+    public $delete_action;
+    public $delete_message;
+    // Should "Save" button return to the list view
+    public $auto_return = true;
+
     /* table editor for platal
      * $plname : the PLname of the page, ex: admin/payments
      * $table : the table to edit, ex: profile_medals
      * $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)
      */
-    function PLTableEditor($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;
-        $r = XDB::iterator("SHOW COLUMNS FROM $table");
+        $this->whereclause = '1';
+        $r = XDB::iterator("SHOW FULL COLUMNS FROM $table");
         $this->vars = array();
         while ($a = $r->next()) {
             // desc will be the title of the column
@@ -74,24 +108,33 @@ class PLTableEditor {
                 $a['Type'] = 'textarea';
             elseif (substr($a['Type'],0,4) == 'set(') {
                 // get the list of options
-                $a['List'] = explode('§',str_replace("','","§",substr($a['Type'], 5, strlen($a['Type']) - 7)));
-                $a['Type'] = 'set';
+                $a['List'] = explode('§',str_replace("','","§",substr($a['Type'], 5, strlen($a['Type']) - 7)));
+                if (count($a['List']) == 1) {
+                    $a['Type'] = 'checkbox';
+                    $a['Value'] = $a['List'][0];
+                } else {
+                    $a['Type'] = 'set';
+                }
             }
             elseif (substr($a['Type'],0,5) == 'enum(') {
                 // get the list of options
-                $a['List'] = explode('§',str_replace("','","§",substr($a['Type'], 6, strlen($a['Type']) - 8)));
+                $a['List'] = explode('§',str_replace("','","§",substr($a['Type'], 6, strlen($a['Type']) - 8)));
                 $a['Type'] = 'enum';
             }
             elseif (substr($a['Type'],0,10) == 'timestamp(' || $a['Type'] == 'datetime') {
                 $a['Type'] = 'timestamp';
             }
+            elseif ($a['Comment'] == 'ip_address') {
+                $a['Type']='ip_address';
+            }
 
             $this->vars[$a['Field']] = $a;
         }
         $this->vars[$idfield]['desc'] = 'id';
     }
+
     // called before creating a new entry
-    function prepare_new()
+    private function prepare_new()
     {
         $entry = array();
         foreach ($this->vars as $field => $descr) {
@@ -99,8 +142,10 @@ class PLTableEditor {
         }
         return $this->prepare_edit($entry);
     }
+
     // called before editing $entry
-    function prepare_edit(&$entry) {
+    private function prepare_edit(&$entry)
+    {
         foreach ($this->vars as $field => $descr) {
             if ($descr['Type'] == 'set') {
                 // get the list of options selected
@@ -118,115 +163,245 @@ class PLTableEditor {
                 $date =& $entry[$field];
                 $date = preg_replace('/([0-9]{4})-?([0-9]{2})-?([0-9]{2})/', '\3/\2/\1', $date);
             }
+            if ($descr['Type'] == 'ip_address') {
+                $ip = & $entry[$field];
+                $ip = long2ip($ip);
+            }
+        }
+        foreach ($this->forced_values as $field => $value) {
+            $entry[$field] = $value;
         }
         return $entry;
     }
+
+    // set whether the save button show redirect to list view or edit view
+    public function list_on_edit($var)
+    {
+        $this->auto_return = $var;
+    }
+
     // change display of a field
-    function describe($name, $desc, $display) {
+    public function describe($name, $desc, $display)
+    {
         $this->vars[$name]['desc'] = $desc;
         $this->vars[$name]['display'] = $display;
     }
+
     // add a join table, when deleting a row corresponding entries will be deleted in these tables
-    function add_join_table($name,$joinid,$joindel,$joinextra="") {
+    public function add_join_table($name,$joinid,$joindel,$joinextra="")
+    {
         if ($joindel)
             $this->jtables[$name] = array("joinid" => $joinid,"joinextra" => $joinextra?(" AND ".$joinextra):"");
     }
+
+    /** Add optional table
+     * @see add_option_field
+     * @param $name the table sql name
+     * @param $jointclause the full joint clause. Use t as main table alias
+     * name.
+     */
+    public function add_option_table($name, $jointclause)
+    {
+        $this->otables[$name] = $jointclause;
+    }
+
+    /** Add optional field
+     * These fields are used to display additionnal infos in listing (and only
+     * there). The additionnal infos are retreived from other tables.
+     * @param $sqlname is the full sql name (table.field) where table must be
+     * added with add_option_table
+     * @param $name the name used for sort (please make it different from
+     * other fields in main table or subtables)
+     * @param $desc the description displayed as column header
+     * @param $type the typed used for display
+     */
+    public function add_option_field($sqlname, $name, $desc, $type = null, $nextvar = null)
+    {
+        $this->ofields[$sqlname] = array($name, $desc, $type, $nextvar);
+    }
+
     // add a sort key
-    function add_sort_field($key, $desc = false, $default = false)
+    public function add_sort_field($key, $desc = false, $default = false)
     {
-       if ($default) {
-                       $this->sortfield = $key . ($desc ? ' DESC' : '');
-               } else {
-               $this->sort[] = $key . ($desc ? ' DESC' : '');
+        if ($default) {
+            $this->sortfield = $key . ($desc ? ' DESC' : '');
+        } else {
+            $this->sort[] = $key . ($desc ? ' DESC' : '');
         }
     }
+
+    // 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
-    function on_delete($action = NULL, $message = NULL)
+    public function on_delete($action = NULL, $message = NULL)
     {
-       $this->delete_action = $action;
-       $this->delete_message = $message;
+        $this->delete_action = $action;
+        $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
-    function apply(&$page, $action, $id = false) {
-        $page->changeTpl('table-editor.tpl');
+    public function apply(PlPage $page, $action, $id = false, $id2 = false)
+    {
+        $page->coreTpl('table-editor.tpl');
         $list = true;
-        if ($action == 'delete') {
-               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->trig("L'entrée ".$id." a été supprimée.");
-               } else if ($this->delete_action) {
-                       XDB::execute($this->delete_action, $id);
-                       if (isset($this->delete_message)) {
-                       $page->trig($this->delete_message);
-                       } else {
-                       $page->trig("L'entrée ".$id." a été supprimée.");
-                               }                       
-               } else {
-                   $page->trig("Impossible de supprimer l'entrée.");
-               }
+        if ($action == 'delete' && $id !== false) {
+            S::assert_xsrf_token();
+
+            if (!isset($this->delete_action)) {
+                foreach ($this->jtables as $table => $j)
+                    XDB::execute("DELETE FROM {$table} WHERE {$j['joinid']} = {?}{$j['joinextra']}", $id);
+                $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)) {
+                    $page->trigSuccess($this->delete_message);
+                } else {
+                    $page->trigSuccess("L'entrée ".$id." a été supprimée.");
+                }
+            } else {
+                $page->trigError("Impossible de supprimer l'entrée.");
+            }
         }
-        if ($action == 'edit') {
-            $r = XDB::query("SELECT * FROM {$this->table} WHERE {$this->idfield} = {?}",$id);
+        if ($action == 'edit' && $id !== false) {
+            $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);
             $list = false;
         }
+        if ($action == 'massadd') {
+            $importer = new CSVImporter($this->table, $this->idfield_editable ? $this->idfield : null);
+            $fields   = array();
+            foreach ($this->vars as $field=>$descr) {
+                if ($this->idfield_editable || $field != $this->idfield) {
+                    $fields[] = $field;
+                    $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;
+        }
         if ($action == 'new') {
             if (!$this->idfield_editable) {
-                $r = XDB::query("SELECT MAX({$this->idfield})+1 FROM {$this->table}");
-                $page->assign('id', $r->fetchOneCell());
                 $page->assign('entry', $this->prepare_new());
             }
             $list = false;
         }
         if ($action == 'update') {
-            $values = "";
+            S::assert_xsrf_token();
+
             $cancel = false;
+            $values = array();
+            $new = false;
             foreach ($this->vars as $field => $descr) {
-                if ($values) $values .= ',';
-                if (($field == $this->idfield) && !$this->idfield_editable)
-                    $val = "'".addslashes($id)."'";
-                elseif ($descr['Type'] == 'set') {
-                    $val = "";
-                    if (Post::has($field)) foreach (Post::v($field) as $option) {
-                        if ($val) $val .= ',';
-                        $val .= $option;
+                $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 {
+                        continue;
+                    }
+                } elseif (array_key_exists($field, $this->forced_values)) {
+                    $val = $this->forced_values[$field];
+                } elseif ($descr['Type'] == 'set') {
+                    $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)? $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') {
+                        $val = ip2long($val);
                     }
-                    $val = "'".addslashes($val)."'";
                 } else {
                     $cancel = true;
-                    $page->trig("Il manque le champ ".$field);
+                    $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)) && $action != 'new')
-                    XDB::execute("UPDATE {$this->table} SET {$this->idfield} = {?} WHERE {$this->idfield} = {?}", Post::v($this->idfield), $id);
-                XDB::execute("REPLACE INTO {$this->table} VALUES ($values)");
-                if ($id !== false)
-                    $page->trig("L'entrée ".$id." a été mise à jour.");
-                else
-                    $page->trig("Une nouvelle entrée a été créée.");
-            } else
-                $page->trig("Impossible de mette à jour.");
+                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 {
+                $page->trigError("Impossible de mettre à jour.");
+            }
+            if (!$this->auto_return) {
+                return $this->apply($page, 'edit', $id);
+            }
         }
         if ($action == 'sort') {
-               $this->sortfield = $id;
+            $this->sortfield = $id;
         }
         if ($action == 'sortdesc') {
-               $this->sortfield = $id.' DESC';
+            $this->sortfield = $id.' DESC';
         }
         if ($list) {
             // user can sort by field by clicking the title of the column
@@ -241,7 +416,46 @@ class PLTableEditor {
             if (count($this->sort) > 0) {
                 $sort = 'ORDER BY ' . join($this->sort, ',');
             }
-            $it = XDB::iterator("SELECT * FROM {$this->table} $sort");
+            // optional infos columns
+            $optional_fields = '';
+            if (count($this->ofields)) {
+                $order = array();
+                foreach ($this->vars as $i => $aliasname) {
+                    $order[sprintf('%f',count($order))] = $i;
+                }
+                // delta for indexing optional columns between existing ones
+                $changeorder = 0.5;
+                foreach ($this->ofields as $sqlname => $ofieldvalues) {
+                    list($aliasname, $desc, $type, $nextvar) = $ofieldvalues;
+                    $optional_fields .= ', '.$sqlname.' AS '.$aliasname;
+                    $this->describe($aliasname, $desc, true);
+                    $this->vars[$aliasname]['optional'] = true;
+                    if (isset($type)) {
+                        $this->vars[$aliasname]['Type'] = $type;
+                    }
+                    if (isset($nextvar) && isset($this->vars[$nextvar]) && $nextvar != $aliasname) {
+                        $nextkey = array_search($nextvar, $order);
+                        $order[sprintf('%f',$nextkey - $changeorder)] = $aliasname;
+                        $changeorder = $changeorder / 2;
+                    } else {
+                        $order[sprintf('%f',count($order))] = $aliasname;
+                    }
+                    $this->vars[$aliasname]['Field'] = $aliasname;
+                }
+                if ($changeorder != 0.5) {
+                    ksort($order);
+                    $orderedvars = array();
+                    foreach ($order as $aliasname) {
+                        $orderedvars[$aliasname] = $this->vars[$aliasname];
+                    }
+                    $this->vars = $orderedvars;
+                }
+            }
+            $optional_joints = '';
+            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->get_where_clause() . " $sort");
             $this->nbfields = 0;
             foreach ($this->vars as $field => $descr)
                 if ($descr['display']) $this->nbfields++;
@@ -251,4 +465,5 @@ class PLTableEditor {
     }
 }
 
+// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
 ?>