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