9cb720f84a7598f12a93fda350a37663da51f2b7
[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         
671         if ($filter) {
672             $cols = array();
673             $has_distinct = false;
674             foreach($xx as $c) {
675                 if ($distinct && $distinct == $c) {
676                     $has_distinct=$c;
677                     continue;
678                 }
679                 if (in_array($c, $filter)) {
680                     $cols[] = $c;
681                 }
682             }
683             if ($has_distinct) {
684                 $do->selectAdd( 'DISTINCT( ' . $do->tableName() .'.'. $has_distinct .' as ' . $has_distinct );
685             }
686             $selectAs = array(array(  $cols , '%s'));
687             
688         } 
689         
690         $this->cols = array();
691         $this->colsJoinName =array();
692         foreach($xx as $k) {
693             $this->cols[$k] = $do->tableName(). '.' . $k;
694         }
695         
696         
697         
698         
699          
700         
701         foreach($map as $ocl=>$info) {
702             
703             list($tab,$col) = explode(':', $info);
704             // what about multiple joins on the same table!!!
705             $xx = DB_DataObject::factory($tab);
706             if (!is_a($xx, 'DB_DataObject')) {
707                 continue;
708             }
709             // this is borked ... for multiple jions..
710             $do->joinAdd($xx, 'LEFT', 'join_'.$ocl.'_'. $col, $ocl);
711             $tabdef = $xx->table();
712             $table = $xx->tableName();
713             if (isset($tabdef['passwd'])) {
714              
715                 unset($tabdef['passwd']);
716               
717             } 
718             $xx = array_keys($tabdef);
719             
720             
721             if ($filter) {
722                 $cols = array();
723                 foreach($xx as $c) {
724                     
725                     $tn = sprintf($ocl.'_%s', $c);
726                     if (in_array($tn, $filter)) {
727                         $cols[] = $c;
728                     }
729                 }
730                 $selectAs[] = array($cols, $ocl.'_%s', 'join_'.$ocl.'_'. $col);
731                 
732             } else {
733                 $selectAs[] = array($xx, $ocl.'_%s', 'join_'.$ocl.'_'. $col);
734                 
735             }
736              
737             
738             foreach($xx as $k) {
739                 $this->cols[sprintf($ocl.'_%s', $k)] = $tab.'.'.$k;
740                 $this->colsJname[sprintf($ocl.'_%s', $k)] = 'join_'.$ocl.'_'.$col.'.'.$k;
741             }
742             
743             
744         }
745         //DB_DataObject::debugLevel(1);
746         // we do select as after everything else as we need to plop distinct at the beginning??
747         /// well I assume..
748         foreach($selectAs as $ar) {
749             $do->selectAs($ar[0], $ar[1])
750         }
751         
752         
753     }
754     /**
755      * generate the meta data neede by queries.
756      * 
757      */
758     function meta($x, $data)
759     {
760         // this is not going to work on queries where the data does not match the database def..
761         // for unknown columns we send them as stirngs..
762         $lost = 0;
763         $cols  = array_keys($data[0]);
764      
765         
766         
767         
768         //echo '<PRE>';print_r($this->cols); exit;
769         $options = &PEAR::getStaticProperty('DB_DataObject','options');
770         $reader = $options["ini_{$x->_database}"] .'.reader';
771         if (!file_exists( $reader )) {
772             return;
773         }
774         
775         $rdata = unserialize(file_get_contents($reader));
776         
777        // echo '<PRE>';print_r($rdata);exit;
778         
779         $meta = array();
780         foreach($cols as $c ) {
781             if (!isset($this->cols[$c]) || !isset($rdata[$this->cols[$c]]) || !is_array($rdata[$this->cols[$c]])) {
782                 $meta[] = $c;
783                 continue;    
784             }
785             $add = $rdata[$this->cols[$c]];
786             $add['name'] = $c;
787             $meta[] = $add;
788         }
789         return array(
790             'totalProperty' =>  'total',
791             'successProperty' => 'success',
792             'root' => 'data',
793             'id' => 'id',
794             'fields' => $meta
795         );
796          
797         
798     }
799     
800     function setFilters($x, $q)
801     {
802         // if a column is type int, and we get ',' -> the it should be come an inc clause..
803        // DB_DataObject::debugLevel(1);
804         if (method_exists($x, 'applyFilters')) {
805            // DB_DataObject::debugLevel(1);
806             $x->applyFilters($q, $this->authUser);
807         }
808         $q_filtered = array();
809         
810         foreach($q as $key=>$val) {
811             
812             // value is an array..
813             if (is_array($val) ) {
814                 
815                 if (!in_array( $key,  array_keys($this->cols))) {
816                     continue;
817                 }
818                 
819                 // support a[0] a[1] ..... => whereAddIn(
820                 $ar = array();
821                 $quote = false;
822                 foreach($val as $k=>$v) {
823                     if (!is_numeric($k)) {
824                         $ar = array();
825                         break;
826                     }
827                     // FIXME: note this is not typesafe for anything other than mysql..
828                     
829                     if (!is_numeric($v) || !is_long($v)) {
830                         $quote = true;
831                     }
832                     $ar[] = $v;
833                     
834                 }
835                 if (count($ar)) {
836                     
837                     
838                     $x->whereAddIn(
839                         isset($this->colsJoinName[$key]) ? 
840                             $this->colsJoinName[$key] :
841                             $x->tableName(). '.'.$key,
842                         $ar, $quote ? 'string' : 'int');
843                 }
844                 
845                 continue;
846             }
847             
848             
849             
850             if ($key[0] == '!' && in_array(substr($key, 1), array_keys($this->cols))) {
851                 
852                 $key  = substr($key, 1) ;
853                 
854                 $x->whereAdd(   (
855                         isset($this->colsJoinName[$key]) ? 
856                             $this->colsJoinName[$key] :
857                             $x->tableName(). '.'.$key ) . ' != ' .
858                     (is_numeric($val) ? $val : "'".  $x->escape($val) . "'")
859                 );
860                 continue;
861                 
862             }
863             
864             
865             
866             switch($key) {
867                     
868                 // Events and remarks -- fixme - move to events/remarsk...
869                 case 'on_id':  // where TF is this used...
870                     if (!empty($q['query']['original'])) {
871                       //  DB_DataObject::debugLevel(1);
872                         $o = (int) $q['query']['original'];
873                         $oid = (int) $val;
874                         $x->whereAdd("(on_id = $oid  OR 
875                                 on_id IN ( SELECT distinct(id) FROM Documents WHERE original = $o ) 
876                             )");
877                         continue;
878                                 
879                     }
880                     $x->on_id = $val;
881                 
882                 
883                 default:
884                     if (strlen($val)) {
885                         $q_filtered[$key] = $val;
886                     }
887                     
888                     // subjoined columns = check the values.
889                     // note this is not typesafe for anything other than mysql..
890                     
891                     if (isset($this->colsJname[$key])) {
892                         $quote = false;
893                         if (!is_numeric($val) || !is_long($val)) {
894                             $quote = true;
895                         }
896                         $x->whereAdd( "{$this->colsJname[$key]} = " . ($quote ? "'". $x->escape($val) ."'" : $val));
897                         
898                     }
899                     
900                     
901                     continue;
902             }
903         }
904         
905         $x->setFrom($q_filtered);
906         
907         
908         
909        
910         // nice generic -- let's get rid of it.. where is it used!!!!
911         // used by: 
912         // Person / Group / most of my queries noww...
913         if (!empty($q['query']['name'])) {
914             $x->whereAdd($x->tableName().".name LIKE '". $x->escape($q['query']['name']) . "%'");
915         }
916         
917         // - projectdirectory staff list - persn queuy
918       
919          
920        
921          
922           
923         
924         
925     }
926     
927 }