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