Pman/Images.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    = 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          
347         
348         $old = false;
349         
350         if (!empty($_REQUEST['_ids'])) {
351             $ids = explode(',',$_REQUEST['_ids']);
352             $x->whereAddIn($keys[0], $ids, 'int');
353             $ar = $x->fetchAll();
354             foreach($ar as $x) {
355                 $this->update($x, $_REQUEST);
356                 
357             }
358             // all done..
359             $this->jok("UPDATED");
360             
361             
362         }
363         
364         
365         if (!empty($_REQUEST[$keys[0]])) {
366             // it's a create..
367             if (!$x->get($keys[0], $_REQUEST[$keys[0]]))  {
368                 $this->jerr("Invalid request");
369             }
370             $this->jok($this->update($x, $_REQUEST));
371         } else {
372             
373             if (empty($_POST)) {
374                 $this->jerr("No data recieved for inserting");
375             }
376             
377             $this->jok($this->insert($x, $_REQUEST));
378             
379         }
380         
381         
382         
383     }
384     function insert($x, $req)
385     {
386         
387     
388         if (method_exists($x, 'checkPerm') && !$x->checkPerm('A', $this->authUser, $req))  {
389             $this->jerr("PERMISSION DENIED");
390         }
391         
392         $_columns = !empty($req['_columns']) ? explode(',', $req['_columns']) : false;
393    
394         if (method_exists($x, 'setFromRoo')) {
395             $res = $x->setFromRoo($req, $this);
396             if (is_string($res)) {
397                 $this->jerr($res);
398             }
399         } else {
400             $x->setFrom($req);
401         }
402         
403          
404         $cols = $x->table();
405      
406         if (isset($cols['created'])) {
407             $x->created = date('Y-m-d H:i:s');
408         }
409         if (isset($cols['created_dt'])) {
410             $x->created_dt = date('Y-m-d H:i:s');
411         }
412         if (isset($cols['created_by'])) {
413             $x->created_by = $this->authUser->id;
414         }
415         
416      
417          if (isset($cols['modified'])) {
418             $x->modified = date('Y-m-d H:i:s');
419         }
420         if (isset($cols['modified_dt'])) {
421             $x->modified_dt = date('Y-m-d H:i:s');
422         }
423         if (isset($cols['modified_by'])) {
424             $x->modified_by = $this->authUser->id;
425         }
426         
427         if (isset($cols['updated'])) {
428             $x->updated = date('Y-m-d H:i:s');
429         }
430         if (isset($cols['updated_dt'])) {
431             $x->updated_dt = date('Y-m-d H:i:s');
432         }
433         if (isset($cols['updated_by'])) {
434             $x->updated_by = $this->authUser->id;
435         }
436         
437      
438         
439         
440         
441         $x->insert();
442         if (method_exists($x, 'onInsert')) {
443             $x->onInsert($_REQUEST, $this);
444         }
445         $this->addEvent("ADD", $x, $x->toEventString());
446         
447         // note setFrom might handle this before hand...!??!
448         if (!empty($_FILES) && method_exists($x, 'onUpload')) {
449             $x->onUpload($this);
450         }
451         
452         $r = DB_DataObject::factory($x->tableName());
453           $pk = $x->keys();
454         // let's assume it has a key!!!
455         $pk = $pk[0];
456         $r->$pk = $x->$pk;
457         $this->loadMap($r, $_columns);
458         $r->limit(1);
459         $r->find(true);
460         
461         $rooar = method_exists($r, 'toRooArray');
462         //print_r(var_dump($rooar)); exit;
463         return $rooar  ? $r->toRooArray($_REQUEST) : $r->toArray();
464     }
465     
466     
467     function update($x, $req)
468     {
469         if (method_exists($x, 'checkPerm') && !$x->checkPerm('E', $this->authUser, $_REQUEST))  {
470             $this->jerr("PERMISSION DENIED");
471         }
472        
473         $_columns = !empty($req['_columns']) ? explode(',', $req['_columns']) : false;
474
475        
476         $old = clone($x);
477         $this->old = $x;
478         // this lot is generic.. needs moving 
479         if (method_exists($x, 'setFromRoo')) {
480             $res = $x->setFromRoo($req, $this);
481             if (is_string($res)) {
482                 $this->jerr($res);
483             }
484         } else {
485             $x->setFrom($req);
486         }
487         $this->addEvent("EDIT", $x, $x->toEventString());
488         //print_r($x);
489         //print_r($old);
490         
491         $cols = $x->table();
492         
493         if (isset($cols['modified'])) {
494             $x->modified = date('Y-m-d H:i:s');
495         }
496         if (isset($cols['modified_dt'])) {
497             $x->modified_dt = date('Y-m-d H:i:s');
498         }
499         if (isset($cols['modified_by'])) {
500             $x->modified_by = $this->authUser->id;
501         }
502         
503         if (isset($cols['updated'])) {
504             $x->updated = date('Y-m-d H:i:s');
505         }
506         if (isset($cols['updated_dt'])) {
507             $x->updated_dt = date('Y-m-d H:i:s');
508         }
509         if (isset($cols['updated_by'])) {
510             $x->updated_by = $this->authUser->id;
511         }
512         
513         
514         $x->update($old);
515         if (method_exists($x, 'onUpdate')) {
516             $x->onUpdate($old, $req, $this);
517         }
518         
519         $r = DB_DataObject::factory($x->tableName());
520         $pk = $x->keys();
521         // let's assume it has a key!!!
522         $pk = $pk[0];
523         $r->$pk = $x->$pk;
524         $this->loadMap($r, $_columns);
525         $r->limit(1);
526         $r->find(true);
527         $rooar = method_exists($r, 'toRooArray');
528         //print_r(var_dump($rooar)); exit;
529         return $rooar  ? $r->toRooArray($_REQUEST) : $r->toArray();
530     }
531     
532     function delete($x, $req)
533     {
534         // do we really delete stuff!?!?!?
535         if (empty($req['_delete'])) {
536             $this->jerr("Delete Requested with no value");
537             
538         }
539         // build a list of tables to queriy for dependant data..
540         $map = $x->links();
541         
542         $affects  = array();
543         
544         $all_links = $GLOBALS['_DB_DATAOBJECT']['LINKS'][$x->_database];
545         foreach($all_links as $tbl => $links) {
546             foreach($links as $col => $totbl_col) {
547                 $to = explode(':', $totbl_col);
548                 if ($to[0] != $x->tableName()) {
549                     continue;
550                 }
551                 
552                 $affects[$tbl .'.' . $col] = true;
553             }
554         }
555         // collect tables
556         
557        // echo '<PRE>';print_r($affects);exit;
558        //DB_Dataobject::debugLevel(1);
559        
560         
561         $clean = create_function('$v', 'return (int)$v;');
562         
563         $bits = array_map($clean, explode(',', $req['_delete']));
564         
565        // print_r($bits);exit;
566          $pk = $x->keys();
567         // let's assume it has a key!!!
568         $pk = $pk[0];
569         
570         $x->whereAdd($pk .'  IN ('. implode(',', $bits) .')');
571         if (!$x->find()) {
572             $this->jerr("Nothing found to delete");
573         }
574         $errs = array();
575         while ($x->fetch()) {
576             $xx = clone($x);
577             
578             
579             foreach($affects as $k=> $true) {
580                 $ka = explode('.', $k);
581                 $chk = DB_DataObject::factory($ka[0]);
582                 if (!is_a($chk,'DB_DataObject')) {
583                     $this->jerr('Unable to load referenced table, check the links config: ' .$ka[0]);
584                 }
585                 $chk->{$ka[1]} =  $xx->$pk;
586                 if ($chk->count()) {
587                     $this->jerr('Delete Dependant records first ('. $ka[0]. ':' . $ka[1] .'='.$xx->$pk.')');
588                 }
589             }
590             
591             
592             
593             if (method_exists($x, 'checkPerm') && !$x->checkPerm('D', $this->authUser))  {
594                 $this->jerr("PERMISSION DENIED");
595             }
596             
597             $this->addEvent("DELETE", $x, $x->toEventString());
598             if ( method_exists($xx, 'beforeDelete') && ($xx->beforeDelete() === false)) {
599                 $errs[] = "Delete failed ({$xx->id})\n". (isset($xx->err) ? $xx->err : '');
600                 continue;
601             }
602             $xx->delete();
603         }
604         if ($errs) {
605             $this->jerr(implode("\n<BR>", $errs));
606         }
607         $this->jok("Deleted");
608         
609     }
610    
611     
612     
613     
614     var $cols = array();
615     function loadMap($do, $filter=false) 
616     {
617         //DB_DataObject::debugLevel(1);
618         $conf = array();
619         
620         
621         $this->init();
622         $mods = explode(',',$this->appModules);
623         
624         $ff = HTML_FlexyFramework::geT();
625         //$db->databaseName();
626         
627         //$ff->DB_DataObject['ini_'. $db->database()];
628         //echo '<PRE>';print_r($do->links());exit;
629         //var_dump($mods);
630         
631         if (in_array('Builder', $mods) ) {
632             
633             foreach(in_array('Builder', $mods) ? scandir($this->rootDir.'/Pman') : $mods as $m) {
634                 
635                 if (!strlen($m) || $m[0] == '.' || !is_dir($this->rootDir."/Pman/$m")) {
636                     continue;
637                 }
638                 $ini = $this->rootDir."/Pman/$m/DataObjects/pman.links.ini";
639                 if (!file_exists($ini)) {
640                     continue;
641                 }
642                 $conf = array_merge($conf, parse_ini_file($ini,true));
643                 if (!isset($conf[$do->tableName()])) {
644                     return;
645                 }
646                 $map = $conf[$do->tableName()];
647             } 
648         } else {
649             $map = $do->links();
650         }
651          
652         
653         
654         
655         // current table..
656         $tabdef = $do->table();
657         if (isset($tabdef['passwd'])) {
658             // prevent exposure of passwords..
659             unset($tabdef['passwd']);     
660         }
661         $xx = clone($do);
662         $xx = array_keys($tabdef);
663         $do->selectAdd(); // we need thsi as normally it's only cleared by an empty selectAs call.
664         
665         if ($filter) {
666             $cols = array();
667          
668             foreach($xx as $c) {
669                 if (in_array($c, $filter)) {
670                     $cols[] = $c;
671                 }
672             }
673             $do->selectAs($cols);
674         } else {
675             $do->selectAs($xx);
676         }
677         
678         
679         $this->cols = array();
680         foreach($xx as $k) {
681             $this->cols[$k] = $do->tableName(). '.' . $k;
682         }
683         
684         
685         
686         
687          
688         
689         foreach($map as $ocl=>$info) {
690             
691             list($tab,$col) = explode(':', $info);
692             // what about multiple joins on the same table!!!
693             $xx = DB_DataObject::factory($tab);
694             if (!is_a($xx, 'DB_DataObject')) {
695                 continue;
696             }
697             // this is borked ... for multiple jions..
698             $do->joinAdd($xx, 'LEFT', 'join_'.$ocl.'_'. $col, $ocl);
699             $tabdef = $xx->table();
700             $table = $xx->tableName();
701             if (isset($tabdef['passwd'])) {
702              
703                 unset($tabdef['passwd']);
704               
705             } 
706             $xx = array_keys($tabdef);
707             
708             
709             if ($filter) {
710                 $cols = array();
711                 foreach($xx as $c) {
712                     
713                     $tn = sprintf($ocl.'_%s', $c);
714                     if (in_array($tn, $filter)) {
715                         $cols[] = $c;
716                     }
717                 }
718                 $do->selectAs($cols, $ocl.'_%s', 'join_'.$ocl.'_'. $col);
719             } else {
720                 $do->selectAs($xx,  $ocl.'_%s', 'join_'.$ocl.'_'. $col);
721             }
722              
723             
724             foreach($xx as $k) {
725                 $this->cols[sprintf($ocl.'_%s', $k)] = $tab.'.'.$k;
726             }
727             
728             
729         }
730         //DB_DataObject::debugLevel(1);
731         
732         
733         
734     }
735     /**
736      * generate the meta data neede by queries.
737      * 
738      */
739     function meta($x, $data)
740     {
741         // this is not going to work on queries where the data does not match the database def..
742         // for unknown columns we send them as stirngs..
743         $lost = 0;
744         $cols  = array_keys($data[0]);
745      
746         
747         
748         
749         //echo '<PRE>';print_r($this->cols); exit;
750         $options = &PEAR::getStaticProperty('DB_DataObject','options');
751         $reader = $options["ini_{$x->_database}"] .'.reader';
752         if (!file_exists( $reader )) {
753             return;
754         }
755         
756         $rdata = unserialize(file_get_contents($reader));
757         
758        // echo '<PRE>';print_r($rdata);exit;
759         
760         $meta = array();
761         foreach($cols as $c ) {
762             if (!isset($this->cols[$c]) || !isset($rdata[$this->cols[$c]]) || !is_array($rdata[$this->cols[$c]])) {
763                 $meta[] = $c;
764                 continue;    
765             }
766             $add = $rdata[$this->cols[$c]];
767             $add['name'] = $c;
768             $meta[] = $add;
769         }
770         return array(
771             'totalProperty' =>  'total',
772             'successProperty' => 'success',
773             'root' => 'data',
774             'id' => 'id',
775             'fields' => $meta
776         );
777          
778         
779     }
780     
781     function setFilters($x, $q)
782     {
783         // if a column is type int, and we get ',' -> the it should be come an inc clause..
784        // DB_DataObject::debugLevel(1);
785         if (method_exists($x, 'applyFilters')) {
786            // DB_DataObject::debugLevel(1);
787             $x->applyFilters($q, $this->authUser);
788         }
789         $q_filtered = array();
790         
791         foreach($q as $key=>$val) {
792             
793             if (is_array($val) ) {
794                 
795                 if (!in_array( $key,  array_keys($this->cols))) {
796                     continue;
797                 }
798                 
799                 // support a[0] a[1] ..... => whereAddIn(
800                 $ar = array();
801                 $quote = false;
802                 foreach($val as $k=>$v) {
803                     if (!is_numeric($k)) {
804                         $ar = array();
805                         break;
806                     }
807                     if (!is_numeric($v) || !is_long($v)) {
808                         $quote = true;
809                     }
810                     $ar[] = $v;
811                     
812                 }
813                 if (count($ar)) {
814                     $x->whereAddIn($x->tableName(). '.'.$key,$ar, $quote ? 'string' : 'int');
815                 }
816                 
817                 continue;
818             }
819             
820             
821             
822             if ($key[0] == '!' && in_array(substr($key, 1), array_keys($this->cols))) {
823                     
824                 $x->whereAdd( $x->tableName() .'.' .substr($key, 1) . ' != ' .
825                     (is_numeric($val) ? $val : "'".  $x->escape($val) . "'")
826                 );
827                 continue;
828                 
829             }
830             
831             
832             
833             switch($key) {
834                     
835                 // Events and remarks
836                 case 'on_id':  // where TF is this used...
837                     if (!empty($q['query']['original'])) {
838                       //  DB_DataObject::debugLevel(1);
839                         $o = (int) $q['query']['original'];
840                         $oid = (int) $val;
841                         $x->whereAdd("(on_id = $oid  OR 
842                                 on_id IN ( SELECT distinct(id) FROM Documents WHERE original = $o ) 
843                             )");
844                         continue;
845                                 
846                     }
847                     $x->on_id = $val;
848                 
849                 
850                 default:
851                     if (strlen($val)) {
852                         $q_filtered[$key] = $val;
853                     }
854                     
855                     continue;
856             }
857         }
858         $x->setFrom($q_filtered);
859        
860         // nice generic -- let's get rid of it.. where is it used!!!!
861         // used by: 
862         // Person / Group
863         if (!empty($q['query']['name'])) {
864             $x->whereAdd($x->tableName().".name LIKE '". $x->escape($q['query']['name']) . "%'");
865         }
866         
867         // - projectdirectory staff list - persn queuy
868       
869          
870        
871          
872           
873         
874         
875     }
876     
877 }