Pman.Gnumeric.js
[Pman.Core] / RooGetTrait.php
index f460616..162ebce 100644 (file)
@@ -107,7 +107,8 @@ trait Pman_Core_RooGetTrait {
         
         PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($this, 'onPearError'));
    
-        $tab = array_shift(explode('/', $tab));
+        $explode_tab = explode('/', $tab);
+        $tab = array_shift($explode_tab);
         
         $x = $this->dataObject($tab);
         
@@ -131,19 +132,6 @@ trait Pman_Core_RooGetTrait {
        
         if (isset($_REQUEST['_delete'])) {
             $this->jerr("DELETE by GET has been removed - update the code to use POST");
-            /*
-            
-            $keys = $x->keys();
-            if (empty($keys) ) {
-                $this->jerr('no key');
-            }
-            
-            $this->key = $keys[0];
-            
-            
-            // do we really delete stuff!?!?!?
-            return $this->delete($x,$_REQUEST);
-            */
         } 
         
         
@@ -169,10 +157,10 @@ trait Pman_Core_RooGetTrait {
         
         // 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);
@@ -181,10 +169,6 @@ trait Pman_Core_RooGetTrait {
             $this->jerr("PERMISSION DENIED (g)");
         }
         
-         //print_r($x);
-        // build join if req.
-          //DB_DataObject::debugLevel(1);
-       //   var_dump($this->countWhat);
         $total = $x->count($this->countWhat);
         // sorting..
       //   
@@ -213,11 +197,8 @@ trait Pman_Core_RooGetTrait {
         
         if (false === $res) {
             $this->jerr($x->_lastError->toString());
-            
         }
         
-        
-        
         $ret = array();
         
         // ---------------- THESE ARE DEPRICATED.. they should be moved to the model...
@@ -271,13 +252,6 @@ trait Pman_Core_RooGetTrait {
             
         
         }
-        //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);
@@ -302,209 +276,229 @@ trait Pman_Core_RooGetTrait {
         
     }
     
-    function selectSingle($x, $id, $req=false)
+    function applySort($x, $sort = '', $dir ='')
     {
-        $_columns = !empty($req['_columns']) ? explode(',', $req['_columns']) : false;
-
-        if (!is_array($id) && empty($id)) {
-            
-            if (method_exists($x, 'toRooSingleArray')) {
-                $this->jok($x->toRooSingleArray($this->getAuthUser(), $req));
-            }
-            
-            if (method_exists($x, 'toRooArray')) {
-                $this->jok($x->toRooArray($req));
-            }
-            
-            $this->jok($x->toArray());
+        $sort = empty($_REQUEST['sort']) ? $sort : $_REQUEST['sort'];
+        $dir = empty($_REQUEST['dir']) ? $dir : $_REQUEST['dir'];
+        $dir = $dir == 'ASC' ? 'ASC' : 'DESC';
+         
+        $ms = empty($_REQUEST['_multisort']) ? false : $_REQUEST['_multisort'];
+        //var_Dump($ms);exit;
+        $sorted = false;
+        if (method_exists($x, 'applySort')) {
+            $sorted = $x->applySort(
+                    $this->authUser,
+                    $sort,
+                    $dir,
+                    array_keys($this->cols),
+                    $ms ? json_decode($ms) : false
+            );
         }
-       
-        
-        $this->loadMap($x, array(
-            'columns' => $_columns,
-
-        ));
-        
-        if ($req !== false) { 
-            $this->setFilters($x, $req);
+        if ($ms !== false) {
+            return $this->multiSort($x);
         }
         
-        if (is_array($id)) {
-            // lookup...
-            $x->setFrom($req['lookup'] );
-            $x->limit(1);
-            if (!$x->find(true)) {
-                if (!empty($id['_id'])) {
-                    // standardize this?
-                    $this->jok($x->toArray());
+        if ($sorted === false) {
+            
+            $cols = $x->table();
+            $excols = array_keys($this->cols);
+            //print_R($excols);
+            
+            if (isset($x->_extra_cols)) {
+                $excols = array_merge($excols, $x->_extra_cols);
+            }
+            $sort_ar = explode(',', $sort);
+            $sort_str = array();
+          
+            foreach($sort_ar as $sort) {
+                
+                if (strlen($sort) && isset($cols[$sort]) ) {
+                    $sort_str[] =  $x->tableName() .'.'.$sort . ' ' . $dir ;
+                    
+                } else if (in_array($sort, $excols)) {
+                    $sort_str[] = $sort . ' ' . $dir ;
                 }
-                $this->jok(false);
             }
-            
-        } else if (!$x->get($id)) {
-            $this->jerr("selectSingle: no such record ($id)");
+             
+            if ($sort_str) {
+                $x->orderBy(implode(', ', $sort_str ));
+            }
         }
+    }
+    
+    function toCsv($data, $cols, $titles, $filename, $addDate = true)
+    {
+        $this->sessionState(0); // turn off sessions  - no locking..
+
+        require_once 'Pman/Core/SimpleExcel.php';
         
-        // ignore perms if comming from update/insert - as it's already done...
-        if ($req !== false && !$this->checkPerm($x,'S'))  {
-            $this->jerr("PERMISSION DENIED - si");
-        }
-        // different symantics on all these calls??
-        if (method_exists($x, 'toRooSingleArray')) {
-            $this->jok($x->toRooSingleArray($this->authUser, $req));
-        }
-        if (method_exists($x, 'toRooArray')) {
-            $this->jok($x->toRooArray($req));
-        }
+        $fn = (empty($filename) ? 'list-export-' : urlencode($filename)) . (($addDate) ? date('Y-m-d') : '') ;
         
-        $this->jok($x->toArray());
         
+        $se_config=  array(
+            'workbook' => substr($fn, 0, 31),
+            'cols' => array(),
+            'leave_open' => true
+        );
         
-    }
-    
-    function setFilters($x, $q)
-    {
-        if (method_exists($x, 'applyFilters')) {
-           // DB_DataObject::debugLevel(1);
-            if (false === $x->applyFilters($q, $this->getAuthUser(), $this)) {
-                return; 
-            } 
-        }
-        $q_filtered = array();
         
-        $keys = $x->keys();
-        // var_dump($keys);exit;
-        foreach($q as $key=>$val) {
-            
-            if (in_array($key,$keys) && !is_array($val)) {
-               
-                $x->$key  = $val;
-            }
-            
-             // handles name[]=fred&name[]=brian => name in ('fred', 'brian').
-            // value is an array..
-            if (is_array($val) ) {
+        $se = false;
+        if (is_object($data)) {
+            $rooar = method_exists($data, 'toRooArray');
+            while($data->fetch()) {
+                $x = $rooar  ? $data->toRooArray($q) : $data->toArray();
                 
-                $pref = '';
                 
-                if ($key[0] == '!') {
-                    $pref = '!';
-                    $key = substr($key,1);
+                if ($cols == '*') {  /// did we get cols sent to us?
+                    $cols = array_keys($x);
                 }
-                
-                if (!in_array( $key,  array_keys($this->cols))) {
-                    continue;
+                if ($titles== '*') {
+                    $titles= array_keys($x);
                 }
-                
-                // support a[0] a[1] ..... => whereAddIn(
-                $ar = array();
-                $quote = false;
-                foreach($val as $k=>$v) {
-                    if (!is_numeric($k)) {
-                        $ar = array();
-                        break;
-                    }
-                    // FIXME: note this is not typesafe for anything other than mysql..
+                if ($titles !== false) {
                     
-                    if (!is_numeric($v) || !is_long($v)) {
-                        $quote = true;
+                    foreach($cols as $i=>$col) {
+                        $se_config['cols'][] = array(
+                            'header'=> isset($titles[$i]) ? $titles[$i] : $col,
+                            'dataIndex'=> $col,
+                            'width'=>  100
+                        );
+                         $se = new Pman_Core_SimpleExcel(array(), $se_config);
+       
+                        
                     }
-                    $ar[] = $v;
-                    
-                }
-                if (count($ar)) {
                     
                     
-                    $x->whereAddIn($pref . (
-                        isset($this->colsJname[$key]) ? 
-                            $this->colsJname[$key] :
-                            ($x->tableName(). '.'.$key)),
-                        $ar, $quote ? 'string' : 'int');
+                    //fputcsv($fh, $titles);
+                    $titles = false;
                 }
                 
-                continue;
-            }
-            
-            
-            // handles !name=fred => name not equal fred.
-            if ($key[0] == '!' && in_array(substr($key, 1), array_keys($this->cols))) {
-                
-                $key  = substr($key, 1) ;
+
+                $se->addLine($se_config['workbook'], $x);
+                    
                 
-                $x->whereAdd(   (
-                        isset($this->colsJname[$key]) ? 
-                            $this->colsJname[$key] :
-                            $x->tableName(). '.'.$key ) . ' != ' .
-                    (is_numeric($val) ? $val : "'".  $x->escape($val) . "'")
-                );
-                continue;
+            }
+            if(!$se){
                 
+                $this->jerr('no data found', false, 'text/plain');
             }
+            $se->send($fn .'.xls');
+            exit;
             
-            
-            
-            switch($key) {
+        } 
+        
+        
+        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 ($titles !== false) {
+                foreach($cols as $i=>$col) {
+                    $se_config['cols'][] = array(
+                        'header'=> isset($titles[$i]) ? $titles[$i] : $col,
+                        'dataIndex'=> $col,
+                        'width'=>  100,
+                       //     'renderer' => array($this, 'getThumb'),
+                         //   'color' => 'yellow', // set color for the cell which is a header element
+                          // 'fillBlank' => 'gray', // set 
+                    );
+                    $se = new Pman_Core_SimpleExcel(array(),$se_config);
+   
                     
-                // 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);
-                        $o = (int) $q['query']['original'];
-                        $oid = (int) $val;
-                        $x->whereAdd("(on_id = $oid  OR 
-                                on_id IN ( SELECT distinct(id) FROM Documents WHERE original = $o ) 
-                            )");
-                        continue;
-                                
-                    }
-                    $x->on_id = $val;
+                }
                 
                 
-                default:
-                    if (strlen($val) && $key[0] != '_') {
-                        $q_filtered[$key] = $val;
-                    }
-                    
-                    // 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( "{$this->colsJname[$key]} = " . ($quote ? "'". $x->escape($val) ."'" : $val));
-                        
-                    }
-                    
-                    
-                    continue;
+                //fputcsv($fh, $titles);
+                $titles = false;
             }
-        }
-        if (!empty($q_filtered)) {
-            //var_dump($q_filtered);
             
             
             
-            $x->setFrom($q_filtered);
+            $se->addLine($se_config['workbook'], $x);
+        }
+        if(!$se){
+            $this->jerr('no data found');
         }
+        $se->send($fn .'.xls');
+        exit;
         
+    }
+    
+    function meta($x, $data)
+    {
+        $lost = 0;
+        $cols  = array_keys($data[0]);
+     
+        $options = &PEAR::getStaticProperty('DB_DataObject','options');
+        $reader = $options["ini_{$x->databaseNickname()}"] .'.reader';
+        if (!file_exists( $reader )) {
+            return;
+        }
         
+        $rdata = unserialize(file_get_contents($reader));
         
-       
-        // nice generic -- let's get rid of it.. where is it used!!!!
-        // used by: 
-        // Person / Group / Comapnies.... most of my queries noww...
-        if (!empty($q['query']['name'])) {
-            
-            
-            if (in_array( 'name',  array_keys($x->table()))) {
-                $x->whereAdd($x->tableName().".name LIKE '". $x->escape($q['query']['name']) . "%'");
+        $keys = $x->keys();
+        $key = empty($keys) ? 'id' : $keys[0];
+        
+        
+        $meta = array();
+        foreach($cols as $c ) {
+            if (!isset($this->cols[$c]) || !isset($rdata[$this->cols[$c]]) || !is_array($rdata[$this->cols[$c]])) {
+                $meta[] = $c;
+                continue;    
             }
+            $add = $rdata[$this->cols[$c]];
+            $add['name'] = $c;
+            $meta[] = $add;
         }
+        return array(
+            'totalProperty' =>  'total',
+            'successProperty' => 'success',
+            'root' => 'data',
+            'id' => $key, // was 'id'...
+            'fields' => $meta
+        );
+         
         
-        // - projectdirectory staff list - persn queuy
-     
+    }
+    
+    function multiSort($x)
+    {
+        $ms = json_decode($_REQUEST['_multisort']);
+        if (!isset($ms->order) || !is_array($ms->order)) {
+            return;
+        }
+        $sort_str = array();
         
+        $cols = $x->table();
+        
+        foreach($ms->order  as $col) {
+            if (!isset($ms->sort->{$col})) {
+                continue; // no direction..
+            }
+            $ms->sort->{$col} = $ms->sort->{$col}  == 'ASC' ? 'ASC' : 'DESC';
+            
+            if (strlen($col) && isset($cols[$col]) ) {
+                $sort_str[] =  $x->tableName() .'.'.$col . ' ' .  $ms->sort->{$col};
+                continue;
+            }
+            
+            if (in_array($col, array_keys($this->cols))) {
+                $sort_str[] = $col. ' ' . $ms->sort->{$col};
+                continue;
+            }
+            if (isset($x->_extra_cols) && in_array($col, $x->_extra_cols)) {
+                $sort_str[] = $col. ' ' . $ms->sort->{$col};
+            }
+        }
+         
+        if ($sort_str) {
+            $x->orderBy(implode(', ', $sort_str ));
+        }
     }
 }