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