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