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