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