sycn
[Pman.Core] / RooPostTrait.php
1 <?php
2
3 trait Pman_Core_RooPostTrait {
4     
5     /**
6      * POST method   Roo/TABLENAME  
7      * -- creates, updates, or deletes data.
8      *
9      * INSERT
10      *    if the primary key is empty, this happens
11      *    will automatically set these to current date and authUser->id
12      *        created, created_by, created_dt
13      *        updated, update_by, updated_dt
14      *        modified, modified_by, modified_dt
15      *        
16      *   will return a GET request SINGLE SELECT (and accepts same)
17      *    
18      * DELETE
19      *    _delete=1,2,3     delete a set of data.
20      * UPDATE
21      *    if the primary key value is set, then update occurs.
22      *    will automatically set these to current date and authUser->id
23      *        updated, update_by, updated_dt
24      *        modified, modified_by, modified_dt
25      *        
26      *
27      * Params:
28      *   _delete=1,2,3   causes a delete to occur.
29      *   _ids=1,2,3,4    causes update to occur on all primary ids.
30      *  
31      *  RETURNS
32      *     = same as single SELECT GET request..
33      *
34      *
35      *
36      * DEBUGGING
37      *   _debug=1    forces debug
38      *   _get=1 - causes a get request to occur when doing a POST..
39      *
40      *
41      * CALLS
42      *   these methods on dataobjects if they exist
43      * 
44      *   checkPerm('E' / 'D' , $authuser)
45      *                      - can we list the stuff
46      *                      - return false to disallow...
47    
48      *   toRooSingleArray($authUser, $request) : array
49      *                       - called on single fetch only, add or maniuplate returned array data.
50      *   toRooArray($request) : array
51      *                      - Called if toSingleArray does not exist.
52      *                      - if you need to return different data than toArray..
53      *
54      *   toEventString()
55      *                  (for logging - this is generically prefixed to all database operations.)
56      *
57      *  
58      *   onUpload($roo)
59      *                  called when $_FILES is not empty
60      *
61      *                  
62      *   setFromRoo($ar, $roo)
63      *                      - alternative to setFrom() which is called if this method does not exist
64      *                      - values from post (deal with dates etc.) - return true|error string.
65      *                      - call $roo->jerr() on failure...
66      *
67      * CALLS BEFORE change occurs:
68      *  
69      *      beforeDelete($dependants_array, $roo, $request)
70      *                      Argument is an array of un-find/fetched dependant items.
71      *                      - jerr() will stop insert.. (Prefered)
72      *                      - return false for fail and set DO->err;
73      *                      
74      *      beforeUpdate($old, $request,$roo)
75      *                      - after update - jerr() will stop insert..
76      *      beforeInsert($request,$roo)
77      *                      - before insert - jerr() will stop insert..
78      *
79      *
80      * CALLS AFTER change occured
81      * 
82      *      onUpdate($old, $request,$roo)
83      *               - after update // return value ignored
84      *
85      *      onInsert($request,$roo)
86      *                  - after insert
87      * 
88      *      onDelete($request, $roo) - after delete
89      * 
90      */                     
91      
92     function post($tab) // update / insert (?? delete??)
93     {   
94         PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($this, 'onPearError'));
95     
96         $this->checkDebug();
97         
98         if (!empty($_REQUEST['_get'])) {
99             return $this->get($tab);
100         }
101         
102         $this->init();
103          
104         $x = $this->dataObject($tab);
105         
106         $this->transObj = clone($x);
107         
108         $this->transObj->query('BEGIN');
109         // find the key and use that to get the thing..
110         $keys = $x->keys();
111         if (empty($keys) ) {
112             $this->jerr('no key');
113         }
114         
115         $this->key = $keys[0];
116         
117           // delete should be here...
118         if (isset($_REQUEST['_delete'])) {
119             // do we really delete stuff!?!?!?
120             return $this->delete($x,$_REQUEST);
121         } 
122         
123         $old = false;
124         
125         // not sure if this is a good idea here...
126         
127         if (!empty($_REQUEST['_ids'])) {
128             $ids = explode(',',$_REQUEST['_ids']);
129             $x->whereAddIn($this->key, $ids, 'int');
130             $ar = $x->fetchAll();
131             
132             foreach($ar as $x) {
133                 $this->update($x, $_REQUEST);
134                 
135             }
136             // all done..
137             $this->jok("UPDATED");
138             
139             
140         }
141          
142         if (!empty($_REQUEST[$this->key])) {
143             // it's a create..
144             if (!$x->get($this->key, $_REQUEST[$this->key]))  {
145                 $this->jerr("Invalid request");
146             }
147             $this->jok($this->update($x, $_REQUEST));
148         } else {
149             
150             if (empty($_POST)) {
151                 $this->jerr("No data recieved for inserting");
152             }
153             
154             $this->jok($this->insert($x, $_REQUEST));
155             
156         }
157         
158         
159         
160     }
161     
162     function delete($x, $req)
163     {
164         // do we really delete stuff!?!?!?
165         if (empty($req['_delete'])) {
166             $this->jerr("Delete Requested with no value");
167         }
168         // build a list of tables to queriy for dependant data..
169         $map = $x->links();
170         
171         $affects  = array();
172         
173         $all_links = $GLOBALS['_DB_DATAOBJECT']['LINKS'][$x->_database];
174         foreach($all_links as $tbl => $links) {
175             foreach($links as $col => $totbl_col) {
176                 $to = explode(':', $totbl_col);
177                 if ($to[0] != $x->tableName()) {
178                     continue;
179                 }
180                 
181                 $affects[$tbl .'.' . $col] = true;
182             }
183         }
184         // collect tables
185
186        // echo '<PRE>';print_r($affects);exit;
187        // DB_Dataobject::debugLevel(1);
188        
189         
190         $clean = create_function('$v', 'return (int)$v;');
191         
192         $bits = array_map($clean, explode(',', $req['_delete']));
193         
194        // print_r($bits);exit;
195          
196         // let's assume it has a key!!!
197         
198         
199         $x->whereAdd($this->key .'  IN ('. implode(',', $bits) .')');
200         if (!$x->find()) {
201             $this->jerr("Nothing found to delete");
202         }
203         $errs = array();
204         while ($x->fetch()) {
205             $xx = clone($x);
206             
207            
208             // perms first.
209             
210             if (!$this->checkPerm($x,'D') )  {
211                 $this->jerr("PERMISSION DENIED (d)");
212             }
213             
214             $match_ar = array();
215             foreach($affects as $k=> $true) {
216                 $ka = explode('.', $k);
217                 
218                 $chk = DB_DataObject::factory($ka[0]);
219                 if (!is_a($chk,'DB_DataObject')) {
220                     $this->jerr('Unable to load referenced table, check the links config: ' .$ka[0]);
221                 }
222                // print_r(array($chk->tablename() , $ka[1] ,  $xx->tablename() , $this->key ));
223                 $chk->{$ka[1]} =  $xx->{$this->key};
224                 
225                 if (count($chk->keys())) {
226                     $matches = $chk->count();
227                 } else {
228                     //DB_DataObject::DebugLevel(1);
229                     $matches = $chk->count($ka[1]);
230                 }
231                 
232                 if ($matches) {
233                     $chk->_match_key = $ka[1];
234                     $match_ar[] = clone($chk);
235                     continue;
236                 }          
237             }
238             
239             $has_beforeDelete = method_exists($xx, 'beforeDelete');
240             // before delte = allows us to trash dependancies if needed..
241             $match_total = 0;
242             
243             if ( $has_beforeDelete ) {
244                 if ($xx->beforeDelete($match_ar, $this, $req) === false) {
245                     $errs[] = "Delete failed ({$xx->id})\n".
246                         (isset($xx->err) ? $xx->err : '');
247                     continue;
248                 }
249                 // refetch affects..
250                 
251                 $match_ar = array();
252                 foreach($affects as $k=> $true) {
253                     $ka = explode('.', $k);
254                     $chk = DB_DataObject::factory($ka[0]);
255                     if (!is_a($chk,'DB_DataObject')) {
256                         $this->jerr('Unable to load referenced table, check the links config: ' .$ka[0]);
257                     }
258                     $chk->{$ka[1]} =  $xx->{$this->key};
259                     $matches = $chk->count();
260                     $match_total += $matches;
261                     if ($matches) {
262                         $chk->_match_key = $ka[1];
263                         $match_ar[] = clone($chk);
264                         continue;
265                     }          
266                 }
267                 
268             }
269             
270             if (!empty($match_ar)) {
271                 $chk = $match_ar[0];
272                 $chk->limit(1);
273                 $o = $chk->fetchAll();
274                 $key = isset($chk->_match_key) ?$chk->_match_key  : '?unknown column?';
275                 $desc =  $chk->tableName(). '.' . $key .'='.$xx->{$this->key} ;
276                 if (method_exists($chk, 'toEventString')) {
277                     $desc .=  ' : ' . $o[0]->toEventString();
278                 }
279                     
280                 $this->jerr("Delete Dependant records ($match_total  found),  " .
281                              "first is ( $desc )");
282           
283             }
284             
285             $this->logDeleteEvent($x);
286             
287             $xx->delete();
288             
289             if (method_exists($xx,'onDelete')) {
290                 $xx->onDelete($req, $this);
291             }
292             
293             
294         }
295         if ($errs) {
296             $this->jerr(implode("\n<BR>", $errs));
297         }
298         $this->jok("Deleted");
299         
300     }
301     
302     function logDeleteEvent($object)
303     {
304         
305         DB_DataObject::Factory('Events')->logDeletedRecord($object);
306         
307         $this->addEvent("DELETE", $object);
308           
309         
310     }
311     
312     
313     function update($x, $req,  $with_perm_check = true)
314     {
315         if ( $with_perm_check && !$this->checkPerm($x,'E', $req) )  {
316             $this->jerr("PERMISSION DENIED - No Edit permissions on this element");
317         }
318        
319         // check any locks..
320         // only done if we recieve a lock_id.
321         // we are very trusing here.. that someone has not messed around with locks..
322         // the object might want to check in their checkPerm - if locking is essential..
323         $lock = $this->updateLock($x,$req);
324         
325         $old = clone($x);
326         $this->old = $x;
327         // this lot is generic.. needs moving 
328         if (method_exists($x, 'setFromRoo')) {
329             $res = $x->setFromRoo($req, $this);
330             if (is_string($res)) {
331                 $this->jerr($res);
332             }
333         } else {
334             $x->setFrom($req);
335         }
336       
337         
338         
339         //echo '<PRE>';print_r($old);print_r($x);exit;
340         //print_r($old);
341         
342         $cols = $x->table();
343         //print_r($cols);
344         if (isset($cols['modified'])) {
345             $x->modified = date('Y-m-d H:i:s');
346         }
347         if (isset($cols['modified_dt'])) {
348             $x->modified_dt = date('Y-m-d H:i:s');
349         }
350         if (isset($cols['modified_by']) && $this->authUser) {
351             $x->modified_by = $this->authUser->id;
352         }
353         
354         if (isset($cols['updated'])) {
355             $x->updated = date('Y-m-d H:i:s');
356         }
357         if (isset($cols['updated_dt'])) {
358             $x->updated_dt = date('Y-m-d H:i:s');
359         }
360         if (isset($cols['updated_by']) && $this->authUser) {
361             $x->updated_by = $this->authUser->id;
362         }
363         
364         if (method_exists($x, 'beforeUpdate')) {
365             $x->beforeUpdate($old, $req, $this);
366         }
367         
368         if ($with_perm_check && !empty($_FILES) && method_exists($x, 'onUpload')) {
369             $x->onUpload($this, $_REQUEST);
370         }
371         
372         //DB_DataObject::DebugLevel(1);
373         $res = $x->update($old);
374         if ($res === false) {
375             $this->jerr($x->_lastError->toString());
376         }
377         
378         if (method_exists($x, 'onUpdate')) {
379             $x->onUpdate($old, $req, $this);
380         }
381         $ev = $this->addEvent("EDIT", $x);
382         if ($ev) { 
383             $ev->audit($x, $old);
384         }
385         
386         
387         return $this->selectSingle(
388             DB_DataObject::factory($x->tableName()),
389             $x->{$this->key}
390         );
391         
392     }
393     
394     function updateLock($x, $req )
395     {
396         $this->permitError = true; // allow it to fail without dieing
397         
398         $lock = DB_DataObjecT::factory('core_locking');
399         $this->permitError = false; 
400         if (is_a($lock,'DB_DataObject') && $this->authUser)  {
401                  
402             $lock->on_id = $x->{$this->key};
403             $lock->on_table= strtolower($x->tableName());
404             if (!empty($_REQUEST['_lock_id'])) {
405                 $lock->whereAdd('id != ' . ((int)$_REQUEST['_lock_id']));
406             } else {
407                 $lock->whereAdd('person_id !=' . $this->authUser->id);
408             }
409             
410             $llc = clone($lock);
411             $exp = date('Y-m-d', strtotime('NOW - 1 WEEK'));
412             $llc->whereAdd("created < '$exp'");
413             if ($llc->count()) {
414                 $llc->find();
415                 while($llc->fetch()) {
416                     $llcd = clone($llc);
417                     $llcd->delete();
418                 }
419             }
420             
421             $lock->limit(1);
422             if ($lock->find(true)) {
423                 // it's locked by someone else..
424                $p = $lock->person();
425                
426                
427                $this->jerr( "Record was locked by " . $p->name . " at " .$lock->created.
428                            " - Please confirm you wish to save" 
429                            , array('needs_confirm' => true)); 
430           
431               
432             }
433             // check the users lock.. - no point.. ??? - if there are no other locks and it's not the users, then they can 
434             // edit it anyways...
435             
436             // can we find the user's lock.
437             $lock = DB_DataObjecT::factory('core_locking');
438             $lock->on_id = $x->{$this->key};
439             $lock->on_table= strtolower($x->tableName());
440             $lock->person_id = $this->authUser->id;
441             $lock->orderBy('created DESC');
442             $lock->limit(1);
443             
444             if (
445                     $lock->find(true) &&
446                     isset($x->modified_dt) &&
447                     strtotime($x->modified_dt) > strtotime($lock->created) &&
448                     empty($req['_submit_confirmed']) &&
449                     $x->modified_by != $this->authUser->id      
450                 )
451             {
452                 $p = DB_DataObject::factory('core_person');
453                 $p->get($x->modified_by);
454                 $this->jerr($p->name . " saved the record since you started editing,\nDo you really want to update it?", array('needs_confirm' => true)); 
455                 
456             }
457         }
458         
459         return $lock;
460         
461     }
462     
463     function insert($x, $req, $with_perm_check = true)
464     {   
465         if (method_exists($x, 'setFromRoo')) {
466             $res = $x->setFromRoo($req, $this);
467             if (is_string($res)) {
468                 $this->jerr($res);
469             }
470         } else {
471             $x->setFrom($req);
472         }
473         
474         if ( $with_perm_check &&  !$this->checkPerm($x,'A', $req))  {
475             $this->jerr("PERMISSION DENIED (i)");
476         }
477         $cols = $x->table();
478      
479         if (isset($cols['created'])) {
480             $x->created = date('Y-m-d H:i:s');
481         }
482         if (isset($cols['created_dt'])) {
483             $x->created_dt = date('Y-m-d H:i:s');
484         }
485         if (isset($cols['created_by'])) {
486             $x->created_by = $this->authUser->id;
487         }
488         
489      
490         if (isset($cols['modified'])) {
491             $x->modified = date('Y-m-d H:i:s');
492         }
493         if (isset($cols['modified_dt'])) {
494             $x->modified_dt = date('Y-m-d H:i:s');
495         }
496         if (isset($cols['modified_by'])) {
497             $x->modified_by = $this->authUser->id;
498         }
499         
500         if (isset($cols['updated'])) {
501             $x->updated = date('Y-m-d H:i:s');
502         }
503         if (isset($cols['updated_dt'])) {
504             $x->updated_dt = date('Y-m-d H:i:s');
505         }
506         if (isset($cols['updated_by'])) {
507             $x->updated_by = $this->authUser->id;
508         }
509         
510         if (method_exists($x, 'beforeInsert')) {
511             $x->beforeInsert($_REQUEST, $this);
512         }
513         
514         $res = $x->insert();
515         if ($res === false) {
516             $this->jerr($x->_lastError->toString());
517         }
518         if (method_exists($x, 'onInsert')) {
519             $x->onInsert($_REQUEST, $this);
520         }
521         $ev = $this->addEvent("ADD", $x);
522         if ($ev) { 
523             $ev->audit($x);
524         }
525         
526         // note setFrom might handle this before hand...!??!
527         if (!empty($_FILES) && method_exists($x, 'onUpload')) {
528             $x->onUpload($this, $_REQUEST);
529         }
530         
531         return $this->selectSingle(
532             DB_DataObject::factory($x->tableName()),
533             $x->pid()
534         );
535         
536     }
537 }