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