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