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