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