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