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