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