fix unititialize value
[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 to the jdata return key/value info.
145      *   postListFilter($data, $authUser, $request) return $data
146      *                      - modify the returned array of data (either add stuff to the data, or remove lines etc)
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 = $extra ? $extra: array();
361                 $extra['metaData'] = $meta;
362             }
363         }
364         // this make take some time...
365         $this->sessionState(0);
366        // echo "<PRE>"; print_r($ret);
367         $this->jdata($ret, max(count($ret), $total), $extra );
368
369     
370     }
371     function checkDebug($req = false)
372     {
373         $req =  $req === false  ? $_REQUEST : $req;
374         
375         if (empty($req['_debug'])) {
376             return false;
377         }
378         
379         if (!empty($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST'] == 'localhost') {
380             DB_DAtaObject::debuglevel((int)$req['_debug']);
381             return;
382         }
383         
384         if ($this->authUser
385                 &&
386                 (
387                     (
388                         method_exists($this->authUser,'canDebug')
389                         &&
390                         $this->authUser->canDebug()
391                     )
392                 ||
393                     (  
394                     
395                         method_exists($this->authUser,'groups') 
396                         &&
397                         is_a($this->authUser, 'Pman_Core_DataObjects_Core_person')
398                         &&
399                         in_array('Administrators', $this->authUser->groups('name'))
400                     )
401                 )
402                 
403             ){
404             DB_DAtaObject::debuglevel((int)$req['_debug']);
405         }
406         
407     }
408     
409     function checkDebugPost()
410     {
411         if (empty($_GET['_post']) && empty($_GET['_debug_post'])) {
412             return false;
413         }
414         // localhost can do anything...
415         if (!empty($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST'] == 'localhost') {
416             return true;
417         }
418         return $this->authUser && 
419                     method_exists($this->authUser,'groups') &&
420                     in_array('Administrators', $this->authUser->groups('name')); 
421         
422     }
423     
424     function checkPerm($obj, $lvl, $req= null)
425     {
426         if (!method_exists($obj, 'checkPerm')) {
427             return true;
428         }
429         if ($obj->checkPerm($lvl, $this->authUser, $req))  {
430             return true;
431         }
432         return false;
433     }
434     
435     function toCsv($data, $cols, $titles, $filename, $addDate = true)
436     {
437          // die('here');
438         $this->sessionState(0); // turn off sessions  - no locking..
439
440         require_once 'Pman/Core/SimpleExcel.php';
441         
442         $fn = (empty($filename) ? 'list-export-' : urlencode($filename)) . (($addDate) ? date('Y-m-d') : '') ;
443         
444         
445         $se_config=  array(
446             'workbook' => substr($fn, 0, 31),
447             'cols' => array(),
448             'leave_open' => true
449         );
450         
451         
452         $se = false;
453         if (is_object($data)) {
454             $rooar = method_exists($data, 'toRooArray');
455             while($data->fetch()) {
456                 $x = $rooar  ? $data->toRooArray($q) : $data->toArray();
457                  
458                 if ($cols == '*') {  /// did we get cols sent to us?
459                     $cols = array_keys($x);
460                 }
461                 
462                 if(!is_array($cols)) {
463                     $cols = explode(',', $cols);
464                 }
465                
466                 if ($titles !== false) {
467                     if ($titles== '*') {
468                         $titles= array_keys($x);
469                     }
470                     if(!is_array($titles)) {
471                         $titles = explode(',', $titles);
472                     }
473                     foreach($cols as $i=>$col) {
474                         $add = array(
475                             'header'=> isset($titles[$i]) ? $titles[$i] : $col,
476                             'dataIndex'=> $col,
477                             'width'=>  100,
478                            //     'renderer' => array($this, 'getThumb'),
479                              //   'color' => 'yellow', // set color for the cell which is a header element
480                               // 'fillBlank' => 'gray', // set 
481                         );
482                         //die('here');
483                         if (method_exists($data, 'toSimpleExcelColumn')) {
484                             $add = $data->toSimpleExcelColumn($add);
485                         } 
486                         
487                         $se_config['cols'][] = $add;
488                         
489        
490                         
491                     }
492                     $se = new Pman_Core_SimpleExcel(array(), $se_config);
493                      
494                     $titles = false;
495                 }
496                 
497
498                 $se->addLine($se_config['workbook'], $x);
499                     
500                 
501             }
502             if(!$se){
503                 
504                 $this->jerr('no data found', false, 'text/plain');
505             }
506             $se->send($fn .'.xls');
507             exit;
508             
509         } 
510         
511          foreach($data as $x) {
512             //echo "<PRE>"; print_r(array($_REQUEST['csvCols'], $x->toArray())); exit;
513             $line = array();
514             
515             if ($cols== '*') {
516                 $cols= array_keys($x);
517             }
518             
519             if(!is_array($cols)) {
520                 $cols = explode(',', $cols);
521             }
522
523             if ($titles !== false) {
524                 if ($titles== '*') {
525                     $titles= array_keys($x);
526                 }
527
528                 if(!is_array($titles)) {
529                     $titles = explode(',', $titles);
530                 }
531
532                 foreach($cols as $i=>$col) {
533                     $add = array(
534                         'header'=> isset($titles[$i]) ? $titles[$i] : $col,
535                         'dataIndex'=> $col,
536                         'width'=>  100,
537                        //     'renderer' => array($this, 'getThumb'),
538                          //   'color' => 'yellow', // set color for the cell which is a header element
539                           // 'fillBlank' => 'gray', // set 
540                     );
541                     //die('here');
542                     if (method_exists($this->do, 'toSimpleExcelColumn')) {
543                         $add = $this->do->toSimpleExcelColumn($add);
544                     } 
545                     
546                     $se_config['cols'][] = $add;
547                     
548    
549                     
550                 }
551                 $se = new Pman_Core_SimpleExcel(array(),$se_config);
552                
553                 
554                 //fputcsv($fh, $titles);
555                 $titles = false;
556             }
557             
558             $se->addLine($se_config['workbook'], $x);
559         }
560         
561         if(!$se){
562             $this->jerr('no data found');
563         }
564         
565         $se->send($fn .'.xls');
566         exit;
567         
568     }
569     
570     
571      /**
572      * POST method   Roo/TABLENAME  
573      * -- creates, updates, or deletes data.
574      *
575      * INSERT
576      *    if the primary key is empty, this happens
577      *    will automatically set these to current date and authUser->id
578      *        created, created_by, created_dt
579      *        updated, update_by, updated_dt
580      *        modified, modified_by, modified_dt
581      *        
582      *   will return a GET request SINGLE SELECT (and accepts same)
583      *    
584      * DELETE
585      *    _delete=1,2,3     delete a set of data.
586      * UPDATE
587      *    if the primary key value is set, then update occurs.
588      *    will automatically set these to current date and authUser->id
589      *        updated, update_by, updated_dt
590      *        modified, modified_by, modified_dt
591      *        
592      *
593      * Params:
594      *   _delete=1,2,3   causes a delete to occur.
595      *   _ids=1,2,3,4    causes update to occur on all primary ids.
596      *  
597      *  RETURNS
598      *     = same as single SELECT GET request..
599      *
600      *
601      *
602      * DEBUGGING
603      *   _debug=1    forces debug
604      *   _get=1 - causes a get request to occur when doing a POST..
605      *
606      *
607      * CALLS
608      *   these methods on dataobjects if they exist
609      * 
610      *   checkPerm('E' / 'D' , $authuser)
611      *                      - can we list the stuff
612      *                      - return false to disallow...
613    
614      *   toRooSingleArray($authUser, $request) : array
615      *                       - called on single fetch only, add or maniuplate returned array data.
616      *   toRooArray($request) : array
617      *                      - Called if toSingleArray does not exist.
618      *                      - if you need to return different data than toArray..
619      *
620      *   toEventString()
621      *                  (for logging - this is generically prefixed to all database operations.)
622      *
623      *  
624      *   onUpload($roo)
625      *                  called when $_FILES is not empty
626      *
627      *                  
628      *   setFromRoo($ar, $roo)
629      *                      - alternative to setFrom() which is called if this method does not exist
630      *                      - values from post (deal with dates etc.) - return true|error string.
631      *                      - call $roo->jerr() on failure...
632      *
633      * CALLS BEFORE change occurs:
634      *  
635      *      beforeDelete($dependants_array, $roo)
636      *                      Argument is an array of un-find/fetched dependant items.
637      *                      - jerr() will stop insert.. (Prefered)
638      *                      - return false for fail and set DO->err;
639      *                      
640      *      beforeUpdate($old, $request,$roo)
641      *                      - before update - jerr() will stop insert..
642      *      beforeInsert($request,$roo)
643      *                      - before insert - jerr() will stop insert..
644      *
645      *
646      * CALLS AFTER change occured
647      * 
648      *      onUpdate($old, $request,$roo)
649      *               - after update // return value ignored
650      *
651      *      onInsert($request,$roo)
652      *                  - after insert
653      * 
654      *      onDelete($request, $roo) - after delete
655      * 
656      */                     
657      
658     function post($tab) // update / insert (?? delete??)
659     {
660         // -- why was this put in? - Roo is not related to Core.All ?
661         //if (!$this->hasPerm("Core.All", 'E'))  {
662         //        $this->jerr("PERMISSION DENIED (e)");
663         //}
664         $this->initErrorHandling();
665         
666         // DB_DataObject::debugLevel(1);
667         $this->checkDebug();
668         
669         if (!empty($_REQUEST['_get'])) {
670             return $this->get($tab);
671         }
672         
673         $this->init(); // for pman.
674          
675         $x = $this->dataObject($tab);
676
677         $this->transObj = clone($x);
678         
679         $this->transObj->query('BEGIN');
680         // find the key and use that to get the thing..
681         $keys = $x->keys();
682         if (empty($keys) ) {
683             $this->jerr('no key');
684         }
685         
686         $this->key = $keys[0];
687         
688           // delete should be here...
689         if (isset($_REQUEST['_delete'])) {
690             // do we really delete stuff!?!?!?
691             return $this->delete($x,$_REQUEST);
692         } 
693         
694         
695         
696         
697         $old = false;
698         
699         // not sure if this is a good idea here...
700
701         if (!empty($_REQUEST['_ids'])) {
702             $ids = explode(',',$_REQUEST['_ids']);
703             $x->whereAddIn($this->key, $ids, 'int');
704             $ar = $x->fetchAll();
705             
706             foreach($ar as $x) {
707                 $this->update($x, $_REQUEST);  
708             }
709             // all done..
710             $this->jok("UPDATED");
711             
712             
713         }
714          
715         if (!empty($_REQUEST[$this->key])) { 
716             // it's a create..
717             if (!$x->get($this->key, $_REQUEST[$this->key]))  {
718                 $this->jerr("Invalid request (id does not point to  a record.)");
719             }
720             $this->jok($this->update($x, $_REQUEST));
721         } else {
722             
723             if (empty($_POST)) {
724                 $this->jerr("No data recieved for inserting");
725             }
726
727             $this->jok($this->insert($x, $_REQUEST));
728             
729         }
730         
731         
732         
733     }
734     
735     
736     /**
737      * applySort
738      * 
739      * apply REQUEST[sort] and [dir]
740      * sort may be an array of columsn..
741      * 
742      * @arg   DB_DataObject $x
743      * 
744      */
745     function applySort($x, $sort = '', $dir ='')
746     {
747         
748         // Db_DataObject::debugLevel(1);
749         $sort = empty($_REQUEST['sort']) ? $sort : $_REQUEST['sort'];
750         $dir = empty($_REQUEST['dir']) ? $dir : $_REQUEST['dir'];
751         $dir = $dir == 'ASC' ? 'ASC' : 'DESC';
752          
753         $ms = empty($_REQUEST['_multisort']) ? false : $_REQUEST['_multisort'];
754         //var_Dump($ms);exit;
755         $sorted = false;
756         if (method_exists($x, 'applySort')) {
757             $sorted = $x->applySort(
758                     $this->authUser,
759                     $sort,
760                     $dir,
761                     array_keys($this->cols),
762                     $ms ? json_decode($ms) : false
763             );
764         }
765         
766         if ($ms !== false) {
767             return $this->multiSort($x);
768         }
769  
770         if ($sorted === false) {
771             $cols = $x->tableColumns();
772             $excols = array_keys($this->cols);
773             
774             if (isset($x->_extra_cols)) {
775                 $excols = array_merge($excols, $x->_extra_cols);
776             }
777             $sort_ar = explode(',', $sort);
778             $sort_str = array();
779           
780             foreach($sort_ar as $sort) {
781                 
782                 if (strlen($sort) && isset($cols[$sort]) ) {
783                     $sort_str[] =  $x->tableName() .'.'.$sort . ' ' . $dir ;
784                     
785                 } else if (in_array($sort, $excols)) {
786                     $sort_str[] = $sort . ' ' . $dir ;
787                 }
788             }
789              
790             if ($sort_str) {
791                 $x->orderBy(implode(', ', $sort_str ));
792             }
793         }
794     }
795     /**
796      * Multisort support
797      *
798      * _multisort
799      *
800      *
801      */
802     function multiSort($x)
803     {
804         //DB_DataObject::debugLevel(1);
805         $ms = json_decode($_REQUEST['_multisort']);
806         if (!isset($ms->order) || !is_array($ms->order)) {
807             return;
808         }
809         $sort_str = array();
810         
811         $cols = $x->tableColumns();
812         
813         //print_r($this->cols);exit;
814         // this-><cols contains  colname => aliased name...
815         foreach($ms->order  as $col) {
816             if (!isset($ms->sort->{$col})) {
817                 continue; // no direction..
818             }
819             $ms->sort->{$col} = $ms->sort->{$col}  == 'ASC' ? 'ASC' : 'DESC';
820             
821             if (strlen($col) && isset($cols[$col]) ) {
822                 $sort_str[] =  $x->tableName() .'.'.$col . ' ' .  $ms->sort->{$col};
823                 continue;
824             }
825             //print_r($this->cols);
826             
827             if (in_array($col, array_keys($this->cols))) {
828                 $sort_str[] = $col. ' ' . $ms->sort->{$col};
829                 continue;
830             }
831             if (isset($x->_extra_cols) && in_array($col, $x->_extra_cols)) {
832                 $sort_str[] = $col. ' ' . $ms->sort->{$col};
833             }
834         }
835          
836         if ($sort_str) {
837             $x->orderBy(implode(', ', $sort_str ));
838         }
839           
840         
841     }
842     /**
843      * single select call
844      * - used when _id is set, or after insert or update
845      *
846      * @param DataObject $x the dataobject to use
847      * @param int $id       the pid of the object
848      * @param array $req    the request, or false if it comes from insert/update.
849      *
850      */
851     function selectSingle($x, $id, $req=false)
852     {
853          
854         
855         $_columns = !empty($req['_columns']) ? explode(',', $req['_columns']) : false;
856
857         //var_dump(array(!is_array($id) , empty($id)));
858         if (!is_array($id) && empty($id)) {
859             
860             
861             if (method_exists($x, 'toRooSingleArray')) {
862                 $this->jok($x->toRooSingleArray($this->authUser, $req));
863             }
864             if (method_exists($x, 'toRooArray')) {
865                 $this->jok($x->toRooArray($req));
866             }
867             
868             $this->jok($x->toArray());
869         }
870        
871         
872         $this->loadMap($x, array(
873                     'columns' => $_columns,
874                      
875             ));
876         if ($req !== false) { 
877             $this->setFilters($x, $req);
878         } else if (method_exists($x, 'applyFilters')) {
879             // always call apply filters even after update/insert...
880             // however arguments are not passed.
881             $x->applyFilters(array('_is_update_request' => true), $this->authUser, $this);
882         }
883         
884         // DB_DataObject::DebugLevel(1);
885         if (is_array($id)) {
886             // lookup...
887             $x->setFrom($req['lookup'] );
888             $x->limit(1);
889             if (!$x->find(true)) {
890                 if (!empty($id['_id'])) {
891                     // standardize this?
892                     $this->jok($x->toArray());
893                 }
894                 $this->jok(false);
895             }
896             
897         } else if (!$x->get($id)) {
898             $this->jerr("selectSingle: no such record ($id)");
899         }
900         
901         // ignore perms if comming from update/insert - as it's already done...
902         if ($req !== false && !$this->checkPerm($x,'S'))  {
903             $this->jerr("PERMISSION DENIED - si");
904         }
905         // different symantics on all these calls??
906         if (method_exists($x, 'toRooSingleArray')) {
907             $this->jok($x->toRooSingleArray($this->authUser, $req));
908         }
909         if (method_exists($x, 'toRooArray')) {
910             $this->jok($x->toRooArray($req));
911         }
912         $this->jok($x->toArray());
913         
914         
915     }
916     
917     function insert($x, $req, $with_perm_check = true)
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 }