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