fix unititialize value
[Pman.Base] / Pman / Roo.php
index f8d4142..d22fdae 100644 (file)
@@ -13,7 +13,7 @@ require_once 'Pman.php';
  * 
  * - applySort($au, $sortcol, $direction, $array_of_columns, $multisort) -- does not support multisort at present..
  * - applyFilters($_REQUEST, $authUser, $roo) -- apply any query filters on data. and hide stuff not to be seen. (RETURN false to prevent default filters.)
- * - postListExtra($_REQUEST) : array(extra_name => data) - add extra column data on the results (like new messages etc.)
+ * - postListExtra($_REQUEST, $roo, $array_data) : array(extra_name => data) - add extra column data on the results (like new messages etc.)
  * - postListFilter($data, $authUser, $request) return $data - add extra data to an object
  * 
  * - toRooSingleArray($authUser, $request) // single fetch, add data..
@@ -25,20 +25,18 @@ require_once 'Pman.php';
  *      ... call $roo->jerr() on failure...
  *
  *  BEFORE
- * - beforeDelete($dependants_array, $roo) Argument is an array of un-find/fetched dependant items.
+ * - beforeDelete($dependants_array, $roo, $request) Argument is an array of un-find/fetched dependant items.
  *                      - jerr() will stop insert.. (Prefered)
  *                      - return false for fail and set DO->err;
  * - beforeUpdate($old, $request,$roo) - after update - jerr() will stop insert..
  * - beforeInsert($request,$roo) - before insert - jerr() will stop insert..
  *
  *  AFTER
- * - onUpdate($old, $request,$roo) - after update // return value ignored
- * - onInsert($request,$roo) - after insert
+ * - onUpdate($old, $request,$roo, $event) - after update // return value ignored
+ * - onInsert($request,$roo, $event) - after insert
  * - onDelete($req, $roo) - after delete
  * - onUpload($roo)
- * 
- * 
+ *  
  * - toEventString (for logging - this is generically prefixed to all database operations.)
  */
 
@@ -51,12 +49,13 @@ class Pman_Roo extends Pman
     
     var $key; // used by update currenly to store primary key.
     
-    var $transObj = false ; // the transaction BEGIN / ROLLBACK / COMMIT Dataobject.
-    
+     
     var $max_limit = 10000;
     
     var $debugEnabled = true; // disable this for public versions of this code.
     
+    var $do = false; // the dataobject being worked on..
+    
     function getAuth()
     {
         parent::getAuth(); // load company!
@@ -74,7 +73,7 @@ class Pman_Roo extends Pman
         return true;
     }
     /**
-     * GET method   Roo/TABLENAME.php
+     * GET method   Roo/TABLENAME
      *
      * Generally for SELECT or Single SELECT
      *
@@ -141,10 +140,10 @@ class Pman_Roo extends Pman
      *   applyFilters($_REQUEST, $authUser, $roo)
      *                     -- apply any query filters on data. and hide stuff not to be seen.
      *                     -- can exit by calling $roo->jerr()
-     *   postListExtra($_REQUEST) : array(extra_name => data)
-     *                     - add extra column data on the results (like new messages etc.)
+     *   postListExtra($_REQUEST, $roo, $array_data) : array(extra_name => data)
+     *                     - add extra column to the jdata return key/value info.
      *   postListFilter($data, $authUser, $request) return $data
-     *                      - add extra data to an object
+     *                      - modify the returned array of data (either add stuff to the data, or remove lines etc)
      * 
      *   
      *   toRooSingleArray($authUser, $request) : array
@@ -153,7 +152,8 @@ class Pman_Roo extends Pman
      *   toRooArray($request) : array
      *                      - called if singleArray is unavailable on single fetch.
      *                      - always tried for mutiple results.
-     *   toArray()          - the default method if none of the others are found. 
+     *   toArray()          - the default method if none of the others are found.
+     *   toSimpleExcelColumn($col) - see toCSV - this enables special columns to be created for exported data.
      *   
      *   autoJoin($request) 
      *                      - standard DataObject feature - causes all results to show all
@@ -241,10 +241,10 @@ class Pman_Roo extends Pman
        
         // sets map and countWhat
         $this->loadMap($x, array(
-                    'columns' => $_columns,
-                    'distinct' => empty($_REQUEST['_distinct']) ? false:  $_REQUEST['_distinct'],
-                    'exclude' => empty($_REQUEST['_exclude_columns']) ? false:  explode(',', $_REQUEST['_exclude_columns'])
-            ));
+                'columns' => $_columns,
+                'distinct' => empty($_REQUEST['_distinct']) ? false:  $_REQUEST['_distinct'],
+                'exclude' => empty($_REQUEST['_exclude_columns']) ? false:  explode(',', $_REQUEST['_exclude_columns'])
+        ));
         
         
         $this->setFilters($x,$_REQUEST);
@@ -256,8 +256,18 @@ class Pman_Roo extends Pman
          //print_r($x);
         // build join if req.
           //DB_DataObject::debugLevel(1);
-       //   var_dump($this->countWhat);
-        $total = $x->count($this->countWhat);
+        // count with multiple joins and no conditions can be quite slow - so if there are no conditions - just remove the joins from the count.
+        $xx = clone($x);
+        $old_where = $x->whereAdd();
+        if (empty($old_where )) {
+            $xx->_join = '';
+        } else {
+            $x->whereAdd($old_where);
+            $xx=clone($x);
+            
+        }
+       
+        $total = $xx->count($this->countWhat);
         // sorting..
       //   
         //var_dump($total);exit;
@@ -282,7 +292,7 @@ class Pman_Roo extends Pman
         $this->sessionState(0);
         $res = $x->find();
         $this->sessionState(1);
-        
+                
         if (false === $res) {
             $this->jerr($x->_lastError->toString());
             
@@ -322,7 +332,7 @@ class Pman_Roo extends Pman
         
         $extra = false;
         if (method_exists($queryObj ,'postListExtra')) {
-            $extra = $queryObj->postListExtra($_REQUEST, $this);
+            $extra = $queryObj->postListExtra($_REQUEST, $this, $ret);
         }
         
         
@@ -337,23 +347,17 @@ class Pman_Roo extends Pman
             
             
             $this->toCsv($ret, $_REQUEST['csvCols'], $_REQUEST['csvTitles'],
-                        empty($_REQUEST['csvFilename']) ? '' : $_REQUEST['csvFilename']
-                         );
+                        empty($_REQUEST['csvFilename']) ? '' : $_REQUEST['csvFilename'] );
             
             
         
         }
-        //die("DONE?");
-      
-        //if ($x->tableName() == 'Documents_Tracking') {
-        //    $ret = $this->replaceSubject(&$ret, 'doc_id_subject');
-       // }
-        
         
         
         if (!empty($_REQUEST['_requestMeta']) &&  count($ret)) {
             $meta = $this->meta($x, $ret);
             if ($meta) {
+                $extra = $extra ? $extra: array();
                 $extra['metaData'] = $meta;
             }
         }
@@ -430,7 +434,7 @@ class Pman_Roo extends Pman
     
     function toCsv($data, $cols, $titles, $filename, $addDate = true)
     {
-          
+         // die('here');
         $this->sessionState(0); // turn off sessions  - no locking..
 
         require_once 'Pman/Core/SimpleExcel.php';
@@ -450,18 +454,24 @@ class Pman_Roo extends Pman
             $rooar = method_exists($data, 'toRooArray');
             while($data->fetch()) {
                 $x = $rooar  ? $data->toRooArray($q) : $data->toArray();
-                
-                
+                 
                 if ($cols == '*') {  /// did we get cols sent to us?
                     $cols = array_keys($x);
                 }
+                
+                if(!is_array($cols)) {
+                    $cols = explode(',', $cols);
+                }
                
                 if ($titles !== false) {
                     if ($titles== '*') {
                         $titles= array_keys($x);
                     }
+                    if(!is_array($titles)) {
+                        $titles = explode(',', $titles);
+                    }
                     foreach($cols as $i=>$col) {
-                        $se_config['cols'][] = array(
+                        $add = array(
                             'header'=> isset($titles[$i]) ? $titles[$i] : $col,
                             'dataIndex'=> $col,
                             'width'=>  100,
@@ -469,10 +479,17 @@ class Pman_Roo extends Pman
                              //   'color' => 'yellow', // set color for the cell which is a header element
                               // 'fillBlank' => 'gray', // set 
                         );
-                         $se = new Pman_Core_SimpleExcel(array(), $se_config);
+                        //die('here');
+                        if (method_exists($data, 'toSimpleExcelColumn')) {
+                            $add = $data->toSimpleExcelColumn($add);
+                        } 
+                        
+                        $se_config['cols'][] = $add;
+                        
        
                         
                     }
+                    $se = new Pman_Core_SimpleExcel(array(), $se_config);
                      
                     $titles = false;
                 }
@@ -491,19 +508,29 @@ class Pman_Roo extends Pman
             
         } 
         
-        
-        foreach($data as $x) {
+         foreach($data as $x) {
             //echo "<PRE>"; print_r(array($_REQUEST['csvCols'], $x->toArray())); exit;
             $line = array();
-            if ($titles== '*') {
-                $titles= array_keys($x);
-            }
+            
             if ($cols== '*') {
                 $cols= array_keys($x);
             }
+            
+            if(!is_array($cols)) {
+                $cols = explode(',', $cols);
+            }
+
             if ($titles !== false) {
+                if ($titles== '*') {
+                    $titles= array_keys($x);
+                }
+
+                if(!is_array($titles)) {
+                    $titles = explode(',', $titles);
+                }
+
                 foreach($cols as $i=>$col) {
-                    $se_config['cols'][] = array(
+                    $add = array(
                         'header'=> isset($titles[$i]) ? $titles[$i] : $col,
                         'dataIndex'=> $col,
                         'width'=>  100,
@@ -511,27 +538,32 @@ class Pman_Roo extends Pman
                          //   'color' => 'yellow', // set color for the cell which is a header element
                           // 'fillBlank' => 'gray', // set 
                     );
-                    $se = new Pman_Core_SimpleExcel(array(),$se_config);
+                    //die('here');
+                    if (method_exists($this->do, 'toSimpleExcelColumn')) {
+                        $add = $this->do->toSimpleExcelColumn($add);
+                    } 
+                    
+                    $se_config['cols'][] = $add;
+                    
    
                     
                 }
-                
+                $se = new Pman_Core_SimpleExcel(array(),$se_config);
+               
                 
                 //fputcsv($fh, $titles);
                 $titles = false;
             }
             
-            
-            
             $se->addLine($se_config['workbook'], $x);
         }
+        
         if(!$se){
             $this->jerr('no data found');
         }
+        
         $se->send($fn .'.xls');
         exit;
-    
-        
         
     }
     
@@ -606,7 +638,7 @@ class Pman_Roo extends Pman
      *                      - return false for fail and set DO->err;
      *                      
      *      beforeUpdate($old, $request,$roo)
-     *                      - after update - jerr() will stop insert..
+     *                      - before update - jerr() will stop insert..
      *      beforeInsert($request,$roo)
      *                      - before insert - jerr() will stop insert..
      *
@@ -641,7 +673,7 @@ class Pman_Roo extends Pman
         $this->init(); // for pman.
          
         $x = $this->dataObject($tab);
-        
+
         $this->transObj = clone($x);
         
         $this->transObj->query('BEGIN');
@@ -658,12 +690,14 @@ class Pman_Roo extends Pman
             // do we really delete stuff!?!?!?
             return $this->delete($x,$_REQUEST);
         } 
-         
+        
+        
+        
         
         $old = false;
         
         // not sure if this is a good idea here...
-        
+
         if (!empty($_REQUEST['_ids'])) {
             $ids = explode(',',$_REQUEST['_ids']);
             $x->whereAddIn($this->key, $ids, 'int');
@@ -678,7 +712,7 @@ class Pman_Roo extends Pman
             
         }
          
-        if (!empty($_REQUEST[$this->key])) {
+        if (!empty($_REQUEST[$this->key])) { 
             // it's a create..
             if (!$x->get($this->key, $_REQUEST[$this->key]))  {
                 $this->jerr("Invalid request (id does not point to  a record.)");
@@ -689,7 +723,7 @@ class Pman_Roo extends Pman
             if (empty($_POST)) {
                 $this->jerr("No data recieved for inserting");
             }
-            
+
             $this->jok($this->insert($x, $_REQUEST));
             
         }
@@ -728,12 +762,12 @@ class Pman_Roo extends Pman
                     $ms ? json_decode($ms) : false
             );
         }
+        
         if ($ms !== false) {
             return $this->multiSort($x);
         }
-        
         if ($sorted === false) {
-            
             $cols = $x->tableColumns();
             $excols = array_keys($this->cols);
             
@@ -844,7 +878,7 @@ class Pman_Roo extends Pman
         } else if (method_exists($x, 'applyFilters')) {
             // always call apply filters even after update/insert...
             // however arguments are not passed.
-            $x->applyFilters(array(), $this->authUser, $this);
+            $x->applyFilters(array('_is_update_request' => true), $this->authUser, $this);
         }
         
         // DB_DataObject::DebugLevel(1);
@@ -875,7 +909,6 @@ class Pman_Roo extends Pman
         if (method_exists($x, 'toRooArray')) {
             $this->jok($x->toRooArray($req));
         }
-        
         $this->jok($x->toArray());
         
         
@@ -883,7 +916,7 @@ class Pman_Roo extends Pman
     
     function insert($x, $req, $with_perm_check = true)
     {
-        if (method_exists($x, 'setFromRoo')) {
+         if (method_exists($x, 'setFromRoo')) {
             $res = $x->setFromRoo($req, $this);
             if (is_string($res)) {
                 $this->jerr($res);
@@ -891,7 +924,7 @@ class Pman_Roo extends Pman
         } else {
             $x->setFrom($req);
         }
-        
+
         if ( $with_perm_check &&  !$this->checkPerm($x,'A', $req))  {
             $this->jerr("PERMISSION DENIED (i)");
         }
@@ -932,17 +965,20 @@ class Pman_Roo extends Pman
         }
         
         $res = $x->insert();
+
         if ($res === false) {
             $this->jerr($x->_lastError->toString());
         }
+        $ev = $this->addEvent("ADD", $x);
         if (method_exists($x, 'onInsert')) {
-            $x->onInsert($_REQUEST, $this);
+                    
+            $x->onInsert($_REQUEST, $this, $ev);
         }
-        $ev = $this->addEvent("ADD", $x);
+        
         if ($ev) { 
             $ev->audit($x);
         }
-        
+      
         // note setFrom might handle this before hand...!??!
         if (!empty($_FILES) && method_exists($x, 'onUpload')) {
             $x->onUpload($this, $_REQUEST);
@@ -1063,7 +1099,7 @@ class Pman_Roo extends Pman
         //print_r($old);
         
         $cols = $x->tableColumns();
-        //print_r($cols);
+
         if (isset($cols['modified'])) {
             $x->modified = date('Y-m-d H:i:s');
         }
@@ -1097,11 +1133,11 @@ class Pman_Roo extends Pman
         if ($res === false) {
             $this->jerr($x->_lastError->toString());
         }
-        
+        $ev = $this->addEvent("EDIT", $x);
+
         if (method_exists($x, 'onUpdate')) {
-            $x->onUpdate($old, $req, $this);
+            $x->onUpdate($old, $req, $this, $ev);
         }
-        $ev = $this->addEvent("EDIT", $x);
         if ($ev) { 
             $ev->audit($x, $old);
         }
@@ -1120,11 +1156,13 @@ class Pman_Roo extends Pman
      */
     
     function delete($x, $req)
-    {
+    { 
         // do we really delete stuff!?!?!?
         if (empty($req['_delete'])) {
             $this->jerr("Delete Requested with no value");
         }
+        
+        
         // build a list of tables to queriy for dependant data..
         $map = $x->links();
         
@@ -1194,12 +1232,13 @@ class Pman_Roo extends Pman
                 }          
             }
             
+            
             $has_beforeDelete = method_exists($xx, 'beforeDelete');
             // before delte = allows us to trash dependancies if needed..
             $match_total = 0;
             
             if ( $has_beforeDelete ) {
-                if ($xx->beforeDelete($match_ar, $this) === false) {
+                if ($xx->beforeDelete($match_ar, $this, $_REQUEST) === false) {
                     $errs[] = "Delete failed ({$xx->id})\n".
                         (isset($xx->err) ? $xx->err : '');
                     continue;
@@ -1382,7 +1421,7 @@ class Pman_Roo extends Pman
         $q_filtered = array();
         
         $keys = $x->keys();
-        // var_dump($keys);exit;
+
         foreach($q as $key=>$val) {
             
             if (in_array($key,$keys) && !is_array($val)) {
@@ -1450,7 +1489,7 @@ class Pman_Roo extends Pman
                 
             }
             
-            
+                
             
             switch($key) {
                     
@@ -1463,7 +1502,7 @@ class Pman_Roo extends Pman
                         $x->whereAdd("(on_id = $oid  OR 
                                 on_id IN ( SELECT distinct(id) FROM Documents WHERE original = $o ) 
                             )");
-                        continue;
+                        continue 2;
                                 
                     }
                     $x->on_id = $val;
@@ -1481,7 +1520,7 @@ class Pman_Roo extends Pman
                         
                         // the aobve rule for !strlen non-joined cols should apply to joined ones.
                         if (!strlen($val)) {
-                            continue;
+                            continue 2;
                         }
                         
                         
@@ -1494,7 +1533,7 @@ class Pman_Roo extends Pman
                     }
                     
                     
-                    continue;
+                    continue 2;
             }
         }
         if (!empty($q_filtered)) {
@@ -1555,39 +1594,13 @@ class Pman_Roo extends Pman
         if (!is_a($x, 'DB_DataObject') && !is_a($x, 'PDO_DataObject')) {
             $this->jerr('invalid url - no dataobject');
         }
-    
+        $this->do = $x;
         return $x;
         
     }
     
-     
-    // our handlers to commit / rollback.
-    
       
     
-    function jok($str)
-    {
-        // note that commit will only work if an insert/update was done,
-        // so some stored proc calls may not have flagged this.
-        
-        if ($this->transObj ) {
-            $this->transObj->query( connection_aborted() ? 'ROLLBACK' :  'COMMIT');
-        }
-        return parent::jok($str);
-    }
-    
-    
-    function jerr($str, $errors=array(), $content_type = false)
-    {
-        // standard error reporting..
-        if ($this->transObj) {
-            $this->transObj->query('ROLLBACK');
-        }
-        return parent::jerr($str,$errors,$content_type);
-    
-    }
-    
-