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