Pman/Roo.php
[Pman.Base] / Pman / Roo.php
index ef459d0..44333a7 100644 (file)
@@ -16,7 +16,7 @@ require_once 'Pman.php';
  * - postListExtra - 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) // single fetch, add data..
+ * - toRooSingleArray($authUser, $request) // single fetch, add data..
  * - toRooArray($request) /// toArray if you need to return different data.. for a list fetch.
  * 
  * 
@@ -26,7 +26,7 @@ require_once 'Pman.php';
  * - onUpload($roo)
  * - setFromRoo($ar) - values from post (deal with dates etc.) - return true|error string.
  * 
- * - toEventString (for logging)
+ * - toEventString (for logging - this is generically prefixed to all database operations.)
  */
 
 class Pman_Roo extends Pman
@@ -59,7 +59,7 @@ class Pman_Roo extends Pman
      * 
      * csvCols[0] csvCols[1]....    = .... column titles for CSV output
      * 
-     * csvTitle[0], csvTitle[1] ....  = columns to use for CSV output
+     * csvTitles[0], csvTitles[1] ....  = columns to use for CSV output
      *
      * sort        = sort column (',' comma delimited)
      * dir         = sort direction ?? in future comma delimited...
@@ -73,7 +73,8 @@ class Pman_Roo extends Pman
     function get($tab)
     {
          //  $this->jerr("Not authenticated", array('authFailure' => true));
-        // DB_DataObject::debuglevel(1);
+       //echo '<PRE>';print_R($_GET);
+       DB_DataObject::debuglevel(1);
         
         $this->init(); // from pnan.
         
@@ -122,7 +123,7 @@ class Pman_Roo extends Pman
                 $this->jerr("PERMISSION DENIED");
             }
             
-            $this->jok(method_exists($x, 'toRooSingleArray') ? $x->toRooSingleArray($this->authUser) : $x->toArray());
+            $this->jok(method_exists($x, 'toRooSingleArray') ? $x->toRooSingleArray($this->authUser, $_REQUEST) : $x->toArray());
             
         }
         if (isset($_REQUEST['_delete'])) {
@@ -148,36 +149,23 @@ class Pman_Roo extends Pman
             $this->jok("Updated");
             
         }
-      // DB_DataObject::debugLevel(1);
+       //DB_DataObject::debugLevel(1);
         if (method_exists($x, 'checkPerm') && !$x->checkPerm('S', $this->authUser))  {
             $this->jerr("PERMISSION DENIED");
         }
-        $map = $this->loadMap($x, $_columns);
         
-        $this->setFilters($x,$_REQUEST);
-        
-         
+        // sets map and countWhat
+        $this->loadMap($x, $_columns, empty($_REQUEST['_distinct']) ? false:  $_REQUEST['_distinct']);
         
+        $this->setFilters($x,$_REQUEST);
+      
+         //print_r($x);
         // build join if req.
-        $countWhat = false;
-        if (!empty($_REQUEST['_distinct'])) {
-            $cols = $x->table();
-           // print_r($cols);
-          
-            if (isset($cols[$_REQUEST['_distinct']])) {
-                $countWhat = 'distinct ' . $_REQUEST['_distinct'];
-                $x->selectAdd();
-                $x->selectAdd('distinct('.$_REQUEST['_distinct'].')');
-                $_columns = array( $_REQUEST['_distinct'] );
-            } else {
-                $this->jerr('invalid distinct');
-            }
-             
-        }
-        $total = $x->count($countWhat);
+          //DB_DataObject::debugLevel(1);
+        $total = $x->count($this->countWhat);
         // sorting..
-      //   DB_DataObject::debugLevel(1);
-        
+      //   
+        //var_dump($total);exit;
         $this->applySort($x);
         
         
@@ -272,12 +260,13 @@ class Pman_Roo extends Pman
      * @arg   DB_DataObject $x
      * 
      */
-    function applySort($x)
+    function applySort($x, $sort = '', $dir ='')
     {
         
        // Db_DataObject::debugLevel(1);
-        $sort = empty($_REQUEST['sort']) ? '' : $_REQUEST['sort'];
-        $dir = (empty($_REQUEST['dir']) || strtoupper($_REQUEST['dir']) == 'ASC' ? 'ASC' : 'DESC');
+        $sort = empty($_REQUEST['sort']) ? $sort : $_REQUEST['sort'];
+        $dir = empty($_REQUEST['dir']) ? $dir : $_REQUEST['dir'];
+        $dir = $dir == 'ASC' ? 'ASC' : 'DESC';
         
         
         
@@ -445,7 +434,7 @@ class Pman_Roo extends Pman
         if (method_exists($x, 'onInsert')) {
             $x->onInsert($_REQUEST, $this);
         }
-        $this->addEvent("ADD", $x, $x->toEventString());
+        $this->addEvent("ADD", $x);
         
         // note setFrom might handle this before hand...!??!
         if (!empty($_FILES) && method_exists($x, 'onUpload')) {
@@ -473,6 +462,35 @@ class Pman_Roo extends Pman
             $this->jerr("PERMISSION DENIED");
         }
        
+        // check any locks..
+        // only done if we recieve a lock_id.
+        // we are very trusing here.. that someone has not messed around with locks..
+        // the object might want to check in their checkPerm - if locking is essential..
+        
+        $lock = DB_DataObjecT::factory('Core_locking');
+        if (is_a($lock,'DB_DataObject'))  {
+                 
+            $lock->on_id = $x->id;
+            $lock->on_table= $x->tableName();
+            if (!empty($_REQUEST['_lock_id'])) {
+                $lock->whereAdd('id != ' . ((int)$_REQUEST['_lock_id']));
+            }
+            $lock->limit(1);
+            if ($lock->find(true)) {
+                // it's locked by someone else..
+                $p = $lock->person();
+                $this->jerr("Your lock is invalid, This record is locked by " . $p->name . " at " .$lock->created);
+            }
+            // check the users lock.. - no point.. ??? - if there are no other locks and it's not the users, then they can 
+            // edit it anyways...
+            
+        }
+        
+         
+        
+        
+        
+       
         $_columns = !empty($req['_columns']) ? explode(',', $req['_columns']) : false;
 
        
@@ -487,7 +505,7 @@ class Pman_Roo extends Pman
         } else {
             $x->setFrom($req);
         }
-        $this->addEvent("EDIT", $x, $x->toEventString());
+        $this->addEvent("EDIT", $x);
         //print_r($x);
         //print_r($old);
         
@@ -578,7 +596,21 @@ class Pman_Roo extends Pman
         while ($x->fetch()) {
             $xx = clone($x);
             
+           
+            // perms first.
+            
+            if (method_exists($x, 'checkPerm') && !$x->checkPerm('D', $this->authUser))  {
+                $this->jerr("PERMISSION DENIED");
+            }
+            
+            // before delte = allows us to trash dependancies if needed..
+            if ( method_exists($xx, 'beforeDelete') && ($xx->beforeDelete() === false)) {
+                $errs[] = "Delete failed ({$xx->id})\n". (isset($xx->err) ? $xx->err : '');
+                continue;
+            }
             
+            // now check deps.
+             
             foreach($affects as $k=> $true) {
                 $ka = explode('.', $k);
                 $chk = DB_DataObject::factory($ka[0]);
@@ -586,22 +618,22 @@ class Pman_Roo extends Pman
                     $this->jerr('Unable to load referenced table, check the links config: ' .$ka[0]);
                 }
                 $chk->{$ka[1]} =  $xx->$pk;
-                if ($chk->count()) {
-                    $this->jerr('Delete Dependant records first ('. $ka[0]. ':' . $ka[1] .'='.$xx->$pk.')');
+                $matches = $chk->count();
+                if ($matches) {
+                    $chk->limit(1);
+                    $o = $chk->fetchAll();
+                    $desc =  $ka[0]. ':' . $ka[1] .'='.$xx->$pk;
+                    if (method_exists($chk, 'toEventString')) {
+                        $desc = $ka[0] . ' : ' . $o[0]->toEventString();
+                    }
+                    
+                    $this->jerr("Delete Dependant records ($matches found),  first is ( $desc )");
                 }
             }
+            // finally log it.. 
             
+            $this->addEvent("DELETE", $x);
             
-            
-            if (method_exists($x, 'checkPerm') && !$x->checkPerm('D', $this->authUser))  {
-                $this->jerr("PERMISSION DENIED");
-            }
-            
-            $this->addEvent("DELETE", $x, $x->toEventString());
-            if ( method_exists($xx, 'beforeDelete') && ($xx->beforeDelete() === false)) {
-                $errs[] = "Delete failed ({$xx->id})\n". (isset($xx->err) ? $xx->err : '');
-                continue;
-            }
             $xx->delete();
         }
         if ($errs) {
@@ -615,22 +647,25 @@ class Pman_Roo extends Pman
     
     
     var $cols = array();
-    function loadMap($do, $filter=false) 
+    function loadMap($do, $filter=false, $distinct = false
     {
         //DB_DataObject::debugLevel(1);
-        $conf = array();
         
+         $this->countWhat = false;
+        
+        $conf = array();
         
         $this->init();
+        
         $mods = explode(',',$this->appModules);
         
-        $ff = HTML_FlexyFramework::geT();
+        $ff = HTML_FlexyFramework::get();
         //$db->databaseName();
         
         //$ff->DB_DataObject['ini_'. $db->database()];
         //echo '<PRE>';print_r($do->links());exit;
         //var_dump($mods);
-        
+        /*
         if (in_array('Builder', $mods) ) {
             
             foreach(in_array('Builder', $mods) ? scandir($this->rootDir.'/Pman') : $mods as $m) {
@@ -649,8 +684,9 @@ class Pman_Roo extends Pman
                 $map = $conf[$do->tableName()];
             } 
         } else {
+            */
             $map = $do->links();
-        }
+        //}
          
         
         
@@ -665,21 +701,32 @@ class Pman_Roo extends Pman
         $xx = array_keys($tabdef);
         $do->selectAdd(); // we need thsi as normally it's only cleared by an empty selectAs call.
         
-        if ($filter) {
+        $selectAs = array(array(  $xx , '%s', false));
+       
+        $has_distinct = false;
+        if ($filter || $distinct) {
             $cols = array();
-         
+            //echo '<PRE>' ;print_r($filter);exit;
             foreach($xx as $c) {
-                if (in_array($c, $filter)) {
+                if ($distinct && $distinct == $c) {
+                    $has_distinct = 'DISTINCT( ' . $do->tableName() .'.'. $c .') as ' . $c;
+                    $this->countWhat =  'DISTINCT  ' . $do->tableName() .'.'. $c .'';
+                    continue;
+                }
+                if (!$filter || in_array($c, $filter)) {
                     $cols[] = $c;
                 }
             }
-            $do->selectAs($cols);
-        } else {
-            $do->selectAs($xx);
-        }
-        
+            
+            
+            $selectAs = empty($cols) ?  array() : array(array(  $cols , '%s', false)) ;
+            
+            
+            
+        } 
         
         $this->cols = array();
+        $this->colsJoinName =array();
         foreach($xx as $k) {
             $this->cols[$k] = $do->tableName(). '.' . $k;
         }
@@ -709,29 +756,51 @@ class Pman_Roo extends Pman
             $xx = array_keys($tabdef);
             
             
-            if ($filter) {
+            if ($filter || $distinct) {
                 $cols = array();
                 foreach($xx as $c) {
-                    
                     $tn = sprintf($ocl.'_%s', $c);
-                    if (in_array($tn, $filter)) {
+                  // echo '<PRE>'; var_dump($tn);
+                    if ($distinct && $tn == $distinct) {
+                        $has_distinct = 'DISTINCT( ' . 'join_'.$ocl.'_'.$col.'.'.$k .')  as ' . $tn ;
+                        $this->countWhat =  'DISTINCT  join_'.$ocl.'_'.$col.'.'.$k;
+                        continue;
+                    }
+                    
+                    
+                    if (!$filter || in_array($tn, $filter)) {
                         $cols[] = $c;
                     }
                 }
-                $do->selectAs($cols, $ocl.'_%s', 'join_'.$ocl.'_'. $col);
+                if (!empty($cols)) {
+                     $selectAs[] = array($cols, $ocl.'_%s', 'join_'.$ocl.'_'. $col);
+                }
+               
+                
             } else {
-                $do->selectAs($xx,  $ocl.'_%s', 'join_'.$ocl.'_'. $col);
+                $selectAs[] = array($xx, $ocl.'_%s', 'join_'.$ocl.'_'. $col);
+                
             }
              
             
             foreach($xx as $k) {
                 $this->cols[sprintf($ocl.'_%s', $k)] = $tab.'.'.$k;
+                $this->colsJname[sprintf($ocl.'_%s', $k)] = 'join_'.$ocl.'_'.$col.'.'.$k;
             }
             
             
         }
-        //DB_DataObject::debugLevel(1);
         
+        if ($has_distinct) {
+            $do->selectAdd($has_distinct);
+        }
+        //DB_DataObject::debugLevel(1);
+        // we do select as after everything else as we need to plop distinct at the beginning??
+        /// well I assume..
+       // echo '<PRE>';print_r($this->colsJname);exit;
+        foreach($selectAs as $ar) {
+            $do->selectAs($ar[0], $ar[1], $ar[2]);
+        }
         
         
     }
@@ -808,6 +877,8 @@ class Pman_Roo extends Pman
                         $ar = array();
                         break;
                     }
+                    // FIXME: note this is not typesafe for anything other than mysql..
+                    
                     if (!is_numeric($v) || !is_long($v)) {
                         $quote = true;
                     }
@@ -815,7 +886,13 @@ class Pman_Roo extends Pman
                     
                 }
                 if (count($ar)) {
-                    $x->whereAddIn($x->tableName(). '.'.$key,$ar, $quote ? 'string' : 'int');
+                    
+                    
+                    $x->whereAddIn(
+                        isset($this->colsJname[$key]) ? 
+                            $this->colsJname[$key] :
+                            ($x->tableName(). '.'.$key),
+                        $ar, $quote ? 'string' : 'int');
                 }
                 
                 continue;
@@ -824,8 +901,13 @@ class Pman_Roo extends Pman
             
             
             if ($key[0] == '!' && in_array(substr($key, 1), array_keys($this->cols))) {
-                    
-                $x->whereAdd( $x->tableName() .'.' .substr($key, 1) . ' != ' .
+                
+                $key  = substr($key, 1) ;
+                
+                $x->whereAdd(   (
+                        isset($this->colsJname[$key]) ? 
+                            $this->colsJname[$key] :
+                            $x->tableName(). '.'.$key ) . ' != ' .
                     (is_numeric($val) ? $val : "'".  $x->escape($val) . "'")
                 );
                 continue;
@@ -836,7 +918,7 @@ class Pman_Roo extends Pman
             
             switch($key) {
                     
-                // Events and remarks
+                // Events and remarks -- fixme - move to events/remarsk...
                 case 'on_id':  // where TF is this used...
                     if (!empty($q['query']['original'])) {
                       //  DB_DataObject::debugLevel(1);
@@ -856,12 +938,15 @@ class Pman_Roo extends Pman
                         $q_filtered[$key] = $val;
                     }
                     
-                    if (isset($this->cols[$key]) && strpos( $this->cols[$key], '.') !== false) {
+                    // subjoined columns = check the values.
+                    // note this is not typesafe for anything other than mysql..
+                    
+                    if (isset($this->colsJname[$key])) {
                         $quote = false;
                         if (!is_numeric($val) || !is_long($val)) {
                             $quote = true;
                         }
-                        $x->whereAdd( "$key  = " . ($quote ? "'". $x->escape($val) ."'" : $val));
+                        $x->whereAdd( "{$this->colsJname[$key]} = " . ($quote ? "'". $x->escape($val) ."'" : $val));
                         
                     }