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