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