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