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