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