Pman/Images.php
[Pman.Base] / Pman / Roo.php
1 <?php
2
3
4 require_once 'Pman.php';
5 /**
6  * 
7  * 
8  * not really sure how save our factory method is....!!!
9  * 
10  * 
11  * Uses these methods of the dataobjects:
12  * - checkPerm('L'/'E'/'A', $authuser) - can we list the stuff
13  * 
14  * - applySort($au, $sortcol, $direction)
15  * - applyFilters($_REQUEST, $authUser) -- apply any query filters on data. and hide stuff not to be seen.
16  * - postListExtra - add extra column data on the results (like new messages etc.)
17  * -postListFilter($data, $authUser, $request) return $data - add extra data to an object
18  * 
19  * - toRooSingleArray($authUser) // single fetch, add data..
20  * - toRooArray($request) /// toArray if you need to return different data.. for a list fetch.
21  * 
22  * 
23  * - beforeDelete() -- return false for fail and set DO->err;
24  * - onUpdate($old, $request,$roo) - after update // return value ignored
25  * - onInsert($request,$roo) - after insert
26  * - onUpload($roo)
27  * - setFromRoo($ar) - values from post (deal with dates etc.) - return true|error string.
28  * 
29  * - toEventString (for logging)
30  */
31
32 class Pman_Roo extends Pman
33 {
34     
35    function getAuth() {
36         parent::getAuth(); // load company!
37         $au = $this->getAuthUser();
38         if (!$au) {
39             $this->jerr("Not authenticated", array('authFailure' => true));
40         }
41         $this->authUser = $au;
42         return true;
43     }
44     /**
45      * GET method   Roo/TABLENAME.php 
46      * -- defaults to listing data. with args.
47      * 
48      * !colname=....                 => colname != ....
49      * colname[0]=... colname[1]=... => colname IN (.....) ** only supports main table at present..
50      * 
51      * other opts:
52      * _post      = simulate a post with debuggin on.
53      * lookup     =  array( k=>v) single fetch based on a key/value pair
54      * _id        =  single fetch based on id.
55      * _delete    = delete a list of ids element. (seperated by ,);
56      * _columns   = comma seperated list of columns.
57      * _distinct   = a distinct column lookup.
58      * _requestMeta = default behaviour of Roo stores.. on first query..
59      * 
60      * csvCols[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           //DB_DataObject::debugLevel(1);
164         $total = $x->count($this->countWhat);
165         // sorting..
166       //   
167         //var_dump($total);exit;
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, $sort = '', $dir ='')
263     {
264         
265        // Db_DataObject::debugLevel(1);
266         $sort = empty($_REQUEST['sort']) ? $sort : $_REQUEST['sort'];
267         $dir = empty($_REQUEST['dir']) ? $dir : $_REQUEST['dir'];
268         $dir = $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', false));
657         $this->countWhat = false;
658         $has_distinct = false;
659         if ($filter || $distinct) {
660             $cols = array();
661             //echo '<PRE>' ;print_r($filter);exit;
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 (!$filter || in_array($c, $filter)) {
669                     $cols[] = $c;
670                 }
671             }
672             
673             
674             $selectAs = empty($cols) ?  array() : array(array(  $cols , '%s', false)) ;
675             
676             
677             
678         } 
679         
680         $this->cols = array();
681         $this->colsJoinName =array();
682         foreach($xx as $k) {
683             $this->cols[$k] = $do->tableName(). '.' . $k;
684         }
685         
686         
687         
688         
689          
690         
691         foreach($map as $ocl=>$info) {
692             
693             list($tab,$col) = explode(':', $info);
694             // what about multiple joins on the same table!!!
695             $xx = DB_DataObject::factory($tab);
696             if (!is_a($xx, 'DB_DataObject')) {
697                 continue;
698             }
699             // this is borked ... for multiple jions..
700             $do->joinAdd($xx, 'LEFT', 'join_'.$ocl.'_'. $col, $ocl);
701             $tabdef = $xx->table();
702             $table = $xx->tableName();
703             if (isset($tabdef['passwd'])) {
704              
705                 unset($tabdef['passwd']);
706               
707             } 
708             $xx = array_keys($tabdef);
709             
710             
711             if ($filter || $distinct) {
712                 $cols = array();
713                 foreach($xx as $c) {
714                     $tn = sprintf($ocl.'_%s', $c);
715                   // echo '<PRE>'; var_dump($tn);
716                     if ($distinct && $tn == $distinct) {
717                         $has_distinct = 'DISTINCT( ' . 'join_'.$ocl.'_'.$col.'.'.$k .')  as ' . $tn ;
718                         $this->countWhat =  'DISTINCT  join_'.$ocl.'_'.$col.'.'.$k;
719                         continue;
720                     }
721                     
722                     
723                     if (!$filter || in_array($tn, $filter)) {
724                         $cols[] = $c;
725                     }
726                 }
727                 if (!empty($cols)) {
728                      $selectAs[] = array($cols, $ocl.'_%s', 'join_'.$ocl.'_'. $col);
729                 }
730                
731                 
732             } else {
733                 $selectAs[] = array($xx, $ocl.'_%s', 'join_'.$ocl.'_'. $col);
734                 
735             }
736              
737             
738             foreach($xx as $k) {
739                 $this->cols[sprintf($ocl.'_%s', $k)] = $tab.'.'.$k;
740                 $this->colsJname[sprintf($ocl.'_%s', $k)] = 'join_'.$ocl.'_'.$col.'.'.$k;
741             }
742             
743             
744         }
745         
746         if ($has_distinct) {
747             $do->selectAdd($has_distinct);
748         }
749         //DB_DataObject::debugLevel(1);
750         // we do select as after everything else as we need to plop distinct at the beginning??
751         /// well I assume..
752        // echo '<PRE>';print_r($this->colsJname);exit;
753         foreach($selectAs as $ar) {
754             $do->selectAs($ar[0], $ar[1], $ar[2]);
755         }
756         
757         
758     }
759     /**
760      * generate the meta data neede by queries.
761      * 
762      */
763     function meta($x, $data)
764     {
765         // this is not going to work on queries where the data does not match the database def..
766         // for unknown columns we send them as stirngs..
767         $lost = 0;
768         $cols  = array_keys($data[0]);
769      
770         
771         
772         
773         //echo '<PRE>';print_r($this->cols); exit;
774         $options = &PEAR::getStaticProperty('DB_DataObject','options');
775         $reader = $options["ini_{$x->_database}"] .'.reader';
776         if (!file_exists( $reader )) {
777             return;
778         }
779         
780         $rdata = unserialize(file_get_contents($reader));
781         
782        // echo '<PRE>';print_r($rdata);exit;
783         
784         $meta = array();
785         foreach($cols as $c ) {
786             if (!isset($this->cols[$c]) || !isset($rdata[$this->cols[$c]]) || !is_array($rdata[$this->cols[$c]])) {
787                 $meta[] = $c;
788                 continue;    
789             }
790             $add = $rdata[$this->cols[$c]];
791             $add['name'] = $c;
792             $meta[] = $add;
793         }
794         return array(
795             'totalProperty' =>  'total',
796             'successProperty' => 'success',
797             'root' => 'data',
798             'id' => 'id',
799             'fields' => $meta
800         );
801          
802         
803     }
804     
805     function setFilters($x, $q)
806     {
807         // if a column is type int, and we get ',' -> the it should be come an inc clause..
808        // DB_DataObject::debugLevel(1);
809         if (method_exists($x, 'applyFilters')) {
810            // DB_DataObject::debugLevel(1);
811             $x->applyFilters($q, $this->authUser);
812         }
813         $q_filtered = array();
814         
815         foreach($q as $key=>$val) {
816             
817             // value is an array..
818             if (is_array($val) ) {
819                 
820                 if (!in_array( $key,  array_keys($this->cols))) {
821                     continue;
822                 }
823                 
824                 // support a[0] a[1] ..... => whereAddIn(
825                 $ar = array();
826                 $quote = false;
827                 foreach($val as $k=>$v) {
828                     if (!is_numeric($k)) {
829                         $ar = array();
830                         break;
831                     }
832                     // FIXME: note this is not typesafe for anything other than mysql..
833                     
834                     if (!is_numeric($v) || !is_long($v)) {
835                         $quote = true;
836                     }
837                     $ar[] = $v;
838                     
839                 }
840                 if (count($ar)) {
841                     
842                     
843                     $x->whereAddIn(
844                         isset($this->colsJname[$key]) ? 
845                             $this->colsJname[$key] :
846                             ($x->tableName(). '.'.$key),
847                         $ar, $quote ? 'string' : 'int');
848                 }
849                 
850                 continue;
851             }
852             
853             
854             
855             if ($key[0] == '!' && in_array(substr($key, 1), array_keys($this->cols))) {
856                 
857                 $key  = substr($key, 1) ;
858                 
859                 $x->whereAdd(   (
860                         isset($this->colsJname[$key]) ? 
861                             $this->colsJname[$key] :
862                             $x->tableName(). '.'.$key ) . ' != ' .
863                     (is_numeric($val) ? $val : "'".  $x->escape($val) . "'")
864                 );
865                 continue;
866                 
867             }
868             
869             
870             
871             switch($key) {
872                     
873                 // Events and remarks -- fixme - move to events/remarsk...
874                 case 'on_id':  // where TF is this used...
875                     if (!empty($q['query']['original'])) {
876                       //  DB_DataObject::debugLevel(1);
877                         $o = (int) $q['query']['original'];
878                         $oid = (int) $val;
879                         $x->whereAdd("(on_id = $oid  OR 
880                                 on_id IN ( SELECT distinct(id) FROM Documents WHERE original = $o ) 
881                             )");
882                         continue;
883                                 
884                     }
885                     $x->on_id = $val;
886                 
887                 
888                 default:
889                     if (strlen($val)) {
890                         $q_filtered[$key] = $val;
891                     }
892                     
893                     // subjoined columns = check the values.
894                     // note this is not typesafe for anything other than mysql..
895                     
896                     if (isset($this->colsJname[$key])) {
897                         $quote = false;
898                         if (!is_numeric($val) || !is_long($val)) {
899                             $quote = true;
900                         }
901                         $x->whereAdd( "{$this->colsJname[$key]} = " . ($quote ? "'". $x->escape($val) ."'" : $val));
902                         
903                     }
904                     
905                     
906                     continue;
907             }
908         }
909         
910         $x->setFrom($q_filtered);
911         
912         
913         
914        
915         // nice generic -- let's get rid of it.. where is it used!!!!
916         // used by: 
917         // Person / Group / most of my queries noww...
918         if (!empty($q['query']['name'])) {
919             $x->whereAdd($x->tableName().".name LIKE '". $x->escape($q['query']['name']) . "%'");
920         }
921         
922         // - projectdirectory staff list - persn queuy
923       
924          
925        
926          
927           
928         
929         
930     }
931     
932 }