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