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