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