Pman/Roo.php
[Pman.Base] / Pman / Roo.php
1 <?php
2
3
4 require_once 'Pman.php';
5 /**
6  * 
7  * 
8  * not really sure how save our factory method is....!!!
9  * 
10  * 
11  * Uses these methods of the dataobjects:
12  * - checkPerm('L'/'E'/'A', $authuser) - can we list the stuff
13  * 
14  * - applySort($au, $sortcol, $direction)
15  * - applyFilters($_REQUEST, $authUser) -- apply any query filters on data. and hide stuff not to be seen.
16  * - postListExtra - 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  * - beforeDelete() -- return false for fail and set DO->err;
24  * - onUpdate($old, $request,$roo) - after update // return value ignored
25  * - onInsert($request,$roo) - after insert
26  * - onUpload($roo)
27  * - setFromRoo($ar) - values from post (deal with dates etc.) - return true|error string.
28  * 
29  * - toEventString (for logging - this is generically prefixed to all database operations.)
30  */
31
32 class Pman_Roo extends Pman
33 {
34     
35    function getAuth() {
36         parent::getAuth(); // load company!
37         $au = $this->getAuthUser();
38         if (!$au) {
39             $this->jerr("Not authenticated", array('authFailure' => true));
40         }
41         $this->authUser = $au;
42         return true;
43     }
44     /**
45      * GET method   Roo/TABLENAME.php 
46      * -- defaults to listing data. with args.
47      * 
48      * !colname=....                 => colname != ....
49      * colname[0]=... colname[1]=... => colname IN (.....) ** only supports main table at present..
50      * 
51      * other opts:
52      * _post      = simulate a post with debuggin on.
53      * lookup     =  array( k=>v) single fetch based on a key/value pair
54      * _id        =  single fetch based on id.
55      * _delete    = delete a list of ids element. (seperated by ,);
56      * _columns   = comma seperated list of columns.
57      * _distinct   = a distinct column lookup.
58      * _requestMeta = default behaviour of Roo stores.. on first query..
59      * 
60      * csvCols[0] csvCols[1]....    = .... column titles for CSV output
61      * 
62      * csvTitle[0], csvTitle[1] ....  = columns to use for CSV output
63      *
64      * sort        = sort column (',' comma delimited)
65      * dir         = sort direction ?? in future comma delimited...
66      * start       = limit start
67      * limit       = limit number 
68      * 
69      * _toggleActive !:!:!:! - this hsould not really be here..
70      * query[add_blank] - add a line in with an empty option...  - not really needed???
71      * 
72      */
73     function get($tab)
74     {
75          //  $this->jerr("Not authenticated", array('authFailure' => true));
76        //echo '<PRE>';print_R($_GET);  DB_DataObject::debuglevel(1);
77         
78         $this->init(); // from pnan.
79         
80         HTML_FlexyFramework::get()->generateDataobjectsCache($this->isDev);
81         // debugging...
82         if (!empty($_GET['_post'])) {
83             $_POST  = $_GET;
84             DB_DAtaObject::debuglevel(1);
85             return $this->post($tab);
86         }
87         $tab = str_replace('/', '',$tab); // basic protection??
88         $x = DB_DataObject::factory($tab);
89         if (!is_a($x, 'DB_DataObject')) {
90             $this->jerr('invalid url');
91         }
92         $_columns = !empty($_REQUEST['_columns']) ? explode(',', $_REQUEST['_columns']) : false;
93         
94         if (isset( $_REQUEST['lookup'] )) { // single fetch based on key/value pairs
95             if (method_exists($x, 'checkPerm') && !$x->checkPerm('S', $this->authUser))  {
96                 $this->jerr("PERMISSION DENIED");
97             }
98             $this->loadMap($x, $_columns);
99             $x->setFrom($_REQUEST['lookup'] );
100             $x->limit(1);
101             if (!$x->find(true)) {
102                 $this->jok(false);
103             }
104             $this->jok($x->toArray());
105         }
106         
107         
108         
109         if (isset($_REQUEST['_id'])) { // single fetch
110             
111             if (empty($_REQUEST['_id'])) {
112                 $this->jok($x->toArray());  // return an empty array!
113             }
114            
115             $this->loadMap($x, $_columns);
116             
117             if (!$x->get($_REQUEST['_id'])) {
118                 $this->jerr("no such record");
119             }
120             
121             if (method_exists($x, 'checkPerm') && !$x->checkPerm('S', $this->authUser))  {
122                 $this->jerr("PERMISSION DENIED");
123             }
124             
125             $this->jok(method_exists($x, 'toRooSingleArray') ? $x->toRooSingleArray($this->authUser, $_REQUEST) : $x->toArray());
126             
127         }
128         if (isset($_REQUEST['_delete'])) {
129             // do we really delete stuff!?!?!?
130             return $this->delete($x,$_REQUEST);
131         } 
132         
133         
134         
135         
136         if (isset($_REQUEST['_toggleActive'])) {
137             // do we really delete stuff!?!?!?
138             if (!$this->hasPerm("Core.Staff", 'E'))  {
139                 $this->jerr("PERMISSION DENIED");
140             }
141             $clean = create_function('$v', 'return (int)$v;');
142             $bits = array_map($clean, explode(',', $_REQUEST['_toggleActive']));
143             if (in_array($this->authUser->id, $bits) && $this->authUser->active) {
144                 $this->jerr("you can not disable yourself");
145             }
146             $x->query('UPDATE Person SET active = !active WHERE id IN (' .implode(',', $bits).')');
147             $this->addEvent("USERTOGGLE", false, implode(',', $bits));
148             $this->jok("Updated");
149             
150         }
151        //DB_DataObject::debugLevel(1);
152         if (method_exists($x, 'checkPerm') && !$x->checkPerm('S', $this->authUser))  {
153             $this->jerr("PERMISSION DENIED");
154         }
155         
156         // sets map and countWhat
157         $this->loadMap($x, $_columns, empty($_REQUEST['_distinct']) ? false:  $_REQUEST['_distinct']);
158         
159         $this->setFilters($x,$_REQUEST);
160       
161          //print_r($x);
162         // build join if req.
163           //DB_DataObject::debugLevel(1);
164         $total = $x->count($this->countWhat);
165         // sorting..
166       //   
167         //var_dump($total);exit;
168         $this->applySort($x);
169         
170         
171  
172         $x->limit(
173             empty($_REQUEST['start']) ? 0 : (int)$_REQUEST['start'],
174             min(empty($_REQUEST['limit']) ? 25 : (int)$_REQUEST['limit'], 1000)
175         );
176         
177         $queryObj = clone($x);
178         
179         $x->find();
180         $ret = array();
181         
182         if (!empty($_REQUEST['query']['add_blank'])) {
183             $ret[] = array( 'id' => 0, 'name' => '----');
184             $total+=1;
185         }
186         // MOVE ME...
187         
188         //if (($tab == 'Groups') && ($_REQUEST['type'] != 0))  { // then it's a list of teams..
189         if ($tab == 'Groups') {
190             
191             $ret[] = array( 'id' => 0, 'name' => 'EVERYONE');
192             $ret[] = array( 'id' => -1, 'name' => 'NOT_IN_GROUP');
193             //$ret[] = array( 'id' => 999999, 'name' => 'ADMINISTRATORS');
194             $total+=2;
195         }
196         
197         // DOWNLOAD...
198         
199         if (!empty($_REQUEST['csvCols']) && !empty($_REQUEST['csvTitles']) ) {
200             header('Content-type: text/csv');
201             
202             header('Content-Disposition: attachment; filename="list-export-'.date('Y-m-d') . '.csv"');
203             //header('Content-type: text/plain');
204             $fh = fopen('php://output', 'w');
205             fputcsv($fh, $_REQUEST['csvTitles']);
206             while ($x->fetch()) {
207                 //echo "<PRE>"; print_r(array($_REQUEST['csvCols'], $x->toArray())); exit;
208                 $line = array();
209                 foreach($_REQUEST['csvCols'] as $k) {
210                     $line[] = isset($x->$k) ? $x->$k : '';
211                 }
212                 fputcsv($fh, $line);
213             }
214             fclose($fh);
215             exit;
216             
217         
218         }
219         //die("DONE?");
220         
221         $rooar = method_exists($x, 'toRooArray');
222         
223         while ($x->fetch()) {
224             $add = $rooar  ? $x->toRooArray($_REQUEST) : $x->toArray();
225             
226             $ret[] =  !$_columns ? $add : array_intersect_key($add, array_flip($_columns));
227         }
228         //if ($x->tableName() == 'Documents_Tracking') {
229         //    $ret = $this->replaceSubject(&$ret, 'doc_id_subject');
230        // }
231         
232         $extra = false;
233         if (method_exists($queryObj ,'postListExtra')) {
234             $extra = $queryObj->postListExtra($_REQUEST);
235         }
236         // filter results, and add any data that is needed...
237         if (method_exists($x,'postListFilter')) {
238             $ret = $x->postListFilter($ret, $this->authUser, $_REQUEST);
239         }
240         
241         if (!empty($_REQUEST['_requestMeta']) &&  count($ret)) {
242             $meta = $this->meta($x, $ret);
243             if ($meta) {
244                 $extra['metaData'] = $meta;
245             }
246         }
247         
248        // echo "<PRE>"; print_r($ret);
249         $this->jdata($ret,$total, $extra );
250
251     
252     }
253     /**
254      * applySort
255      * 
256      * apply REQUEST[sort] and [dir]
257      * sort may be an array of columsn..
258      * 
259      * @arg   DB_DataObject $x
260      * 
261      */
262     function applySort($x, $sort = '', $dir ='')
263     {
264         
265        // Db_DataObject::debugLevel(1);
266         $sort = empty($_REQUEST['sort']) ? $sort : $_REQUEST['sort'];
267         $dir = empty($_REQUEST['dir']) ? $dir : $_REQUEST['dir'];
268         $dir = $dir == 'ASC' ? 'ASC' : 'DESC';
269         
270         
271         
272         $sorted = false;
273         if (method_exists($x, 'applySort')) {
274             $sorted = $x->applySort($this->authUser, $sort, $dir, array_keys($this->cols));
275         }
276         if ($sorted === false) {
277             
278             $cols = $x->table();
279             $sort_ar = explode(',', $sort);
280             $sort_str = array();
281           
282             foreach($sort_ar as $sort) {
283                 
284                 if (strlen($sort) && isset($cols[$sort]) ) {
285                     $sort_str[] =  $x->tableName() .'.'.$sort . ' ' . $dir ;
286                     
287                 } else if (in_array($sort, array_keys($this->cols))) {
288                     $sort_str[] = $sort . ' ' . $dir ;
289                 }
290             }
291              
292             if ($sort_str) {
293                 $x->orderBy(implode(', ', $sort_str ));
294             }
295         }
296     }
297      /**
298      * POST method   Roo/TABLENAME.php 
299      * -- updates the data..
300      * 
301      * other opts:
302      * _debug - forces debugging on.
303      * _get - forces a get request
304      * _ids - multiple update of records.
305      * {colid} - forces fetching
306      * 
307      */
308     function post($tab) // update / insert (?? dleete??)
309     {
310        // DB_DataObject::debugLevel(1);
311         if (!empty($_REQUEST['_debug'])) {
312             DB_DataObject::debugLevel(1);
313         }
314         
315         if (!empty($_REQUEST['_get'])) {
316             return $this->get($tab);
317         }
318       
319         $_columns = !empty($_REQUEST['_columns']) ? explode(',', $_REQUEST['_columns']) : false;
320         
321         $tab = str_replace('/', '',$tab); // basic protection??
322         $x = DB_DataObject::factory($tab);
323         if (!is_a($x, 'DB_DataObject')) {
324             $this->jerr('invalid url');
325         }
326         // find the key and use that to get the thing..
327         $keys = $x->keys();
328         if (empty($keys) ) {
329             $this->jerr('no key');
330         }
331         
332           // delete should be here...
333         if (isset($_REQUEST['_delete'])) {
334             // do we really delete stuff!?!?!?
335             return $this->delete($x,$_REQUEST);
336         } 
337          
338         
339         $old = false;
340         
341         if (!empty($_REQUEST['_ids'])) {
342             $ids = explode(',',$_REQUEST['_ids']);
343             $x->whereAddIn($keys[0], $ids, 'int');
344             $ar = $x->fetchAll();
345             foreach($ar as $x) {
346                 $this->update($x, $_REQUEST);
347                 
348             }
349             // all done..
350             $this->jok("UPDATED");
351             
352             
353         }
354         
355         
356         if (!empty($_REQUEST[$keys[0]])) {
357             // it's a create..
358             if (!$x->get($keys[0], $_REQUEST[$keys[0]]))  {
359                 $this->jerr("Invalid request");
360             }
361             $this->jok($this->update($x, $_REQUEST));
362         } else {
363             
364             if (empty($_POST)) {
365                 $this->jerr("No data recieved for inserting");
366             }
367             
368             $this->jok($this->insert($x, $_REQUEST));
369             
370         }
371         
372         
373         
374     }
375     function insert($x, $req)
376     {
377         
378     
379         if (method_exists($x, 'checkPerm') && !$x->checkPerm('A', $this->authUser, $req))  {
380             $this->jerr("PERMISSION DENIED");
381         }
382         
383         $_columns = !empty($req['_columns']) ? explode(',', $req['_columns']) : false;
384    
385         if (method_exists($x, 'setFromRoo')) {
386             $res = $x->setFromRoo($req, $this);
387             if (is_string($res)) {
388                 $this->jerr($res);
389             }
390         } else {
391             $x->setFrom($req);
392         }
393         
394          
395         $cols = $x->table();
396      
397         if (isset($cols['created'])) {
398             $x->created = date('Y-m-d H:i:s');
399         }
400         if (isset($cols['created_dt'])) {
401             $x->created_dt = date('Y-m-d H:i:s');
402         }
403         if (isset($cols['created_by'])) {
404             $x->created_by = $this->authUser->id;
405         }
406         
407      
408          if (isset($cols['modified'])) {
409             $x->modified = date('Y-m-d H:i:s');
410         }
411         if (isset($cols['modified_dt'])) {
412             $x->modified_dt = date('Y-m-d H:i:s');
413         }
414         if (isset($cols['modified_by'])) {
415             $x->modified_by = $this->authUser->id;
416         }
417         
418         if (isset($cols['updated'])) {
419             $x->updated = date('Y-m-d H:i:s');
420         }
421         if (isset($cols['updated_dt'])) {
422             $x->updated_dt = date('Y-m-d H:i:s');
423         }
424         if (isset($cols['updated_by'])) {
425             $x->updated_by = $this->authUser->id;
426         }
427         
428      
429         
430         
431         
432         $x->insert();
433         if (method_exists($x, 'onInsert')) {
434             $x->onInsert($_REQUEST, $this);
435         }
436         $this->addEvent("ADD", $x);
437         
438         // note setFrom might handle this before hand...!??!
439         if (!empty($_FILES) && method_exists($x, 'onUpload')) {
440             $x->onUpload($this);
441         }
442         
443         $r = DB_DataObject::factory($x->tableName());
444           $pk = $x->keys();
445         // let's assume it has a key!!!
446         $pk = $pk[0];
447         $r->$pk = $x->$pk;
448         $this->loadMap($r, $_columns);
449         $r->limit(1);
450         $r->find(true);
451         
452         $rooar = method_exists($r, 'toRooArray');
453         //print_r(var_dump($rooar)); exit;
454         return $rooar  ? $r->toRooArray($_REQUEST) : $r->toArray();
455     }
456     
457     
458     function update($x, $req)
459     {
460         if (method_exists($x, 'checkPerm') && !$x->checkPerm('E', $this->authUser, $_REQUEST))  {
461             $this->jerr("PERMISSION DENIED");
462         }
463        
464         // check any locks..
465         // only done if we recieve a lock_id.
466         // we are very trusing here.. that someone has not messed around with locks..
467         // the object might want to check in their checkPerm - if locking is essential..
468         
469         $lock = DB_DataObjecT::factory('Core_locking');
470         if (is_a($lock,'DB_DataObject'))  {
471                  
472             $lock->on_id = $x->id;
473             $lock->on_table= $x->tableName();
474             if (!empty($_REQUEST['_lock_id'])) {
475                 $lock->whereAdd('id != ' . ((int)$_REQUEST['_lock_id']));
476             }
477             $lock->limit(1);
478             if ($lock->find(true)) {
479                 // it's locked by someone else..
480                 $p = $lock->person();
481                 $this->jerr("Your lock is invalid, This record is locked by " . $p->name . " at " .$lock->created);
482             }
483             // check the users lock.. - no point.. ??? - if there are no other locks and it's not the users, then they can 
484             // edit it anyways...
485             
486         }
487         
488          
489         
490         
491         
492        
493         $_columns = !empty($req['_columns']) ? explode(',', $req['_columns']) : false;
494
495        
496         $old = clone($x);
497         $this->old = $x;
498         // this lot is generic.. needs moving 
499         if (method_exists($x, 'setFromRoo')) {
500             $res = $x->setFromRoo($req, $this);
501             if (is_string($res)) {
502                 $this->jerr($res);
503             }
504         } else {
505             $x->setFrom($req);
506         }
507         $this->addEvent("EDIT", $x);
508         //print_r($x);
509         //print_r($old);
510         
511         $cols = $x->table();
512         
513         if (isset($cols['modified'])) {
514             $x->modified = date('Y-m-d H:i:s');
515         }
516         if (isset($cols['modified_dt'])) {
517             $x->modified_dt = date('Y-m-d H:i:s');
518         }
519         if (isset($cols['modified_by'])) {
520             $x->modified_by = $this->authUser->id;
521         }
522         
523         if (isset($cols['updated'])) {
524             $x->updated = date('Y-m-d H:i:s');
525         }
526         if (isset($cols['updated_dt'])) {
527             $x->updated_dt = date('Y-m-d H:i:s');
528         }
529         if (isset($cols['updated_by'])) {
530             $x->updated_by = $this->authUser->id;
531         }
532         
533         
534         $x->update($old);
535         if (method_exists($x, 'onUpdate')) {
536             $x->onUpdate($old, $req, $this);
537         }
538         
539         $r = DB_DataObject::factory($x->tableName());
540         $pk = $x->keys();
541         // let's assume it has a key!!!
542         $pk = $pk[0];
543         $r->$pk = $x->$pk;
544         $this->loadMap($r, $_columns);
545         $r->limit(1);
546         $r->find(true);
547         $rooar = method_exists($r, 'toRooArray');
548         //print_r(var_dump($rooar)); exit;
549         return $rooar  ? $r->toRooArray($_REQUEST) : $r->toArray();
550     }
551     
552     function delete($x, $req)
553     {
554         // do we really delete stuff!?!?!?
555         if (empty($req['_delete'])) {
556             $this->jerr("Delete Requested with no value");
557             
558         }
559         // build a list of tables to queriy for dependant data..
560         $map = $x->links();
561         
562         $affects  = array();
563         
564         $all_links = $GLOBALS['_DB_DATAOBJECT']['LINKS'][$x->_database];
565         foreach($all_links as $tbl => $links) {
566             foreach($links as $col => $totbl_col) {
567                 $to = explode(':', $totbl_col);
568                 if ($to[0] != $x->tableName()) {
569                     continue;
570                 }
571                 
572                 $affects[$tbl .'.' . $col] = true;
573             }
574         }
575         // collect tables
576         
577        // echo '<PRE>';print_r($affects);exit;
578        //DB_Dataobject::debugLevel(1);
579        
580         
581         $clean = create_function('$v', 'return (int)$v;');
582         
583         $bits = array_map($clean, explode(',', $req['_delete']));
584         
585        // print_r($bits);exit;
586          $pk = $x->keys();
587         // let's assume it has a key!!!
588         $pk = $pk[0];
589         
590         $x->whereAdd($pk .'  IN ('. implode(',', $bits) .')');
591         if (!$x->find()) {
592             $this->jerr("Nothing found to delete");
593         }
594         $errs = array();
595         while ($x->fetch()) {
596             $xx = clone($x);
597             
598            
599             // perms first.
600             
601             if (method_exists($x, 'checkPerm') && !$x->checkPerm('D', $this->authUser))  {
602                 $this->jerr("PERMISSION DENIED");
603             }
604             
605             // before delte = allows us to trash dependancies if needed..
606             if ( method_exists($xx, 'beforeDelete') && ($xx->beforeDelete() === false)) {
607                 $errs[] = "Delete failed ({$xx->id})\n". (isset($xx->err) ? $xx->err : '');
608                 continue;
609             }
610             
611             // now check deps.
612              
613             foreach($affects as $k=> $true) {
614                 $ka = explode('.', $k);
615                 $chk = DB_DataObject::factory($ka[0]);
616                 if (!is_a($chk,'DB_DataObject')) {
617                     $this->jerr('Unable to load referenced table, check the links config: ' .$ka[0]);
618                 }
619                 $chk->{$ka[1]} =  $xx->$pk;
620                 $matches = $chk->count();
621                 if ($matches) {
622                     $chk->limit(1);
623                     $o = $chk->fetchAll();
624                     $desc =  $ka[0]. ':' . $ka[1] .'='.$xx->$pk;
625                     if (method_exists($chk, 'toEventString')) {
626                         $desc = $ka[0] . ' : ' . $o[0]->toEventString();
627                     }
628                     
629                     $this->jerr("Delete Dependant records ($matches found) first is ( $desc )");
630                 }
631             }
632             // finally log it.. 
633             
634             $this->addEvent("DELETE", $x);
635             
636             $xx->delete();
637         }
638         if ($errs) {
639             $this->jerr(implode("\n<BR>", $errs));
640         }
641         $this->jok("Deleted");
642         
643     }
644    
645     
646     
647     
648     var $cols = array();
649     function loadMap($do, $filter=false, $distinct = false) 
650     {
651         //DB_DataObject::debugLevel(1);
652         
653          $this->countWhat = false;
654         
655         $conf = array();
656         
657         $this->init();
658         
659         $mods = explode(',',$this->appModules);
660         
661         $ff = HTML_FlexyFramework::get();
662         //$db->databaseName();
663         
664         //$ff->DB_DataObject['ini_'. $db->database()];
665         //echo '<PRE>';print_r($do->links());exit;
666         //var_dump($mods);
667         /*
668         if (in_array('Builder', $mods) ) {
669             
670             foreach(in_array('Builder', $mods) ? scandir($this->rootDir.'/Pman') : $mods as $m) {
671                 
672                 if (!strlen($m) || $m[0] == '.' || !is_dir($this->rootDir."/Pman/$m")) {
673                     continue;
674                 }
675                 $ini = $this->rootDir."/Pman/$m/DataObjects/pman.links.ini";
676                 if (!file_exists($ini)) {
677                     continue;
678                 }
679                 $conf = array_merge($conf, parse_ini_file($ini,true));
680                 if (!isset($conf[$do->tableName()])) {
681                     return;
682                 }
683                 $map = $conf[$do->tableName()];
684             } 
685         } else {
686             */
687             $map = $do->links();
688         //}
689          
690         
691         
692         
693         // current table..
694         $tabdef = $do->table();
695         if (isset($tabdef['passwd'])) {
696             // prevent exposure of passwords..
697             unset($tabdef['passwd']);     
698         }
699         $xx = clone($do);
700         $xx = array_keys($tabdef);
701         $do->selectAdd(); // we need thsi as normally it's only cleared by an empty selectAs call.
702         
703         $selectAs = array(array(  $xx , '%s', false));
704        
705         $has_distinct = false;
706         if ($filter || $distinct) {
707             $cols = array();
708             //echo '<PRE>' ;print_r($filter);exit;
709             foreach($xx as $c) {
710                 if ($distinct && $distinct == $c) {
711                     $has_distinct = 'DISTINCT( ' . $do->tableName() .'.'. $c .') as ' . $c;
712                     $this->countWhat =  'DISTINCT  ' . $do->tableName() .'.'. $c .'';
713                     continue;
714                 }
715                 if (!$filter || in_array($c, $filter)) {
716                     $cols[] = $c;
717                 }
718             }
719             
720             
721             $selectAs = empty($cols) ?  array() : array(array(  $cols , '%s', false)) ;
722             
723             
724             
725         } 
726         
727         $this->cols = array();
728         $this->colsJoinName =array();
729         foreach($xx as $k) {
730             $this->cols[$k] = $do->tableName(). '.' . $k;
731         }
732         
733         
734         
735         
736          
737         
738         foreach($map as $ocl=>$info) {
739             
740             list($tab,$col) = explode(':', $info);
741             // what about multiple joins on the same table!!!
742             $xx = DB_DataObject::factory($tab);
743             if (!is_a($xx, 'DB_DataObject')) {
744                 continue;
745             }
746             // this is borked ... for multiple jions..
747             $do->joinAdd($xx, 'LEFT', 'join_'.$ocl.'_'. $col, $ocl);
748             $tabdef = $xx->table();
749             $table = $xx->tableName();
750             if (isset($tabdef['passwd'])) {
751              
752                 unset($tabdef['passwd']);
753               
754             } 
755             $xx = array_keys($tabdef);
756             
757             
758             if ($filter || $distinct) {
759                 $cols = array();
760                 foreach($xx as $c) {
761                     $tn = sprintf($ocl.'_%s', $c);
762                   // echo '<PRE>'; var_dump($tn);
763                     if ($distinct && $tn == $distinct) {
764                         $has_distinct = 'DISTINCT( ' . 'join_'.$ocl.'_'.$col.'.'.$k .')  as ' . $tn ;
765                         $this->countWhat =  'DISTINCT  join_'.$ocl.'_'.$col.'.'.$k;
766                         continue;
767                     }
768                     
769                     
770                     if (!$filter || in_array($tn, $filter)) {
771                         $cols[] = $c;
772                     }
773                 }
774                 if (!empty($cols)) {
775                      $selectAs[] = array($cols, $ocl.'_%s', 'join_'.$ocl.'_'. $col);
776                 }
777                
778                 
779             } else {
780                 $selectAs[] = array($xx, $ocl.'_%s', 'join_'.$ocl.'_'. $col);
781                 
782             }
783              
784             
785             foreach($xx as $k) {
786                 $this->cols[sprintf($ocl.'_%s', $k)] = $tab.'.'.$k;
787                 $this->colsJname[sprintf($ocl.'_%s', $k)] = 'join_'.$ocl.'_'.$col.'.'.$k;
788             }
789             
790             
791         }
792         
793         if ($has_distinct) {
794             $do->selectAdd($has_distinct);
795         }
796         //DB_DataObject::debugLevel(1);
797         // we do select as after everything else as we need to plop distinct at the beginning??
798         /// well I assume..
799        // echo '<PRE>';print_r($this->colsJname);exit;
800         foreach($selectAs as $ar) {
801             $do->selectAs($ar[0], $ar[1], $ar[2]);
802         }
803         
804         
805     }
806     /**
807      * generate the meta data neede by queries.
808      * 
809      */
810     function meta($x, $data)
811     {
812         // this is not going to work on queries where the data does not match the database def..
813         // for unknown columns we send them as stirngs..
814         $lost = 0;
815         $cols  = array_keys($data[0]);
816      
817         
818         
819         
820         //echo '<PRE>';print_r($this->cols); exit;
821         $options = &PEAR::getStaticProperty('DB_DataObject','options');
822         $reader = $options["ini_{$x->_database}"] .'.reader';
823         if (!file_exists( $reader )) {
824             return;
825         }
826         
827         $rdata = unserialize(file_get_contents($reader));
828         
829        // echo '<PRE>';print_r($rdata);exit;
830         
831         $meta = array();
832         foreach($cols as $c ) {
833             if (!isset($this->cols[$c]) || !isset($rdata[$this->cols[$c]]) || !is_array($rdata[$this->cols[$c]])) {
834                 $meta[] = $c;
835                 continue;    
836             }
837             $add = $rdata[$this->cols[$c]];
838             $add['name'] = $c;
839             $meta[] = $add;
840         }
841         return array(
842             'totalProperty' =>  'total',
843             'successProperty' => 'success',
844             'root' => 'data',
845             'id' => 'id',
846             'fields' => $meta
847         );
848          
849         
850     }
851     
852     function setFilters($x, $q)
853     {
854         // if a column is type int, and we get ',' -> the it should be come an inc clause..
855        // DB_DataObject::debugLevel(1);
856         if (method_exists($x, 'applyFilters')) {
857            // DB_DataObject::debugLevel(1);
858             $x->applyFilters($q, $this->authUser);
859         }
860         $q_filtered = array();
861         
862         foreach($q as $key=>$val) {
863             
864             // value is an array..
865             if (is_array($val) ) {
866                 
867                 if (!in_array( $key,  array_keys($this->cols))) {
868                     continue;
869                 }
870                 
871                 // support a[0] a[1] ..... => whereAddIn(
872                 $ar = array();
873                 $quote = false;
874                 foreach($val as $k=>$v) {
875                     if (!is_numeric($k)) {
876                         $ar = array();
877                         break;
878                     }
879                     // FIXME: note this is not typesafe for anything other than mysql..
880                     
881                     if (!is_numeric($v) || !is_long($v)) {
882                         $quote = true;
883                     }
884                     $ar[] = $v;
885                     
886                 }
887                 if (count($ar)) {
888                     
889                     
890                     $x->whereAddIn(
891                         isset($this->colsJname[$key]) ? 
892                             $this->colsJname[$key] :
893                             ($x->tableName(). '.'.$key),
894                         $ar, $quote ? 'string' : 'int');
895                 }
896                 
897                 continue;
898             }
899             
900             
901             
902             if ($key[0] == '!' && in_array(substr($key, 1), array_keys($this->cols))) {
903                 
904                 $key  = substr($key, 1) ;
905                 
906                 $x->whereAdd(   (
907                         isset($this->colsJname[$key]) ? 
908                             $this->colsJname[$key] :
909                             $x->tableName(). '.'.$key ) . ' != ' .
910                     (is_numeric($val) ? $val : "'".  $x->escape($val) . "'")
911                 );
912                 continue;
913                 
914             }
915             
916             
917             
918             switch($key) {
919                     
920                 // Events and remarks -- fixme - move to events/remarsk...
921                 case 'on_id':  // where TF is this used...
922                     if (!empty($q['query']['original'])) {
923                       //  DB_DataObject::debugLevel(1);
924                         $o = (int) $q['query']['original'];
925                         $oid = (int) $val;
926                         $x->whereAdd("(on_id = $oid  OR 
927                                 on_id IN ( SELECT distinct(id) FROM Documents WHERE original = $o ) 
928                             )");
929                         continue;
930                                 
931                     }
932                     $x->on_id = $val;
933                 
934                 
935                 default:
936                     if (strlen($val)) {
937                         $q_filtered[$key] = $val;
938                     }
939                     
940                     // subjoined columns = check the values.
941                     // note this is not typesafe for anything other than mysql..
942                     
943                     if (isset($this->colsJname[$key])) {
944                         $quote = false;
945                         if (!is_numeric($val) || !is_long($val)) {
946                             $quote = true;
947                         }
948                         $x->whereAdd( "{$this->colsJname[$key]} = " . ($quote ? "'". $x->escape($val) ."'" : $val));
949                         
950                     }
951                     
952                     
953                     continue;
954             }
955         }
956         
957         $x->setFrom($q_filtered);
958         
959         
960         
961        
962         // nice generic -- let's get rid of it.. where is it used!!!!
963         // used by: 
964         // Person / Group / most of my queries noww...
965         if (!empty($q['query']['name'])) {
966             $x->whereAdd($x->tableName().".name LIKE '". $x->escape($q['query']['name']) . "%'");
967         }
968         
969         // - projectdirectory staff list - persn queuy
970       
971          
972        
973          
974           
975         
976         
977     }
978     
979 }