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