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