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, $event) - after update // return value ignored
36  * - onInsert($request,$roo, $event) - 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
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         if ($titles== '*') {
447             $titles= array_keys($x);
448         }
449         if ($cols== '*') {
450             $cols= array_keys($x);
451         }
452
453         if(!is_array($titles)) {
454             $titles = explode(',', $titles);
455         }
456         if(!is_array($cols)) {
457             $cols = explode(',', $cols);
458         }
459             
460         
461         $se = false;
462         if (is_object($data)) {
463             $rooar = method_exists($data, 'toRooArray');
464             while($data->fetch()) {
465                 $x = $rooar  ? $data->toRooArray($q) : $data->toArray();
466                 
467                 
468                 if ($cols == '*') {  /// did we get cols sent to us?
469                     $cols = array_keys($x);
470                 }
471                 
472                 if(!is_array($cols)) {
473                     $cols = explode(',', $cols);
474                 }
475                
476                 if ($titles !== false) {
477                     
478                     foreach($cols as $i=>$col) {
479                         $se_config['cols'][] = array(
480                             'header'=> isset($titles[$i]) ? $titles[$i] : $col,
481                             'dataIndex'=> $col,
482                             'width'=>  100,
483                            //     'renderer' => array($this, 'getThumb'),
484                              //   'color' => 'yellow', // set color for the cell which is a header element
485                               // 'fillBlank' => 'gray', // set 
486                         );
487                          $se = new Pman_Core_SimpleExcel(array(), $se_config);
488        
489                         
490                     }
491                      
492                     $titles = false;
493                 }
494                 
495
496                 $se->addLine($se_config['workbook'], $x);
497                     
498                 
499             }
500             if(!$se){
501                 
502                 $this->jerr('no data found', false, 'text/plain');
503             }
504             $se->send($fn .'.xls');
505             exit;
506             
507         } 
508         
509         
510         foreach($data as $x) {
511             //echo "<PRE>"; print_r(array($_REQUEST['csvCols'], $x->toArray())); exit;
512             $line = array();
513             
514             if ($titles !== false) {
515                 foreach($cols as $i=>$col) {
516                     $se_config['cols'][] = array(
517                         'header'=> isset($titles[$i]) ? $titles[$i] : $col,
518                         'dataIndex'=> $col,
519                         'width'=>  100,
520                        //     'renderer' => array($this, 'getThumb'),
521                          //   'color' => 'yellow', // set color for the cell which is a header element
522                           // 'fillBlank' => 'gray', // set 
523                     );
524                     $se = new Pman_Core_SimpleExcel(array(),$se_config);
525    
526                     
527                 }
528                 
529                 
530                 //fputcsv($fh, $titles);
531                 $titles = false;
532             }
533             
534             
535             
536             $se->addLine($se_config['workbook'], $x);
537         }
538         if(!$se){
539             $this->jerr('no data found');
540         }
541         $se->send($fn .'.xls');
542         exit;
543     
544         
545         
546     }
547     
548     
549      /**
550      * POST method   Roo/TABLENAME  
551      * -- creates, updates, or deletes data.
552      *
553      * INSERT
554      *    if the primary key is empty, this happens
555      *    will automatically set these to current date and authUser->id
556      *        created, created_by, created_dt
557      *        updated, update_by, updated_dt
558      *        modified, modified_by, modified_dt
559      *        
560      *   will return a GET request SINGLE SELECT (and accepts same)
561      *    
562      * DELETE
563      *    _delete=1,2,3     delete a set of data.
564      * UPDATE
565      *    if the primary key value is set, then update occurs.
566      *    will automatically set these to current date and authUser->id
567      *        updated, update_by, updated_dt
568      *        modified, modified_by, modified_dt
569      *        
570      *
571      * Params:
572      *   _delete=1,2,3   causes a delete to occur.
573      *   _ids=1,2,3,4    causes update to occur on all primary ids.
574      *  
575      *  RETURNS
576      *     = same as single SELECT GET request..
577      *
578      *
579      *
580      * DEBUGGING
581      *   _debug=1    forces debug
582      *   _get=1 - causes a get request to occur when doing a POST..
583      *
584      *
585      * CALLS
586      *   these methods on dataobjects if they exist
587      * 
588      *   checkPerm('E' / 'D' , $authuser)
589      *                      - can we list the stuff
590      *                      - return false to disallow...
591    
592      *   toRooSingleArray($authUser, $request) : array
593      *                       - called on single fetch only, add or maniuplate returned array data.
594      *   toRooArray($request) : array
595      *                      - Called if toSingleArray does not exist.
596      *                      - if you need to return different data than toArray..
597      *
598      *   toEventString()
599      *                  (for logging - this is generically prefixed to all database operations.)
600      *
601      *  
602      *   onUpload($roo)
603      *                  called when $_FILES is not empty
604      *
605      *                  
606      *   setFromRoo($ar, $roo)
607      *                      - alternative to setFrom() which is called if this method does not exist
608      *                      - values from post (deal with dates etc.) - return true|error string.
609      *                      - call $roo->jerr() on failure...
610      *
611      * CALLS BEFORE change occurs:
612      *  
613      *      beforeDelete($dependants_array, $roo)
614      *                      Argument is an array of un-find/fetched dependant items.
615      *                      - jerr() will stop insert.. (Prefered)
616      *                      - return false for fail and set DO->err;
617      *                      
618      *      beforeUpdate($old, $request,$roo)
619      *                      - after update - jerr() will stop insert..
620      *      beforeInsert($request,$roo)
621      *                      - before insert - jerr() will stop insert..
622      *
623      *
624      * CALLS AFTER change occured
625      * 
626      *      onUpdate($old, $request,$roo)
627      *               - after update // return value ignored
628      *
629      *      onInsert($request,$roo)
630      *                  - after insert
631      * 
632      *      onDelete($request, $roo) - after delete
633      * 
634      */                     
635      
636     function post($tab) // update / insert (?? delete??)
637     {
638         // -- why was this put in? - Roo is not related to Core.All ?
639         //if (!$this->hasPerm("Core.All", 'E'))  {
640         //        $this->jerr("PERMISSION DENIED (e)");
641         //}
642         $this->initErrorHandling();
643         
644         // DB_DataObject::debugLevel(1);
645         $this->checkDebug();
646         
647         if (!empty($_REQUEST['_get'])) {
648             return $this->get($tab);
649         }
650         
651         $this->init(); // for pman.
652          
653         $x = $this->dataObject($tab);
654
655         $this->transObj = clone($x);
656         
657         $this->transObj->query('BEGIN');
658         // find the key and use that to get the thing..
659         $keys = $x->keys();
660         if (empty($keys) ) {
661             $this->jerr('no key');
662         }
663         
664         $this->key = $keys[0];
665         
666           // delete should be here...
667         if (isset($_REQUEST['_delete'])) {
668             // do we really delete stuff!?!?!?
669             return $this->delete($x,$_REQUEST);
670         } 
671         
672         
673         
674         
675         $old = false;
676         
677         // not sure if this is a good idea here...
678
679         if (!empty($_REQUEST['_ids'])) {
680             $ids = explode(',',$_REQUEST['_ids']);
681             $x->whereAddIn($this->key, $ids, 'int');
682             $ar = $x->fetchAll();
683             
684             foreach($ar as $x) {
685                 $this->update($x, $_REQUEST);  
686             }
687             // all done..
688             $this->jok("UPDATED");
689             
690             
691         }
692          
693         if (!empty($_REQUEST[$this->key])) { 
694             // it's a create..
695             if (!$x->get($this->key, $_REQUEST[$this->key]))  {
696                 $this->jerr("Invalid request (id does not point to  a record.)");
697             }
698             $this->jok($this->update($x, $_REQUEST));
699         } else {
700             
701             if (empty($_POST)) {
702                 $this->jerr("No data recieved for inserting");
703             }
704
705             $this->jok($this->insert($x, $_REQUEST));
706             
707         }
708         
709         
710         
711     }
712     
713     
714     /**
715      * applySort
716      * 
717      * apply REQUEST[sort] and [dir]
718      * sort may be an array of columsn..
719      * 
720      * @arg   DB_DataObject $x
721      * 
722      */
723     function applySort($x, $sort = '', $dir ='')
724     {
725         
726         // Db_DataObject::debugLevel(1);
727         $sort = empty($_REQUEST['sort']) ? $sort : $_REQUEST['sort'];
728         $dir = empty($_REQUEST['dir']) ? $dir : $_REQUEST['dir'];
729         $dir = $dir == 'ASC' ? 'ASC' : 'DESC';
730          
731         $ms = empty($_REQUEST['_multisort']) ? false : $_REQUEST['_multisort'];
732         //var_Dump($ms);exit;
733         $sorted = false;
734         if (method_exists($x, 'applySort')) {
735             $sorted = $x->applySort(
736                     $this->authUser,
737                     $sort,
738                     $dir,
739                     array_keys($this->cols),
740                     $ms ? json_decode($ms) : false
741             );
742         }
743         if ($ms !== false) {
744             return $this->multiSort($x);
745         }
746         
747         if ($sorted === false) {
748             
749             $cols = $x->tableColumns();
750             $excols = array_keys($this->cols);
751             
752             if (isset($x->_extra_cols)) {
753                 $excols = array_merge($excols, $x->_extra_cols);
754             }
755             $sort_ar = explode(',', $sort);
756             $sort_str = array();
757           
758             foreach($sort_ar as $sort) {
759                 
760                 if (strlen($sort) && isset($cols[$sort]) ) {
761                     $sort_str[] =  $x->tableName() .'.'.$sort . ' ' . $dir ;
762                     
763                 } else if (in_array($sort, $excols)) {
764                     $sort_str[] = $sort . ' ' . $dir ;
765                 }
766             }
767              
768             if ($sort_str) {
769                 $x->orderBy(implode(', ', $sort_str ));
770             }
771         }
772     }
773     /**
774      * Multisort support
775      *
776      * _multisort
777      *
778      *
779      */
780     function multiSort($x)
781     {
782         //DB_DataObject::debugLevel(1);
783         $ms = json_decode($_REQUEST['_multisort']);
784         if (!isset($ms->order) || !is_array($ms->order)) {
785             return;
786         }
787         $sort_str = array();
788         
789         $cols = $x->tableColumns();
790         
791         //print_r($this->cols);exit;
792         // this-><cols contains  colname => aliased name...
793         foreach($ms->order  as $col) {
794             if (!isset($ms->sort->{$col})) {
795                 continue; // no direction..
796             }
797             $ms->sort->{$col} = $ms->sort->{$col}  == 'ASC' ? 'ASC' : 'DESC';
798             
799             if (strlen($col) && isset($cols[$col]) ) {
800                 $sort_str[] =  $x->tableName() .'.'.$col . ' ' .  $ms->sort->{$col};
801                 continue;
802             }
803             //print_r($this->cols);
804             
805             if (in_array($col, array_keys($this->cols))) {
806                 $sort_str[] = $col. ' ' . $ms->sort->{$col};
807                 continue;
808             }
809             if (isset($x->_extra_cols) && in_array($col, $x->_extra_cols)) {
810                 $sort_str[] = $col. ' ' . $ms->sort->{$col};
811             }
812         }
813          
814         if ($sort_str) {
815             $x->orderBy(implode(', ', $sort_str ));
816         }
817           
818         
819     }
820     /**
821      * single select call
822      * - used when _id is set, or after insert or update
823      *
824      * @param DataObject $x the dataobject to use
825      * @param int $id       the pid of the object
826      * @param array $req    the request, or false if it comes from insert/update.
827      *
828      */
829     function selectSingle($x, $id, $req=false)
830     {
831          
832         
833         $_columns = !empty($req['_columns']) ? explode(',', $req['_columns']) : false;
834
835         //var_dump(array(!is_array($id) , empty($id)));
836         if (!is_array($id) && empty($id)) {
837             
838             
839             if (method_exists($x, 'toRooSingleArray')) {
840                 $this->jok($x->toRooSingleArray($this->authUser, $req));
841             }
842             if (method_exists($x, 'toRooArray')) {
843                 $this->jok($x->toRooArray($req));
844             }
845             
846             $this->jok($x->toArray());
847         }
848        
849         
850         $this->loadMap($x, array(
851                     'columns' => $_columns,
852                      
853             ));
854         if ($req !== false) { 
855             $this->setFilters($x, $req);
856         } else if (method_exists($x, 'applyFilters')) {
857             // always call apply filters even after update/insert...
858             // however arguments are not passed.
859             $x->applyFilters(array('_is_update_request' => true), $this->authUser, $this);
860         }
861         
862         // DB_DataObject::DebugLevel(1);
863         if (is_array($id)) {
864             // lookup...
865             $x->setFrom($req['lookup'] );
866             $x->limit(1);
867             if (!$x->find(true)) {
868                 if (!empty($id['_id'])) {
869                     // standardize this?
870                     $this->jok($x->toArray());
871                 }
872                 $this->jok(false);
873             }
874             
875         } else if (!$x->get($id)) {
876             $this->jerr("selectSingle: no such record ($id)");
877         }
878         
879         // ignore perms if comming from update/insert - as it's already done...
880         if ($req !== false && !$this->checkPerm($x,'S'))  {
881             $this->jerr("PERMISSION DENIED - si");
882         }
883         // different symantics on all these calls??
884         if (method_exists($x, 'toRooSingleArray')) {
885             $this->jok($x->toRooSingleArray($this->authUser, $req));
886         }
887         if (method_exists($x, 'toRooArray')) {
888             $this->jok($x->toRooArray($req));
889         }
890         
891         $this->jok($x->toArray());
892         
893         
894     }
895     
896     function insert($x, $req, $with_perm_check = true)
897     {
898         if (method_exists($x, 'setFromRoo')) {
899             $res = $x->setFromRoo($req, $this);
900             if (is_string($res)) {
901                 $this->jerr($res);
902             }
903         } else {
904             $x->setFrom($req);
905         }
906         
907         if ( $with_perm_check &&  !$this->checkPerm($x,'A', $req))  {
908             $this->jerr("PERMISSION DENIED (i)");
909         }
910         $cols = $x->tableColumns();
911      
912         if (isset($cols['created'])) {
913             $x->created = date('Y-m-d H:i:s');
914         }
915         if (isset($cols['created_dt'])) {
916             $x->created_dt = date('Y-m-d H:i:s');
917         }
918         if (isset($cols['created_by'])) {
919             $x->created_by = $this->authUser->id;
920         }
921         
922         if (isset($cols['modified'])) {
923             $x->modified = date('Y-m-d H:i:s');
924         }
925         if (isset($cols['modified_dt'])) {
926             $x->modified_dt = date('Y-m-d H:i:s');
927         }
928         if (isset($cols['modified_by'])) {
929             $x->modified_by = $this->authUser->id;
930         }
931         
932         if (isset($cols['updated'])) {
933             $x->updated = date('Y-m-d H:i:s');
934         }
935         if (isset($cols['updated_dt'])) {
936             $x->updated_dt = date('Y-m-d H:i:s');
937         }
938         if (isset($cols['updated_by'])) {
939             $x->updated_by = $this->authUser->id;
940         }
941         
942         if (method_exists($x, 'beforeInsert')) {
943             $x->beforeInsert($_REQUEST, $this);
944         }
945         
946         $res = $x->insert();
947
948         if ($res === false) {
949             $this->jerr($x->_lastError->toString());
950         }
951         $ev = $this->addEvent("ADD", $x);
952         if (method_exists($x, 'onInsert')) {
953             $x->onInsert($_REQUEST, $this, $ev);
954         }
955         
956         if ($ev) { 
957             $ev->audit($x);
958         }
959         
960         // note setFrom might handle this before hand...!??!
961         if (!empty($_FILES) && method_exists($x, 'onUpload')) {
962             $x->onUpload($this, $_REQUEST);
963         }
964         
965         return $this->selectSingle(
966             DB_DataObject::factory($x->tableName()),
967             $x->pid()
968         );
969         
970     }
971     
972     function updateLock($x, $req )
973     {
974         Pman::$permitError = true; // allow it to fail without dieing
975         
976         $lock = DB_DataObjecT::factory('Core_locking');
977         Pman::$permitError = false; 
978         if (is_a($lock,'DB_DataObject') && $this->authUser)  {
979                  
980             $lock->on_id = $x->{$this->key};
981             $lock->on_table= strtolower($x->tableName());
982             if (!empty($_REQUEST['_lock_id'])) {
983                 $lock->whereAdd('id != ' . ((int)$_REQUEST['_lock_id']));
984             } else {
985                 $lock->whereAdd('person_id !=' . $this->authUser->id);
986             }
987             
988             $llc = clone($lock);
989             $exp = date('Y-m-d', strtotime('NOW - 1 WEEK'));
990             $llc->whereAdd("created < '$exp'");
991             if ($llc->count()) {
992                 $llc->find();
993                 while($llc->fetch()) {
994                     $llcd = clone($llc);
995                     $llcd->delete();
996                 }
997             }
998             
999             $lock->limit(1);
1000             if ($lock->find(true)) {
1001                 // it's locked by someone else..
1002                $p = $lock->person();
1003                
1004                
1005                $this->jerr( "Record was locked by " . $p->name . " at " .$lock->created.
1006                            " - Please confirm you wish to save" 
1007                            , array('needs_confirm' => true)); 
1008           
1009               
1010             }
1011             // check the users lock.. - no point.. ??? - if there are no other locks and it's not the users, then they can 
1012             // edit it anyways...
1013             
1014             // can we find the user's lock.
1015             $lock = DB_DataObjecT::factory('Core_locking');
1016             $lock->on_id = $x->{$this->key};
1017             $lock->on_table= strtolower($x->tableName());
1018             $lock->person_id = $this->authUser->id;
1019             $lock->orderBy('created DESC');
1020             $lock->limit(1);
1021             
1022             if (
1023                     $lock->find(true) &&
1024                     isset($x->modified_dt) &&
1025                     strtotime($x->modified_dt) > strtotime($lock->created) &&
1026                     empty($req['_submit_confirmed']) &&
1027                $x->modified_by != $this->authUser->id   
1028                 )
1029             {
1030                 $p = DB_DataObject::factory('core_person');
1031                 $p->get($x->modified_by);
1032        $this->jerr($p->name . " saved the record since you started editing,\nDo you really want to update it?", array('needs_confirm' => true)); 
1033                 
1034             }
1035             
1036             
1037             
1038         }
1039         return $lock;
1040         
1041     }
1042     
1043     
1044     function update($x, $req,  $with_perm_check = true)
1045     {
1046         if ( $with_perm_check && !$this->checkPerm($x,'E', $req) )  {
1047             $this->jerr("PERMISSION DENIED - No Edit permissions on this element");
1048         }
1049        
1050         // check any locks..
1051         // only done if we recieve a lock_id.
1052         // we are very trusing here.. that someone has not messed around with locks..
1053         // the object might want to check in their checkPerm - if locking is essential..
1054         $lock = $this->updateLock($x,$req);
1055          
1056         
1057         
1058         
1059        
1060          
1061        
1062         $old = clone($x);
1063         $this->old = $x;
1064         // this lot is generic.. needs moving 
1065         if (method_exists($x, 'setFromRoo')) {
1066             $res = $x->setFromRoo($req, $this);
1067             if (is_string($res)) {
1068                 $this->jerr($res);
1069             }
1070         } else {
1071             $x->setFrom($req);
1072         }
1073       
1074         
1075         
1076         //echo '<PRE>';print_r($old);print_r($x);exit;
1077         //print_r($old);
1078         
1079         $cols = $x->tableColumns();
1080
1081         if (isset($cols['modified'])) {
1082             $x->modified = date('Y-m-d H:i:s');
1083         }
1084         if (isset($cols['modified_dt'])) {
1085             $x->modified_dt = date('Y-m-d H:i:s');
1086         }
1087         if (isset($cols['modified_by']) && $this->authUser) {
1088             $x->modified_by = $this->authUser->id;
1089         }
1090         
1091         if (isset($cols['updated'])) {
1092             $x->updated = date('Y-m-d H:i:s');
1093         }
1094         if (isset($cols['updated_dt'])) {
1095             $x->updated_dt = date('Y-m-d H:i:s');
1096         }
1097         if (isset($cols['updated_by']) && $this->authUser) {
1098             $x->updated_by = $this->authUser->id;
1099         }
1100         
1101         if (method_exists($x, 'beforeUpdate')) {
1102             $x->beforeUpdate($old, $req, $this);
1103         }
1104         
1105         if ($with_perm_check && !empty($_FILES) && method_exists($x, 'onUpload')) {
1106             $x->onUpload($this, $_REQUEST);
1107         }
1108         
1109         //DB_DataObject::DebugLevel(1);
1110         $res = $x->update($old);
1111         if ($res === false) {
1112             $this->jerr($x->_lastError->toString());
1113         }
1114         $ev = $this->addEvent("EDIT", $x);
1115
1116         if (method_exists($x, 'onUpdate')) {
1117             $x->onUpdate($old, $req, $this, $ev);
1118         }
1119         if ($ev) { 
1120             $ev->audit($x, $old);
1121         }
1122         
1123         
1124         return $this->selectSingle(
1125             DB_DataObject::factory($x->tableName()),
1126             $x->{$this->key}
1127         );
1128         
1129     }
1130     /**
1131      * Delete a number of records.
1132      * calls $delete_obj->beforeDelete($array_of_dependant_dataobjects, $this)
1133      *
1134      */
1135     
1136     function delete($x, $req)
1137     { 
1138         // do we really delete stuff!?!?!?
1139         if (empty($req['_delete'])) {
1140             $this->jerr("Delete Requested with no value");
1141         }
1142         
1143         
1144         // build a list of tables to queriy for dependant data..
1145         $map = $x->links();
1146         
1147         $affects  = array();
1148         
1149         $all_links = $x->databaseLinks();
1150         
1151         foreach($all_links as $tbl => $links) {
1152             foreach($links as $col => $totbl_col) {
1153                 $to = explode(':', $totbl_col);
1154                 if ($to[0] != $x->tableName()) {
1155                     continue;
1156                 }
1157                 
1158                 $affects[$tbl .'.' . $col] = true;
1159             }
1160         }
1161         // collect tables
1162
1163        // echo '<PRE>';print_r($affects);exit;
1164        // DB_Dataobject::debugLevel(1);
1165        
1166         
1167         
1168         
1169         $bits = array_map(function($v) { return (int)$v; } , explode(',', $req['_delete']));
1170         
1171         // let's assume it has a key!!!
1172         
1173         $x->whereAdd($this->key .'  IN ('. implode(',', $bits) .')');
1174         if (!$x->find()) {
1175             $this->jerr("Nothing found to delete");
1176         }
1177         $errs = array();
1178         while ($x->fetch()) {
1179             $xx = clone($x);
1180             
1181            
1182             // perms first.
1183             
1184             if (!$this->checkPerm($x,'D') )  {
1185                 $this->jerr("PERMISSION DENIED (d)");
1186             }
1187             
1188             $match_ar = array();
1189             foreach($affects as $k=> $true) {
1190                 $ka = explode('.', $k);
1191                 
1192                 $chk = DB_DataObject::factory($ka[0]);
1193                 if (!is_a($chk,'DB_DataObject') && !is_a($chk,'PDO_DataObject'))  {
1194                     $this->jerr('Unable to load referenced table, check the links config: ' .$ka[0]);
1195                 }
1196                // print_r(array($chk->tablename() , $ka[1] ,  $xx->tablename() , $this->key ));
1197                 $chk->{$ka[1]} =  $xx->{$this->key};
1198                 
1199                 if (count($chk->keys())) {
1200                     $matches = $chk->count();
1201                 } else {
1202                     //DB_DataObject::DebugLevel(1);
1203                     $matches = $chk->count($ka[1]);
1204                 }
1205                 
1206                 if ($matches) {
1207                     $chk->_match_key = $ka[1];
1208                     $match_ar[] = clone($chk);
1209                     continue;
1210                 }          
1211             }
1212             
1213             
1214             $has_beforeDelete = method_exists($xx, 'beforeDelete');
1215             // before delte = allows us to trash dependancies if needed..
1216             $match_total = 0;
1217             
1218             if ( $has_beforeDelete ) {
1219                 if ($xx->beforeDelete($match_ar, $this) === false) {
1220                     $errs[] = "Delete failed ({$xx->id})\n".
1221                         (isset($xx->err) ? $xx->err : '');
1222                     continue;
1223                 }
1224                 // refetch affects..
1225                 
1226                 $match_ar = array();
1227                 foreach($affects as $k=> $true) {
1228                     $ka = explode('.', $k);
1229                     $chk = DB_DataObject::factory($ka[0]);
1230                     if (!is_a($chk,'DB_DataObject') && !is_a($chk,'PDO_DataObject'))  {
1231                         $this->jerr('Unable to load referenced table, check the links config: ' .$ka[0]);
1232                     }
1233                     $chk->{$ka[1]} =  $xx->{$this->key};
1234                     $matches = $chk->count();
1235                     $match_total += $matches;
1236                     if ($matches) {
1237                         $chk->_match_key = $ka[1];
1238                         $match_ar[] = clone($chk);
1239                         continue;
1240                     }          
1241                 }
1242                 
1243             }
1244             
1245             if (!empty($match_ar)) {
1246                 $chk = $match_ar[0];
1247                 $chk->limit(1);
1248                 $o = $chk->fetchAll();
1249                 $key = isset($chk->_match_key) ?$chk->_match_key  : '?unknown column?';
1250                 $desc =  $chk->tableName(). '.' . $key .'='.$xx->{$this->key} ;
1251                 if (method_exists($chk, 'toEventString')) {
1252                     $desc .=  ' : ' . $o[0]->toEventString();
1253                 }
1254                 $this->jerr("Delete Dependant records ($match_total  found),  " .
1255                              "first is ( $desc )");
1256           
1257             }
1258             
1259             // now che 
1260             // finally log it.. 
1261             DB_DataObject::Factory('Events')->logDeletedRecord($x);
1262             
1263             $this->addEvent("DELETE", $x);
1264             
1265             $xx->delete();
1266             
1267             if (method_exists($xx,'onDelete')) {
1268                 $xx->onDelete($req, $this);
1269             }
1270             
1271             
1272         }
1273         if ($errs) {
1274             $this->jerr(implode("\n<BR>", $errs));
1275         }
1276         $this->jok("Deleted");
1277         
1278     }
1279    
1280     
1281     /**
1282      * cols stores the list of columns that are available from the query.
1283      *
1284      *
1285      * This is a dupe of what is in autojoin -- we should move to using autojoin really.
1286      *
1287      *
1288      * // changes:
1289      
1290       countWhat
1291       cols
1292       $this->colsJoinName
1293     
1294      *
1295      */
1296     
1297     var $cols = array();
1298     
1299     
1300     
1301     function loadMap($do, $cfg =array()) //$onlycolumns=false, $distinct = false) 
1302     {
1303        
1304         //DB_DataObject::debugLevel(5);
1305         $onlycolumns    = !empty($cfg['columns']) ? $cfg['columns'] : false;
1306         $distinct       = !empty($cfg['distinct']) ? $cfg['distinct'] : false;
1307         $excludecolumns = !empty($cfg['exclude']) ? $cfg['exclude'] : array();
1308           
1309         $excludecolumns[] = 'passwd'; // we never expose passwords
1310         $excludecolumns[] = 'oath_key';
1311        
1312         $ret = $do->autoJoin(array(
1313             'include' => $onlycolumns,
1314             'exclude' => $excludecolumns,
1315             'distinct' => $distinct
1316         ));
1317         
1318         $this->countWhat = $ret['count'];
1319         $this->cols = $ret['cols'];
1320         $this->colsJname = $ret['join_names'];
1321         
1322         
1323         return;
1324         
1325         
1326         
1327     }
1328     /**
1329      * generate the meta data neede by queries.
1330      * 
1331      */
1332     function meta($x, $data)
1333     {
1334         // this is not going to work on queries where the data does not match the database def..
1335         // for unknown columns we send them as stirngs..
1336         $lost = 0;
1337         $cols  = array_keys($data[0]);
1338      
1339         
1340         
1341         if (class_exists('PDO_DataObject')) {
1342             $options = PDO_DataObject::config();
1343             if (!file_exists($options["schema_location"] . '.reader')) {
1344                 return;
1345             }
1346            
1347             $rdata = unserialize(file_get_contents($options["schema_location"] . '.reader'));
1348           
1349         } else {
1350             //echo '<PRE>';print_r($this->cols); exit;
1351             $options = &PEAR::getStaticProperty('DB_DataObject','options');
1352             $reader = $options["ini_{$x->databaseNickname()}"] .'.reader';
1353             if (!file_exists( $reader )) {
1354                 return;
1355             }
1356             
1357             $rdata = unserialize(file_get_contents($reader));
1358         }
1359         
1360         //echo '<PRE>';print_r($this->cols);exit;
1361         //echo '<PRE>';print_r($rdata);exit;
1362        // echo '<PRE>';print_r($rdata);exit;
1363         
1364         $keys = $x->keys();
1365         $key = empty($keys) ? 'id' : $keys[0];
1366         
1367         
1368         $meta = array();
1369         foreach($cols as $c ) {
1370             if (!isset($this->cols[$c]) || !isset($rdata[$this->cols[$c]]) || !is_array($rdata[$this->cols[$c]])) {
1371                 $meta[] = $c;
1372                 continue;    
1373             }
1374             $add = $rdata[$this->cols[$c]];
1375             $add['name'] = $c;
1376             $meta[] = $add;
1377         }
1378         return array(
1379             'totalProperty' =>  'total',
1380             'successProperty' => 'success',
1381             'root' => 'data',
1382             'id' => $key, // was 'id'...
1383             'fields' => $meta
1384         );
1385          
1386         
1387     }
1388     
1389     function setFilters($x, $q)
1390     {
1391         // if a column is type int, and we get ',' -> the it should be come an inc clause..
1392        // DB_DataObject::debugLevel(1);
1393         if (method_exists($x, 'applyFilters')) {
1394            // DB_DataObject::debugLevel(1);
1395             if (false === $x->applyFilters($q, $this->authUser, $this)) {
1396                 return; 
1397             } 
1398         }
1399         $q_filtered = array();
1400         
1401         $keys = $x->keys();
1402
1403         foreach($q as $key=>$val) {
1404             
1405             if (in_array($key,$keys) && !is_array($val)) {
1406                
1407                 $x->$key  = $val;
1408             }
1409             
1410              // handles name[]=fred&name[]=brian => name in ('fred', 'brian').
1411             // value is an array..
1412             if (is_array($val) ) {
1413                 
1414                 $pref = '';
1415                 
1416                 if ($key[0] == '!') {
1417                     $pref = '!';
1418                     $key = substr($key,1);
1419                 }
1420                 
1421                 if (!in_array( $key,  array_keys($this->cols))) {
1422                     continue;
1423                 }
1424                 
1425                 // support a[0] a[1] ..... => whereAddIn(
1426                 $ar = array();
1427                 $quote = false;
1428                 foreach($val as $k=>$v) {
1429                     if (!is_numeric($k)) {
1430                         $ar = array();
1431                         break;
1432                     }
1433                     // FIXME: note this is not typesafe for anything other than mysql..
1434                     
1435                     if (!is_numeric($v) || !is_long($v)) {
1436                         $quote = true;
1437                     }
1438                     $ar[] = $v;
1439                     
1440                 }
1441                 if (count($ar)) {
1442                     
1443                     
1444                     $x->whereAddIn($pref . (
1445                         isset($this->colsJname[$key]) ? 
1446                             $this->colsJname[$key] :
1447                             ($x->tableName(). '.'.$key)),
1448                         $ar, $quote ? 'string' : 'int');
1449                 }
1450                 
1451                 continue;
1452             }
1453             
1454             
1455             // handles !name=fred => name not equal fred.
1456             if ($key[0] == '!' && in_array(substr($key, 1), array_keys($this->cols))) {
1457                 
1458                 $key  = substr($key, 1) ;
1459                 
1460                 $x->whereAdd(   (
1461                         isset($this->colsJname[$key]) ? 
1462                             $this->colsJname[$key] :
1463                             $x->tableName(). '.'.$key ) . ' != ' .
1464                     (is_numeric($val) ? $val : "'".  $x->escape($val) . "'")
1465                 );
1466                 continue;
1467                 
1468             }
1469             
1470                 
1471             
1472             switch($key) {
1473                     
1474                 // Events and remarks -- fixme - move to events/remarsk...
1475                 case 'on_id':  // where TF is this used...
1476                     if (!empty($q['query']['original'])) {
1477                       //  DB_DataObject::debugLevel(1);
1478                         $o = (int) $q['query']['original'];
1479                         $oid = (int) $val;
1480                         $x->whereAdd("(on_id = $oid  OR 
1481                                 on_id IN ( SELECT distinct(id) FROM Documents WHERE original = $o ) 
1482                             )");
1483                         continue;
1484                                 
1485                     }
1486                     $x->on_id = $val;
1487                 
1488                 
1489                 default:
1490                     if (strlen($val) && $key[0] != '_') {
1491                         $q_filtered[$key] = $val;
1492                     }
1493                     
1494                     // subjoined columns = check the values.
1495                     // note this is not typesafe for anything other than mysql..
1496                     
1497                     if (isset($this->colsJname[$key])) {
1498                         
1499                         // the aobve rule for !strlen non-joined cols should apply to joined ones.
1500                         if (!strlen($val)) {
1501                             continue;
1502                         }
1503                         
1504                         
1505                         $quote = false;
1506                         if (!is_numeric($val) || !is_long($val)) {
1507                             $quote = true;
1508                         }
1509                         $x->whereAdd( "{$this->colsJname[$key]} = " . ($quote ? "'". $x->escape($val) ."'" : $val));
1510                         
1511                     }
1512                     
1513                     
1514                     continue;
1515             }
1516         }
1517         if (!empty($q_filtered)) {
1518             //var_dump($q_filtered);
1519             
1520             
1521             
1522             $x->setFrom($q_filtered);
1523         }
1524         
1525         
1526         
1527        
1528         // nice generic -- let's get rid of it.. where is it used!!!!
1529         // used by: 
1530         // Person / Group / Comapnies.... most of my queries noww...
1531         /*
1532         if (!empty($q['query']['name'])) {
1533             
1534             
1535             if (in_array( 'name',  array_keys($x->table()))) {
1536                 $x->whereAdd($x->tableName().".name LIKE '". $x->escape($q['query']['name']) . "%'");
1537             }
1538         }
1539         */
1540         
1541         // - projectdirectory staff list - persn queuy
1542      
1543         
1544     }
1545     /**
1546      * create the  dataobject from (usually the url)
1547      * This uses $this->validTables
1548      *           $this->validPrefix (later..)
1549      * to determine if class can be created..
1550      *
1551      */
1552      
1553     function dataObject($tab)
1554     {
1555         if (is_array($this->validTables) &&  !in_array($tab,$this->validTables)) {
1556             $this->jerr("Invalid url - not listed in validTables");
1557         }
1558         $tab = str_replace('/', '',$tab); // basic protection??
1559         
1560         $pm = HTML_FlexyFramework::get()->Pman;
1561         
1562         if (isset($pm['roo_alias'])) {
1563             $map = array_flip($pm['roo_alias']);
1564             if (isset($map[$tab])) {
1565                 $tab = $map[$tab];
1566             }
1567         }
1568         
1569         
1570         $x = DB_DataObject::factory($tab);
1571         
1572         if (!is_a($x, 'DB_DataObject') && !is_a($x, 'PDO_DataObject')) {
1573             $this->jerr('invalid url - no dataobject');
1574         }
1575     
1576         return $x;
1577         
1578     }
1579     
1580       
1581     
1582     
1583     
1584     
1585 }