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