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