Pman/Roo.php
[Pman.Base] / Pman / Roo.php
1 <?php
2
3
4 require_once 'Pman.php';
5 /**
6  * 
7  * 
8   * 
9  * 
10  * Uses these methods of the dataobjects:
11  * 
12  * - checkPerm('L'/'E'/'A', $authuser) - can we list the stuff
13  * 
14  * - applySort($au, $sortcol, $direction, $array_of_columns, $multisort) -- does not support multisort at present..
15  * - applyFilters($_REQUEST, $authUser, $roo) -- apply any query filters on data. and hide stuff not to be seen. (RETURN false to prevent default filters.)
16  * - postListExtra($_REQUEST, $roo, $array_data) : array(extra_name => data) - add extra column data on the results (like new messages etc.)
17  * - postListFilter($data, $authUser, $request) return $data - add extra data to an object
18  * 
19  * - toRooSingleArray($authUser, $request) // single fetch, add data..
20  * - toRooArray($request) /// toArray if you need to return different data.. for a list fetch.
21  *
22  * 
23  *  CRUD - before/after handlers..
24  * - setFromRoo($ar, $roo) - values from post (deal with dates etc.) - return true|error string.
25  *      ... call $roo->jerr() on failure...
26  *
27  *  BEFORE
28  * - beforeDelete($dependants_array, $roo, $request) Argument is an array of un-find/fetched dependant items.
29  *                      - jerr() will stop insert.. (Prefered)
30  *                      - return false for fail and set DO->err;
31  * - beforeUpdate($old, $request,$roo) - after update - jerr() will stop insert..
32  * - beforeInsert($request,$roo) - before insert - jerr() will stop insert..
33  *
34  *  AFTER
35  * - onUpdate($old, $request,$roo, $event) - after update // return value ignored
36  * - onInsert($request,$roo, $event) - after insert
37  * - onDelete($req, $roo) - after delete
38  * - onUpload($roo)
39  *  
40  * - toEventString (for logging - this is generically prefixed to all database operations.)
41  */
42
43 class Pman_Roo extends Pman
44 {
45     /**
46      * if set to an array (when extending this, then you can restrict which tables are available
47      */
48     var $validTables = false; 
49     
50     var $key; // used by update currenly to store primary key.
51     
52      
53     var $max_limit = 10000;
54     
55     var $debugEnabled = true; // disable this for public versions of this code.
56     
57     var $do = false; // the dataobject being worked on..
58     
59     function getAuth()
60     {
61         parent::getAuth(); // load company!
62         $au = $this->getAuthUser();
63        
64         if (!$au) {  
65             $this->jerr("Not authenticated", array('authFailure' => true));
66         }
67         if (!$au->pid()   ) { // not set up yet..
68             $this->jerr("Not authenticated", array('authFailure' => true));
69         }
70         
71         
72         $this->authUser = $au;
73         return true;
74     }
75     /**
76      * GET method   Roo/TABLENAME
77      *
78      * Generally for SELECT or Single SELECT
79      *
80      * Single SELECT:
81      *    _id=value          single fetch based on primary id.
82      *                       can be '0' if you want to fetch a set of defaults
83      *                       Use in conjuntion with toRooSingleArray()
84      *                      
85      *    lookup[key]=value  single fetch based on a single key value lookup.
86      *                       multiple key/value can be used. eg. ontable+onid..
87      *    _columns           what to return.
88      * 
89      *    _no_count          
90      *
91      *    
92      * JOINS:
93      *  - all tables are always autojoined.
94      * 
95      * Search SELECT
96      *    COLUMNS to fetch
97      *      _columns=a,b,c,d     comma seperated list of columns.
98      *      _exclude_columns=a,b,c,d   comma seperated list of columns.
99      *      _distinct=name        a distinct column lookup. you also have to use _columns with this.
100      *
101      *    WHERE (searches)
102      *       colname = ...              => colname = ....
103      *       !colname=....                 => colname != ....
104      *       !colname[0]=... !colname[1]=... => colname NOT IN (.....) ** only supports main table at present..
105      *       colname[0]=... colname[1]=... => colname IN (.....) ** only supports main table at present..
106      *
107      *    ORDER BY
108      *       sort=name          what to sort.
109      *       sort=a,b,d         can support multiple columns
110      *       dir=ASC            what direction
111      *       _multisort ={...}  JSON encoded { sort : { row : direction }, order : [ row, row, row ] }
112      *
113      *    LIMIT
114      *      start=0         limit start
115      *      limit=25        limit number 
116      * 
117      * 
118      *    Simple CSV support
119      *      csvCols[0] csvCols[1]....    = .... column titles for CSV output
120      *      csvTitles[0], csvTitles[1] ....  = columns to use for CSV output
121      *
122      *  Depricated  
123      *      _toggleActive !:!:!:! - this hsould not really be here..
124      *      query[add_blank] - add a line in with an empty option...  - not really needed???
125      *      _delete    = delete a list of ids element. (depricated.. this will be removed...)
126      * 
127      * DEBUGGING
128      *  _post   =1    = simulate a post with debuggin on.
129      *  _debug_post << This is prefered, as _post may overlap with accouting posts..
130      *  
131      *  _debug     = turn on DB_dataobject deubbing, must be admin at present..
132      *
133      *
134      * CALLS methods on dataobjects if they exist
135      *
136      * 
137      *   checkPerm('S' , $authuser)
138      *                      - can we list the stuff
139      *                      - return false to disallow...
140      *   applySort($au, $sortcol, $direction, $array_of_columns, $multisort)
141      *                     -- does not support multisort at present..
142      *   applyFilters($_REQUEST, $authUser, $roo)
143      *                     -- apply any query filters on data. and hide stuff not to be seen.
144      *                     -- can exit by calling $roo->jerr()
145      *   postListExtra($_REQUEST, $roo, $array_data) : array(extra_name => data)
146      *                     - add extra column to the jdata return key/value info.
147      *   postListFilter($data, $authUser, $request) return $data
148      *                      - modify the returned array of data (either add stuff to the data, or remove lines etc)
149      * 
150      *   
151      *   toRooSingleArray($authUser, $request) : array
152      *                       - called on single fetch only, add or maniuplate returned array data.
153      *                       - is also called when _id=0 is used (for fetching a default set.)
154      *   toRooArray($request) : array
155      *                      - called if singleArray is unavailable on single fetch.
156      *                      - always tried for mutiple results.
157      *   toArray()          - the default method if none of the others are found.
158      *   toSimpleExcelColumn($col) - see toCSV - this enables special columns to be created for exported data.
159      *   
160      *   autoJoin($request) 
161      *                      - standard DataObject feature - causes all results to show all
162      *                        referenced data.
163      *
164      * PROPERTIES:
165      *    _extra_cols  -- if set, then filtering by column etc. will use them.
166      *
167      
168      */
169     function get($tab, $opts = Array())
170     {
171          //  $this->jerr("Not authenticated", array('authFailure' => true));
172        //echo '<PRE>';print_R($_GET);
173       //DB_DataObject::debuglevel(1);
174         
175         $this->init(); // from pman.
176         //DB_DataObject::debuglevel(1);
177         HTML_FlexyFramework::get()->generateDataobjectsCache($this->isDev && !empty($_REQUEST['isDev']));
178         
179    
180         
181         // debugging...
182         
183         
184         
185         if ( $this->checkDebugPost()) {
186                     
187             
188             
189             $_POST  = $_GET;
190             //DB_DAtaObject::debuglevel(1);
191             return $this->post($tab);
192         }
193         
194         $this->checkDebug();
195         $this->initErrorHandling();
196    
197         $tt = explode('/', $tab);
198         $tab = array_shift($tt);
199         $x = $this->dataObject($tab);
200         
201         $_columns = !empty($_REQUEST['_columns']) ? explode(',', $_REQUEST['_columns']) : false;
202         
203         if (isset( $_REQUEST['lookup'] ) && is_array($_REQUEST['lookup'] )) { // single fetch based on key/value pairs
204              $this->selectSingle($x, $_REQUEST['lookup'],$_REQUEST);
205              // actually exits.
206         }
207         
208         
209         // single fetch (use '0' to fetch an empty object..)
210         if (isset($_REQUEST['_id']) && is_numeric($_REQUEST['_id'])) {
211              
212              $this->selectSingle($x, $_REQUEST['_id'],$_REQUEST);
213              // actually exits.
214         }
215         
216         // Depricated...
217
218        
219         if (isset($_REQUEST['_delete'])) {
220             $this->jerr("DELETE by GET has been removed - update the code to use POST");
221            
222         } 
223         
224         
225         // Depricated...
226         
227         if (isset($_REQUEST['_toggleActive'])) {
228             // do we really delete stuff!?!?!?
229             if (!$this->hasPerm("Core.Staff", 'E'))  {
230                 $this->jerr("PERMISSION DENIED (ta)");
231             }
232             $clean = create_function('$v', 'return (int)$v;');
233             $bits = array_map($clean, explode(',', $_REQUEST['_toggleActive']));
234             if (in_array($this->authUser->id, $bits) && $this->authUser->active) {
235                 $this->jerr("you can not disable yourself");
236             }
237             $x->query('UPDATE core_person SET active = !active WHERE id IN (' .implode(',', $bits).')');
238             $this->addEvent("USERTOGGLE", false, implode(',', $bits));
239             $this->jok("Updated");
240             
241         }
242        //DB_DataObject::debugLevel(1);
243        
244         // sets map and countWhat
245         $this->loadMap($x, array(
246                 'columns' => $_columns,
247                 'distinct' => empty($_REQUEST['_distinct']) ? false:  $_REQUEST['_distinct'],
248                 'exclude' => empty($_REQUEST['_exclude_columns']) ? false:  explode(',', $_REQUEST['_exclude_columns'])
249         ));
250         
251         
252         $this->setFilters($x,$_REQUEST);
253         
254         if (!$this->checkPerm($x,'S', $_REQUEST))  {
255             $this->jerr("PERMISSION DENIED (g)");
256         }
257         
258          //print_r($x);
259         // build join if req.
260           //DB_DataObject::debugLevel(1);
261         // count with multiple joins and no conditions can be quite slow - so if there are no conditions - just remove the joins from the count.
262         $xx = clone($x);
263         $old_where = $x->whereAdd();
264         if (empty($old_where )) {
265             $xx->_join = '';
266         } else {
267             $x->whereAdd($old_where);
268             $xx=clone($x);
269             
270         }
271         
272         if (!isset($_REQUEST['_no_count'])) {
273             $total = $xx->count($this->countWhat);
274         }
275         // sorting..
276       //   
277         // var_dump($total);exit;
278         $this->applySort($x);
279         
280         $fake_limit = false;
281         
282         if (!empty($_REQUEST['_distinct']) && isset($total) && $total < 400) {
283             $fake_limit  = true;
284         }
285         
286         if (!$fake_limit) {
287  
288             $x->limit(
289                 empty($_REQUEST['start']) ? 0 : (int)$_REQUEST['start'],
290                 min(empty($_REQUEST['limit']) ? 25 : (int)$_REQUEST['limit'], $this->max_limit)
291             );
292         } 
293         $queryObj = clone($x);
294         //DB_DataObject::debuglevel(1);
295         
296         $this->sessionState(0);
297         $res = $x->find();
298         $this->sessionState(1);
299                 
300         if (false === $res) {
301             $this->jerr($x->_lastError->toString());
302             
303         }
304         
305         
306         
307         $ret = array();
308         
309         // ---------------- THESE ARE DEPRICATED.. they should be moved to the model...
310         
311         
312         if (!empty($_REQUEST['query']['add_blank'])) {
313             $ret[] = array( 'id' => 0, 'name' => '----');
314             if(isset($total)) {
315                 $total+=1;
316             }
317         }
318          
319         $rooar = method_exists($x, 'toRooArray');
320         $_columnsf = $_columns  ? array_flip($_columns) : false;
321         while ($x->fetch()) {
322             //print_R($x);exit;
323             $add = $rooar  ? $x->toRooArray($_REQUEST) : $x->toArray();
324             if ($add === false) {
325                 continue;
326             }
327             $ret[] =  !$_columns ? $add : array_intersect_key($add, $_columnsf);
328         }
329         
330         if ($fake_limit) {
331             $ret = array_slice($ret,
332                    empty($_REQUEST['start']) ? 0 : (int)$_REQUEST['start'],
333                     min(empty($_REQUEST['limit']) ? 25 : (int)$_REQUEST['limit'], 10000)
334             );
335             
336         }
337         
338         
339         $extra = false;
340         if (method_exists($queryObj ,'postListExtra')) {
341             $extra = $queryObj->postListExtra($_REQUEST, $this, $ret);
342         }
343         
344         
345         // filter results, and add any data that is needed...
346         if (method_exists($x,'postListFilter')) {
347             $ret = $x->postListFilter($ret, $this->authUser, $_REQUEST);
348         }
349         
350         
351         
352         if (!empty($_REQUEST['csvCols']) && !empty($_REQUEST['csvTitles']) ) {
353             
354             
355             $this->toCsv($ret, $_REQUEST['csvCols'], $_REQUEST['csvTitles'],
356                         empty($_REQUEST['csvFilename']) ? '' : $_REQUEST['csvFilename'] );
357             
358             
359         
360         }
361         
362         
363         if (!empty($_REQUEST['_requestMeta']) &&  count($ret)) {
364             $meta = $this->meta($x, $ret);
365             if ($meta) {
366                 $extra = $extra ? $extra: array();
367                 $extra['metaData'] = $meta;
368             }
369         }
370         // this make take some time...
371         $this->sessionState(0);
372        // echo "<PRE>"; print_r($ret);
373         $this->jdata($ret, max(count($ret), isset($total) ? $total : 0), $extra );
374
375     
376     }
377     function checkDebug($req = false)
378     {
379         $req =  $req === false  ? $_REQUEST : $req;
380         
381         if (empty($req['_debug'])) {
382             return false;
383         }
384         
385         if (!empty($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST'] == 'localhost') {
386             DB_DAtaObject::debuglevel((int)$req['_debug']);
387             return;
388         }
389         
390         if ($this->authUser
391                 &&
392                 (
393                     (
394                         method_exists($this->authUser,'canDebug')
395                         &&
396                         $this->authUser->canDebug()
397                     )
398                 ||
399                     (  
400                     
401                         method_exists($this->authUser,'groups') 
402                         &&
403                         is_a($this->authUser, 'Pman_Core_DataObjects_Core_person')
404                         &&
405                         in_array('Administrators', $this->authUser->groups('name'))
406                     )
407                 )
408                 
409             ){
410             DB_DAtaObject::debuglevel((int)$req['_debug']);
411         }
412         
413     }
414     
415     function checkDebugPost()
416     {
417         if (empty($_GET['_post']) && empty($_GET['_debug_post'])) {
418             return false;
419         }
420         // localhost can do anything...
421         if (!empty($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST'] == 'localhost') {
422             return true;
423         }
424         return $this->authUser && 
425                     method_exists($this->authUser,'groups') &&
426                     in_array('Administrators', $this->authUser->groups('name')); 
427         
428     }
429     
430     function checkPerm($obj, $lvl, $req= null)
431     {
432         if (!method_exists($obj, 'checkPerm')) {
433             return true;
434         }
435         if ($obj->checkPerm($lvl, $this->authUser, $req))  {
436             return true;
437         }
438         return false;
439     }
440     
441     function toCsv($data, $cols, $titles, $filename, $addDate = true)
442     {
443          // die('here');
444         $this->sessionState(0); // turn off sessions  - no locking..
445
446         require_once 'Pman/Core/SimpleExcel.php';
447         
448         $fn = (empty($filename) ? 'list-export-' : urlencode($filename)) . (($addDate) ? date('Y-m-d') : '') ;
449         
450         
451         $se_config=  array(
452             'workbook' => substr($fn, 0, 31),
453             'cols' => array(),
454             'leave_open' => true
455         );
456         
457         
458         $se = false;
459         if (is_object($data)) {
460             $rooar = method_exists($data, 'toRooArray');
461             while($data->fetch()) {
462                 $x = $rooar  ? $data->toRooArray($q) : $data->toArray();
463                  
464                 if ($cols == '*') {  /// did we get cols sent to us?
465                     $cols = array_keys($x);
466                 }
467                 
468                 if(!is_array($cols)) {
469                     $cols = explode(',', $cols);
470                 }
471                
472                 if ($titles !== false) {
473                     if ($titles== '*') {
474                         $titles= array_keys($x);
475                     }
476                     if(!is_array($titles)) {
477                         $titles = explode(',', $titles);
478                     }
479                     foreach($cols as $i=>$col) {
480                         $add = array(
481                             'header'=> isset($titles[$i]) ? $titles[$i] : $col,
482                             'dataIndex'=> $col,
483                             'width'=>  100,
484                            //     'renderer' => array($this, 'getThumb'),
485                              //   'color' => 'yellow', // set color for the cell which is a header element
486                               // 'fillBlank' => 'gray', // set 
487                         );
488                         //die('here');
489                         if (method_exists($data, 'toSimpleExcelColumn')) {
490                             $add = $data->toSimpleExcelColumn($add);
491                         } 
492                         
493                         $se_config['cols'][] = $add;
494                         
495        
496                         
497                     }
498                     $se = new Pman_Core_SimpleExcel(array(), $se_config);
499                      
500                     $titles = false;
501                 }
502                 
503
504                 $se->addLine($se_config['workbook'], $x);
505                     
506                 
507             }
508             if(!$se){
509                 
510                 $this->jerr('no data found', false, 'text/plain');
511             }
512             $se->send($fn .'.xls');
513             exit;
514             
515         } 
516         
517          foreach($data as $x) {
518             //echo "<PRE>"; print_r(array($_REQUEST['csvCols'], $x->toArray())); exit;
519             $line = array();
520             
521             if ($cols== '*') {
522                 $cols= array_keys($x);
523             }
524             
525             if(!is_array($cols)) {
526                 $cols = explode(',', $cols);
527             }
528
529             if ($titles !== false) {
530                 if ($titles== '*') {
531                     $titles= array_keys($x);
532                 }
533
534                 if(!is_array($titles)) {
535                     $titles = explode(',', $titles);
536                 }
537
538                 foreach($cols as $i=>$col) {
539                     $add = array(
540                         'header'=> isset($titles[$i]) ? $titles[$i] : $col,
541                         'dataIndex'=> $col,
542                         'width'=>  100,
543                        //     'renderer' => array($this, 'getThumb'),
544                          //   'color' => 'yellow', // set color for the cell which is a header element
545                           // 'fillBlank' => 'gray', // set 
546                     );
547                     //die('here');
548                     if (method_exists($this->do, 'toSimpleExcelColumn')) {
549                         $add = $this->do->toSimpleExcelColumn($add);
550                     } 
551                     
552                     $se_config['cols'][] = $add;
553                     
554    
555                     
556                 }
557                 $se = new Pman_Core_SimpleExcel(array(),$se_config);
558                
559                 
560                 //fputcsv($fh, $titles);
561                 $titles = false;
562             }
563             
564             $se->addLine($se_config['workbook'], $x);
565         }
566         
567         if(!$se){
568             $this->jerr('no data found');
569         }
570         
571         $se->send($fn .'.xls');
572         exit;
573         
574     }
575     
576     
577      /**
578      * POST method   Roo/TABLENAME  
579      * -- creates, updates, or deletes data.
580      *
581      * INSERT
582      *    if the primary key is empty, this happens
583      *    will automatically set these to current date and authUser->id
584      *        created, created_by, created_dt
585      *        updated, update_by, updated_dt
586      *        modified, modified_by, modified_dt
587      *        
588      *   will return a GET request SINGLE SELECT (and accepts same)
589      *    
590      * DELETE
591      *    _delete=1,2,3     delete a set of data.
592      * UPDATE
593      *    if the primary key value is set, then update occurs.
594      *    will automatically set these to current date and authUser->id
595      *        updated, update_by, updated_dt
596      *        modified, modified_by, modified_dt
597      *        
598      *
599      * Params:
600      *   _delete=1,2,3   causes a delete to occur.
601      *   _ids=1,2,3,4    causes update to occur on all primary ids.
602      *  
603      *  RETURNS
604      *     = same as single SELECT GET request..
605      *
606      *
607      *
608      * DEBUGGING
609      *   _debug=1    forces debug
610      *   _get=1 - causes a get request to occur when doing a POST..
611      *
612      *
613      * CALLS
614      *   these methods on dataobjects if they exist
615      * 
616      *   checkPerm('E' / 'D' , $authuser)
617      *                      - can we list the stuff
618      *                      - return false to disallow...
619    
620      *   toRooSingleArray($authUser, $request) : array
621      *                       - called on single fetch only, add or maniuplate returned array data.
622      *   toRooArray($request) : array
623      *                      - Called if toSingleArray does not exist.
624      *                      - if you need to return different data than toArray..
625      *
626      *   toEventString()
627      *                  (for logging - this is generically prefixed to all database operations.)
628      *
629      *  
630      *   onUpload($roo)
631      *                  called when $_FILES is not empty
632      *
633      *                  
634      *   setFromRoo($ar, $roo)
635      *                      - alternative to setFrom() which is called if this method does not exist
636      *                      - values from post (deal with dates etc.) - return true|error string.
637      *                      - call $roo->jerr() on failure...
638      *
639      * CALLS BEFORE change occurs:
640      *  
641      *      beforeDelete($dependants_array, $roo)
642      *                      Argument is an array of un-find/fetched dependant items.
643      *                      - jerr() will stop insert.. (Prefered)
644      *                      - return false for fail and set DO->err;
645      *                      
646      *      beforeUpdate($old, $request,$roo)
647      *                      - before update - jerr() will stop insert..
648      *      beforeInsert($request,$roo)
649      *                      - before insert - jerr() will stop insert..
650      *
651      *
652      * CALLS AFTER change occured
653      * 
654      *      onUpdate($old, $request,$roo)
655      *               - after update // return value ignored
656      *
657      *      onInsert($request,$roo)
658      *                  - after insert
659      * 
660      *      onDelete($request, $roo) - after delete
661      * 
662      */                     
663      
664     function post($tab) // update / insert (?? delete??)
665     {
666         // -- why was this put in? - Roo is not related to Core.All ?
667         //if (!$this->hasPerm("Core.All", 'E'))  {
668         //        $this->jerr("PERMISSION DENIED (e)");
669         //}
670         $this->initErrorHandling();
671         
672         // DB_DataObject::debugLevel(1);
673         $this->checkDebug();
674         
675         if (!empty($_REQUEST['_get'])) {
676             return $this->get($tab);
677         }
678         
679         $this->init(); // for pman.
680          
681         $x = $this->dataObject($tab);
682
683         $this->transObj = clone($x);
684         
685         $this->transObj->query('BEGIN');
686         // find the key and use that to get the thing..
687         $keys = $x->keys();
688         if (empty($keys) ) {
689             $this->jerr('no key');
690         }
691         
692         $this->key = $keys[0];
693         
694           // delete should be here...
695         if (isset($_REQUEST['_delete'])) {
696             // do we really delete stuff!?!?!?
697             return $this->delete($x,$_REQUEST);
698         } 
699         
700         
701         
702         
703         $old = false;
704         
705         // not sure if this is a good idea here...
706
707         if (!empty($_REQUEST['_ids'])) {
708             $ids = explode(',',$_REQUEST['_ids']);
709             $x->whereAddIn($this->key, $ids, 'int');
710             $ar = $x->fetchAll();
711             
712             foreach($ar as $x) {
713                 $this->update($x, $_REQUEST);  
714             }
715             // all done..
716             $this->jok("UPDATED");
717             
718             
719         }
720          
721         if (!empty($_REQUEST[$this->key])) { 
722             // it's a create..
723             if (!$x->get($this->key, $_REQUEST[$this->key]))  {
724                 $this->jerr("Invalid request (id does not point to  a record.)");
725             }
726             $this->jok($this->update($x, $_REQUEST));
727         } else {
728             
729             if (empty($_POST)) {
730                 $this->jerr("No data recieved for inserting");
731             }
732
733             $this->jok($this->insert($x, $_REQUEST));
734             
735         }
736         
737         
738         
739     }
740     
741     
742     /**
743      * applySort
744      * 
745      * apply REQUEST[sort] and [dir]
746      * sort may be an array of columsn..
747      * 
748      * @arg   DB_DataObject $x
749      * 
750      */
751     function applySort($x, $sort = '', $dir ='')
752     {
753         
754         // Db_DataObject::debugLevel(1);
755         $sort = empty($_REQUEST['sort']) ? $sort : $_REQUEST['sort'];
756         $dir = empty($_REQUEST['dir']) ? $dir : $_REQUEST['dir'];
757         $dir = $dir == 'ASC' ? 'ASC' : 'DESC';
758          
759         $ms = empty($_REQUEST['_multisort']) ? false : $_REQUEST['_multisort'];
760         //var_Dump($ms);exit;
761         $sorted = false;
762         if (method_exists($x, 'applySort')) {
763             $sorted = $x->applySort(
764                     $this->authUser,
765                     $sort,
766                     $dir,
767                     array_keys($this->cols),
768                     $ms ? json_decode($ms) : false
769             );
770         }
771         
772         if ($ms !== false) {
773             return $this->multiSort($x);
774         }
775  
776         if ($sorted === false) {
777             $cols = $x->tableColumns();
778             $excols = array_keys($this->cols);
779             
780             if (isset($x->_extra_cols)) {
781                 $excols = array_merge($excols, $x->_extra_cols);
782             }
783             $sort_ar = explode(',', $sort);
784             $sort_str = array();
785           
786             foreach($sort_ar as $sort) {
787                 
788                 if (strlen($sort) && isset($cols[$sort]) ) {
789                     $sort_str[] =  $x->tableName() .'.'.$sort . ' ' . $dir ;
790                     
791                 } else if (in_array($sort, $excols)) {
792                     $sort_str[] = $sort . ' ' . $dir ;
793                 }
794             }
795              
796             if ($sort_str) {
797                 $x->orderBy(implode(', ', $sort_str ));
798             }
799         }
800     }
801     /**
802      * Multisort support
803      *
804      * _multisort
805      *
806      *
807      */
808     function multiSort($x)
809     {
810         //DB_DataObject::debugLevel(1);
811         $ms = json_decode($_REQUEST['_multisort']);
812         if (!isset($ms->order) || !is_array($ms->order)) {
813             return;
814         }
815         $sort_str = array();
816         
817         $cols = $x->tableColumns();
818         
819         //print_r($this->cols);exit;
820         // this-><cols contains  colname => aliased name...
821         foreach($ms->order  as $col) {
822             if (!isset($ms->sort->{$col})) {
823                 continue; // no direction..
824             }
825             $ms->sort->{$col} = $ms->sort->{$col}  == 'ASC' ? 'ASC' : 'DESC';
826             
827             if (strlen($col) && isset($cols[$col]) ) {
828                 $sort_str[] =  $x->tableName() .'.'.$col . ' ' .  $ms->sort->{$col};
829                 continue;
830             }
831             //print_r($this->cols);
832             
833             if (in_array($col, array_keys($this->cols))) {
834                 $sort_str[] = $col. ' ' . $ms->sort->{$col};
835                 continue;
836             }
837             if (isset($x->_extra_cols) && in_array($col, $x->_extra_cols)) {
838                 $sort_str[] = $col. ' ' . $ms->sort->{$col};
839             }
840         }
841          
842         if ($sort_str) {
843             $x->orderBy(implode(', ', $sort_str ));
844         }
845           
846         
847     }
848     /**
849      * single select call
850      * - used when _id is set, or after insert or update
851      *
852      * @param DataObject $x the dataobject to use
853      * @param int $id       the pid of the object
854      * @param array $req    the request, or false if it comes from insert/update.
855      *
856      */
857     function selectSingle($x, $id, $req=false)
858     {
859          
860         
861         $_columns = !empty($req['_columns']) ? explode(',', $req['_columns']) : false;
862
863         //var_dump(array(!is_array($id) , empty($id)));
864         if (!is_array($id) && empty($id)) {
865             
866             
867             if (method_exists($x, 'toRooSingleArray')) {
868                 $this->jok($x->toRooSingleArray($this->authUser, $req));
869             }
870             if (method_exists($x, 'toRooArray')) {
871                 $this->jok($x->toRooArray($req));
872             }
873             
874             $this->jok($x->toArray());
875         }
876        
877         
878         $this->loadMap($x, array(
879                     'columns' => $_columns,
880                      
881             ));
882         if ($req !== false) { 
883             $this->setFilters($x, $req);
884         } else if (method_exists($x, 'applyFilters')) {
885             // always call apply filters even after update/insert...
886             // however arguments are not passed.
887             $x->applyFilters(array('_is_update_request' => true), $this->authUser, $this);
888         }
889         
890         // DB_DataObject::DebugLevel(1);
891         if (is_array($id)) {
892             // lookup...
893             $x->setFrom($req['lookup'] );
894             $x->limit(1);
895             if (!$x->find(true)) {
896                 if (!empty($id['_id'])) {
897                     // standardize this?
898                     $this->jok($x->toArray());
899                 }
900                 $this->jok(false);
901             }
902             
903         } else if (!$x->get($id)) {
904             $this->jerr("selectSingle: no such record ($id)");
905         }
906         
907         // ignore perms if comming from update/insert - as it's already done...
908         if ($req !== false && !$this->checkPerm($x,'S'))  {
909             $this->jerr("PERMISSION DENIED - si");
910         }
911         // different symantics on all these calls??
912         if (method_exists($x, 'toRooSingleArray')) {
913             $this->jok($x->toRooSingleArray($this->authUser, $req));
914         }
915         if (method_exists($x, 'toRooArray')) {
916             $this->jok($x->toRooArray($req));
917         }
918         $this->jok($x->toArray());
919         
920         
921     }
922     
923     function insert($x, $req, $with_perm_check = true)
924     {
925          if (method_exists($x, 'setFromRoo')) {
926             $res = $x->setFromRoo($req, $this);
927             if (is_string($res)) {
928                 $this->jerr($res);
929             }
930         } else {
931             $x->setFrom($req);
932         }
933
934         if ( $with_perm_check &&  !$this->checkPerm($x,'A', $req))  {
935             $this->jerr("PERMISSION DENIED (i)");
936         }
937         $cols = $x->tableColumns();
938      
939         if (isset($cols['created'])) {
940             $x->created = date('Y-m-d H:i:s');
941         }
942         if (isset($cols['created_dt'])) {
943             $x->created_dt = date('Y-m-d H:i:s');
944         }
945         if (isset($cols['created_by'])) {
946             $x->created_by = $this->authUser->id;
947         }
948         
949         if (isset($cols['modified'])) {
950             $x->modified = date('Y-m-d H:i:s');
951         }
952         if (isset($cols['modified_dt'])) {
953             $x->modified_dt = date('Y-m-d H:i:s');
954         }
955         if (isset($cols['modified_by'])) {
956             $x->modified_by = $this->authUser->id;
957         }
958         
959         if (isset($cols['updated'])) {
960             $x->updated = date('Y-m-d H:i:s');
961         }
962         if (isset($cols['updated_dt'])) {
963             $x->updated_dt = date('Y-m-d H:i:s');
964         }
965         if (isset($cols['updated_by'])) {
966             $x->updated_by = $this->authUser->id;
967         }
968         
969         if (method_exists($x, 'beforeInsert')) {
970             $x->beforeInsert($_REQUEST, $this);
971         }
972         
973         $res = $x->insert();
974
975         if ($res === false) {
976             $this->jerr($x->_lastError->toString());
977         }
978         $ev = $this->addEvent("ADD", $x);
979         if (method_exists($x, 'onInsert')) {
980                     
981             $x->onInsert($_REQUEST, $this, $ev);
982         }
983         
984         if ($ev) { 
985             $ev->audit($x);
986         }
987       
988         // note setFrom might handle this before hand...!??!
989         if (!empty($_FILES) && method_exists($x, 'onUpload')) {
990             $x->onUpload($this, $_REQUEST);
991         }
992         
993         return $this->selectSingle(
994             DB_DataObject::factory($x->tableName()),
995             $x->pid()
996         );
997         
998     }
999     
1000     function updateLock($x, $req )
1001     {
1002         Pman::$permitError = true; // allow it to fail without dieing
1003         
1004         $lock = DB_DataObjecT::factory('Core_locking');
1005         Pman::$permitError = false; 
1006         if (is_a($lock,'DB_DataObject') && $this->authUser)  {
1007                  
1008             $lock->on_id = $x->{$this->key};
1009             $lock->on_table= strtolower($x->tableName());
1010             if (!empty($_REQUEST['_lock_id'])) {
1011                 $lock->whereAdd('id != ' . ((int)$_REQUEST['_lock_id']));
1012             } else {
1013                 $lock->whereAdd('person_id !=' . $this->authUser->id);
1014             }
1015             
1016             $llc = clone($lock);
1017             $exp = date('Y-m-d', strtotime('NOW - 1 WEEK'));
1018             $llc->whereAdd("created < '$exp'");
1019             if ($llc->count()) {
1020                 $llc->find();
1021                 while($llc->fetch()) {
1022                     $llcd = clone($llc);
1023                     $llcd->delete();
1024                 }
1025             }
1026             
1027             $lock->limit(1);
1028             if ($lock->find(true)) {
1029                 // it's locked by someone else..
1030                $p = $lock->person();
1031                
1032                
1033                $this->jerr( "Record was locked by " . $p->name . " at " .$lock->created.
1034                            " - Please confirm you wish to save" 
1035                            , array('needs_confirm' => true)); 
1036           
1037               
1038             }
1039             // check the users lock.. - no point.. ??? - if there are no other locks and it's not the users, then they can 
1040             // edit it anyways...
1041             
1042             // can we find the user's lock.
1043             $lock = DB_DataObjecT::factory('Core_locking');
1044             $lock->on_id = $x->{$this->key};
1045             $lock->on_table= strtolower($x->tableName());
1046             $lock->person_id = $this->authUser->id;
1047             $lock->orderBy('created DESC');
1048             $lock->limit(1);
1049             
1050             if (
1051                     $lock->find(true) &&
1052                     isset($x->modified_dt) &&
1053                     strtotime($x->modified_dt) > strtotime($lock->created) &&
1054                     empty($req['_submit_confirmed']) &&
1055                $x->modified_by != $this->authUser->id   
1056                 )
1057             {
1058                 $p = DB_DataObject::factory('core_person');
1059                 $p->get($x->modified_by);
1060        $this->jerr($p->name . " saved the record since you started editing,\nDo you really want to update it?", array('needs_confirm' => true)); 
1061                 
1062             }
1063             
1064             
1065             
1066         }
1067         return $lock;
1068         
1069     }
1070     
1071     
1072     function update($x, $req,  $with_perm_check = true)
1073     {
1074         if ( $with_perm_check && !$this->checkPerm($x,'E', $req) )  {
1075             $this->jerr("PERMISSION DENIED - No Edit permissions on this element");
1076         }
1077        
1078         // check any locks..
1079         // only done if we recieve a lock_id.
1080         // we are very trusing here.. that someone has not messed around with locks..
1081         // the object might want to check in their checkPerm - if locking is essential..
1082         $lock = $this->updateLock($x,$req);
1083          
1084         
1085         
1086         
1087        
1088          
1089        
1090         $old = clone($x);
1091         $this->old = $x;
1092         // this lot is generic.. needs moving 
1093         if (method_exists($x, 'setFromRoo')) {
1094             $res = $x->setFromRoo($req, $this);
1095             if (is_string($res)) {
1096                 $this->jerr($res);
1097             }
1098         } else {
1099             $x->setFrom($req);
1100         }
1101       
1102         
1103         
1104         //echo '<PRE>';print_r($old);print_r($x);exit;
1105         //print_r($old);
1106         
1107         $cols = $x->tableColumns();
1108
1109         if (isset($cols['modified'])) {
1110             $x->modified = date('Y-m-d H:i:s');
1111         }
1112         if (isset($cols['modified_dt'])) {
1113             $x->modified_dt = date('Y-m-d H:i:s');
1114         }
1115         if (isset($cols['modified_by']) && $this->authUser) {
1116             $x->modified_by = $this->authUser->id;
1117         }
1118         
1119         if (isset($cols['updated'])) {
1120             $x->updated = date('Y-m-d H:i:s');
1121         }
1122         if (isset($cols['updated_dt'])) {
1123             $x->updated_dt = date('Y-m-d H:i:s');
1124         }
1125         if (isset($cols['updated_by']) && $this->authUser) {
1126             $x->updated_by = $this->authUser->id;
1127         }
1128         
1129         if (method_exists($x, 'beforeUpdate')) {
1130             $x->beforeUpdate($old, $req, $this);
1131         }
1132         
1133         if ($with_perm_check && !empty($_FILES) && method_exists($x, 'onUpload')) {
1134             $x->onUpload($this, $_REQUEST);
1135         }
1136         
1137         //DB_DataObject::DebugLevel(1);
1138         $res = $x->update($old);
1139         if ($res === false) {
1140             $this->jerr($x->_lastError->toString());
1141         }
1142         $ev = $this->addEvent("EDIT", $x);
1143
1144         if (method_exists($x, 'onUpdate')) {
1145             $x->onUpdate($old, $req, $this, $ev);
1146         }
1147         if ($ev) { 
1148             $ev->audit($x, $old);
1149         }
1150         
1151         
1152         return $this->selectSingle(
1153             DB_DataObject::factory($x->tableName()),
1154             $x->{$this->key}
1155         );
1156         
1157     }
1158     /**
1159      * Delete a number of records.
1160      * calls $delete_obj->beforeDelete($array_of_dependant_dataobjects, $this)
1161      *
1162      */
1163     
1164     function delete($x, $req)
1165     { 
1166         // do we really delete stuff!?!?!?
1167         if (empty($req['_delete'])) {
1168             $this->jerr("Delete Requested with no value");
1169         }
1170         
1171         
1172         // build a list of tables to queriy for dependant data..
1173         $map = $x->links();
1174         
1175         $affects  = array();
1176         
1177         $all_links = $x->databaseLinks();
1178         
1179         foreach($all_links as $tbl => $links) {
1180             foreach($links as $col => $totbl_col) {
1181                 $to = explode(':', $totbl_col);
1182                 if ($to[0] != $x->tableName()) {
1183                     continue;
1184                 }
1185                 
1186                 $affects[$tbl .'.' . $col] = true;
1187             }
1188         }
1189         // collect tables
1190
1191        // echo '<PRE>';print_r($affects);exit;
1192        // DB_Dataobject::debugLevel(1);
1193        
1194         
1195         
1196         
1197         $bits = array_map(function($v) { return (int)$v; } , explode(',', $req['_delete']));
1198         
1199         // let's assume it has a key!!!
1200         
1201         $x->whereAdd($this->key .'  IN ('. implode(',', $bits) .')');
1202         if (!$x->find()) {
1203             $this->jerr("Nothing found to delete");
1204         }
1205         $errs = array();
1206         while ($x->fetch()) {
1207             $xx = clone($x);
1208             
1209            
1210             // perms first.
1211             
1212             if (!$this->checkPerm($x,'D') )  {
1213                 $this->jerr("PERMISSION DENIED (d)");
1214             }
1215             
1216             $match_ar = array();
1217             foreach($affects as $k=> $true) {
1218                 $ka = explode('.', $k);
1219                 
1220                 $chk = DB_DataObject::factory($ka[0]);
1221                 if (!is_a($chk,'DB_DataObject') && !is_a($chk,'PDO_DataObject'))  {
1222                     $this->jerr('Unable to load referenced table, check the links config: ' .$ka[0]);
1223                 }
1224                // print_r(array($chk->tablename() , $ka[1] ,  $xx->tablename() , $this->key ));
1225                 $chk->{$ka[1]} =  $xx->{$this->key};
1226                 
1227                 if (count($chk->keys())) {
1228                     $matches = $chk->count();
1229                 } else {
1230                     //DB_DataObject::DebugLevel(1);
1231                     $matches = $chk->count($ka[1]);
1232                 }
1233                 
1234                 if ($matches) {
1235                     $chk->_match_key = $ka[1];
1236                     $match_ar[] = clone($chk);
1237                     continue;
1238                 }          
1239             }
1240             
1241             
1242             $has_beforeDelete = method_exists($xx, 'beforeDelete');
1243             // before delte = allows us to trash dependancies if needed..
1244             $match_total = 0;
1245             
1246             if ( $has_beforeDelete ) {
1247                 if ($xx->beforeDelete($match_ar, $this, $_REQUEST) === false) {
1248                     $errs[] = "Delete failed ({$xx->id})\n".
1249                         (isset($xx->err) ? $xx->err : '');
1250                     continue;
1251                 }
1252                 // refetch affects..
1253                 
1254                 $match_ar = array();
1255                 foreach($affects as $k=> $true) {
1256                     $ka = explode('.', $k);
1257                     $chk = DB_DataObject::factory($ka[0]);
1258                     if (!is_a($chk,'DB_DataObject') && !is_a($chk,'PDO_DataObject'))  {
1259                         $this->jerr('Unable to load referenced table, check the links config: ' .$ka[0]);
1260                     }
1261                     $chk->{$ka[1]} =  $xx->{$this->key};
1262                     $matches = $chk->count();
1263                     $match_total += $matches;
1264                     if ($matches) {
1265                         $chk->_match_key = $ka[1];
1266                         $match_ar[] = clone($chk);
1267                         continue;
1268                     }          
1269                 }
1270                 
1271             }
1272             
1273             if (!empty($match_ar)) {
1274                 $chk = $match_ar[0];
1275                 $chk->limit(1);
1276                 $o = $chk->fetchAll();
1277                 $key = isset($chk->_match_key) ?$chk->_match_key  : '?unknown column?';
1278                 $desc =  $chk->tableName(). '.' . $key .'='.$xx->{$this->key} ;
1279                 if (method_exists($chk, 'toEventString')) {
1280                     $desc .=  ' : ' . $o[0]->toEventString();
1281                 }
1282                 $this->jerr("Delete Dependant records ($match_total  found),  " .
1283                              "first is ( $desc )");
1284           
1285             }
1286             
1287             // now che 
1288             // finally log it.. 
1289             DB_DataObject::Factory('Events')->logDeletedRecord($x);
1290             
1291             $this->addEvent("DELETE", $x);
1292             
1293             $xx->delete();
1294             
1295             if (method_exists($xx,'onDelete')) {
1296                 $xx->onDelete($req, $this);
1297             }
1298             
1299             
1300         }
1301         if ($errs) {
1302             $this->jerr(implode("\n<BR>", $errs));
1303         }
1304         $this->jok("Deleted");
1305         
1306     }
1307    
1308     
1309     /**
1310      * cols stores the list of columns that are available from the query.
1311      *
1312      *
1313      * This is a dupe of what is in autojoin -- we should move to using autojoin really.
1314      *
1315      *
1316      * // changes:
1317      
1318       countWhat
1319       cols
1320       $this->colsJoinName
1321     
1322      *
1323      */
1324     
1325     var $cols = array();
1326     
1327     
1328     
1329     function loadMap($do, $cfg =array()) //$onlycolumns=false, $distinct = false) 
1330     {
1331        
1332         //DB_DataObject::debugLevel(5);
1333         $onlycolumns    = !empty($cfg['columns']) ? $cfg['columns'] : false;
1334         $distinct       = !empty($cfg['distinct']) ? $cfg['distinct'] : false;
1335         $excludecolumns = !empty($cfg['exclude']) ? $cfg['exclude'] : array();
1336           
1337         $excludecolumns[] = 'passwd'; // we never expose passwords
1338         $excludecolumns[] = 'oath_key';
1339        
1340         $ret = $do->autoJoin(array(
1341             'include' => $onlycolumns,
1342             'exclude' => $excludecolumns,
1343             'distinct' => $distinct
1344         ));
1345         
1346         $this->countWhat = $ret['count'];
1347         $this->cols = $ret['cols'];
1348         $this->colsJname = $ret['join_names'];
1349         
1350         
1351         return;
1352         
1353         
1354         
1355     }
1356     /**
1357      * generate the meta data neede by queries.
1358      * 
1359      */
1360     function meta($x, $data)
1361     {
1362         // this is not going to work on queries where the data does not match the database def..
1363         // for unknown columns we send them as stirngs..
1364         $lost = 0;
1365         $cols  = array_keys($data[0]);
1366      
1367         
1368         
1369         if (class_exists('PDO_DataObject')) {
1370             $options = PDO_DataObject::config();
1371             if (!file_exists($options["schema_location"] . '.reader')) {
1372                 return;
1373             }
1374            
1375             $rdata = unserialize(file_get_contents($options["schema_location"] . '.reader'));
1376           
1377         } else {
1378             //echo '<PRE>';print_r($this->cols); exit;
1379             $options = &PEAR::getStaticProperty('DB_DataObject','options');
1380             $reader = $options["ini_{$x->databaseNickname()}"] .'.reader';
1381             if (!file_exists( $reader )) {
1382                 return;
1383             }
1384             
1385             $rdata = unserialize(file_get_contents($reader));
1386         }
1387         
1388         //echo '<PRE>';print_r($this->cols);exit;
1389         //echo '<PRE>';print_r($rdata);exit;
1390        // echo '<PRE>';print_r($rdata);exit;
1391         
1392         $keys = $x->keys();
1393         $key = empty($keys) ? 'id' : $keys[0];
1394         
1395         
1396         $meta = array();
1397         foreach($cols as $c ) {
1398             if (!isset($this->cols[$c]) || !isset($rdata[$this->cols[$c]]) || !is_array($rdata[$this->cols[$c]])) {
1399                 $meta[] = $c;
1400                 continue;    
1401             }
1402             $add = $rdata[$this->cols[$c]];
1403             $add['name'] = $c;
1404             $meta[] = $add;
1405         }
1406         return array(
1407             'totalProperty' =>  'total',
1408             'successProperty' => 'success',
1409             'root' => 'data',
1410             'id' => $key, // was 'id'...
1411             'fields' => $meta
1412         );
1413          
1414         
1415     }
1416     
1417     function setFilters($x, $q)
1418     {
1419         // if a column is type int, and we get ',' -> the it should be come an inc clause..
1420        // DB_DataObject::debugLevel(1);
1421         if (method_exists($x, 'applyFilters')) {
1422            // DB_DataObject::debugLevel(1);
1423             if (false === $x->applyFilters($q, $this->authUser, $this)) {
1424                 return; 
1425             } 
1426         }
1427         $q_filtered = array();
1428         
1429         $keys = $x->keys();
1430
1431         foreach($q as $key=>$val) {
1432             
1433             if (in_array($key,$keys) && !is_array($val)) {
1434                
1435                 $x->$key  = $val;
1436             }
1437             
1438              // handles name[]=fred&name[]=brian => name in ('fred', 'brian').
1439             // value is an array..
1440             if (is_array($val) ) {
1441                 
1442                 $pref = '';
1443                 
1444                 if ($key[0] == '!') {
1445                     $pref = '!';
1446                     $key = substr($key,1);
1447                 }
1448                 
1449                 if (!in_array( $key,  array_keys($this->cols))) {
1450                     continue;
1451                 }
1452                 
1453                 // support a[0] a[1] ..... => whereAddIn(
1454                 $ar = array();
1455                 $quote = false;
1456                 foreach($val as $k=>$v) {
1457                     if (!is_numeric($k)) {
1458                         $ar = array();
1459                         break;
1460                     }
1461                     // FIXME: note this is not typesafe for anything other than mysql..
1462                     
1463                     if (!is_numeric($v) || !is_long($v)) {
1464                         $quote = true;
1465                     }
1466                     $ar[] = $v;
1467                     
1468                 }
1469                 if (count($ar)) {
1470                     
1471                     
1472                     $x->whereAddIn($pref . (
1473                         isset($this->colsJname[$key]) ? 
1474                             $this->colsJname[$key] :
1475                             ($x->tableName(). '.'.$key)),
1476                         $ar, $quote ? 'string' : 'int');
1477                 }
1478                 
1479                 continue;
1480             }
1481             
1482             
1483             // handles !name=fred => name not equal fred.
1484             if ($key[0] == '!' && in_array(substr($key, 1), array_keys($this->cols))) {
1485                 
1486                 $key  = substr($key, 1) ;
1487                 
1488                 $x->whereAdd(   (
1489                         isset($this->colsJname[$key]) ? 
1490                             $this->colsJname[$key] :
1491                             $x->tableName(). '.'.$key ) . ' != ' .
1492                     (is_numeric($val) ? $val : "'".  $x->escape($val) . "'")
1493                 );
1494                 continue;
1495                 
1496             }
1497             
1498                 
1499             
1500             switch($key) {
1501                     
1502                 // Events and remarks -- fixme - move to events/remarsk...
1503                 case 'on_id':  // where TF is this used...
1504                     if (!empty($q['query']['original'])) {
1505                       //  DB_DataObject::debugLevel(1);
1506                         $o = (int) $q['query']['original'];
1507                         $oid = (int) $val;
1508                         $x->whereAdd("(on_id = $oid  OR 
1509                                 on_id IN ( SELECT distinct(id) FROM Documents WHERE original = $o ) 
1510                             )");
1511                         continue 2;
1512                                 
1513                     }
1514                     $x->on_id = $val;
1515                 
1516                 
1517                 default:
1518                     if (strlen($val) && $key[0] != '_') {
1519                         $q_filtered[$key] = $val;
1520                     }
1521                     
1522                     // subjoined columns = check the values.
1523                     // note this is not typesafe for anything other than mysql..
1524                     
1525                     if (isset($this->colsJname[$key])) {
1526                         
1527                         // the aobve rule for !strlen non-joined cols should apply to joined ones.
1528                         if (!strlen($val)) {
1529                             continue 2;
1530                         }
1531                         
1532                         
1533                         $quote = false;
1534                         if (!is_numeric($val) || !is_long($val)) {
1535                             $quote = true;
1536                         }
1537                         $x->whereAdd( "{$this->colsJname[$key]} = " . ($quote ? "'". $x->escape($val) ."'" : $val));
1538                         
1539                     }
1540                     
1541                     
1542                     continue 2;
1543             }
1544         }
1545         if (!empty($q_filtered)) {
1546             //var_dump($q_filtered);
1547             
1548             
1549             
1550             $x->setFrom($q_filtered);
1551         }
1552         
1553         
1554         
1555        
1556         // nice generic -- let's get rid of it.. where is it used!!!!
1557         // used by: 
1558         // Person / Group / Comapnies.... most of my queries noww...
1559         /*
1560         if (!empty($q['query']['name'])) {
1561             
1562             
1563             if (in_array( 'name',  array_keys($x->table()))) {
1564                 $x->whereAdd($x->tableName().".name LIKE '". $x->escape($q['query']['name']) . "%'");
1565             }
1566         }
1567         */
1568         
1569         // - projectdirectory staff list - persn queuy
1570      
1571         
1572     }
1573     /**
1574      * create the  dataobject from (usually the url)
1575      * This uses $this->validTables
1576      *           $this->validPrefix (later..)
1577      * to determine if class can be created..
1578      *
1579      */
1580      
1581     function dataObject($tab)
1582     {
1583         if (is_array($this->validTables) &&  !in_array($tab,$this->validTables)) {
1584             $this->jerr("Invalid url - not listed in validTables");
1585         }
1586         $tab = str_replace('/', '',$tab); // basic protection??
1587         
1588         $pm = HTML_FlexyFramework::get()->Pman;
1589         
1590         if (isset($pm['roo_alias'])) {
1591             $map = array_flip($pm['roo_alias']);
1592             if (isset($map[$tab])) {
1593                 $tab = $map[$tab];
1594             }
1595         }
1596         
1597         
1598         $x = DB_DataObject::factory($tab);
1599         
1600         if (!is_a($x, 'DB_DataObject') && !is_a($x, 'PDO_DataObject')) {
1601             $this->jerr('invalid url - no dataobject');
1602         }
1603         $this->do = $x;
1604         return $x;
1605         
1606     }
1607     
1608       
1609     
1610     
1611     
1612     
1613 }