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