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