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