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