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