fix #8131 - chinese translations
[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         if (function_exists('create_function')) {
193             $clean = create_function('$v', 'return (int)$v;');
194         } else {
195             $clean = function($v) {
196                 return (int)$v;
197             };
198         }
199         
200         $bits = array_map($clean, explode(',', $req['_delete']));
201         
202        // print_r($bits);exit;
203          
204         // let's assume it has a key!!!
205         
206         
207         $x->whereAdd($this->key .'  IN ('. implode(',', $bits) .')');
208         if (!$x->find()) {
209             $this->jerr("Nothing found to delete");
210         }
211         $errs = array();
212         while ($x->fetch()) {
213             $xx = clone($x);
214             
215            
216             // perms first.
217             
218             if (!$this->checkPerm($x,'D') )  {
219                 $this->jerr("PERMISSION DENIED (d)");
220             }
221             
222             $match_ar = array();
223             foreach($affects as $k=> $true) {
224                 $ka = explode('.', $k);
225                 
226                 $chk = DB_DataObject::factory($ka[0]);
227                 if (!is_a($chk,'DB_DataObject')) {
228                     $this->jerr('Unable to load referenced table, check the links config: ' .$ka[0]);
229                 }
230                // print_r(array($chk->tablename() , $ka[1] ,  $xx->tablename() , $this->key ));
231                 $chk->{$ka[1]} =  $xx->{$this->key};
232                 
233                 if (count($chk->keys())) {
234                     $matches = $chk->count();
235                 } else {
236                     //DB_DataObject::DebugLevel(1);
237                     $matches = $chk->count($ka[1]);
238                 }
239                 
240                 if ($matches) {
241                     $chk->_match_key = $ka[1];
242                     $match_ar[] = clone($chk);
243                     continue;
244                 }          
245             }
246             
247             $has_beforeDelete = method_exists($xx, 'beforeDelete');
248             // before delte = allows us to trash dependancies if needed..
249             $match_total = 0;
250             
251             if ( $has_beforeDelete ) {
252                 if ($xx->beforeDelete($match_ar, $this, $req) === false) {
253                     $errs[] = "Delete failed ({$xx->id})\n".
254                         (isset($xx->err) ? $xx->err : '');
255                     continue;
256                 }
257                 // refetch affects..
258                 
259                 $match_ar = array();
260                 foreach($affects as $k=> $true) {
261                     $ka = explode('.', $k);
262                     $chk = DB_DataObject::factory($ka[0]);
263                     if (!is_a($chk,'DB_DataObject')) {
264                         $this->jerr('Unable to load referenced table, check the links config: ' .$ka[0]);
265                     }
266                     $chk->{$ka[1]} =  $xx->{$this->key};
267                     $matches = $chk->count();
268                     $match_total += $matches;
269                     if ($matches) {
270                         $chk->_match_key = $ka[1];
271                         $match_ar[] = clone($chk);
272                         continue;
273                     }          
274                 }
275                 
276             }
277             
278             if (!empty($match_ar)) {
279                 $chk = $match_ar[0];
280                 $chk->limit(1);
281                 $o = $chk->fetchAll();
282                 $key = isset($chk->_match_key) ?$chk->_match_key  : '?unknown column?';
283                 $desc =  $chk->tableName(). '.' . $key .'='.$xx->{$this->key} ;
284                 if (method_exists($chk, 'toEventString')) {
285                     $desc .=  ' : ' . $o[0]->toEventString();
286                 }
287                     
288                 $this->jerr("Delete Dependant records ($match_total  found),  " .
289                              "first is ( $desc )");
290           
291             }
292             
293             $this->logDeleteEvent($x);
294             
295             $xx->delete();
296             
297             if (method_exists($xx,'onDelete')) {
298                 $xx->onDelete($req, $this);
299             }
300             
301             
302         }
303         if ($errs) {
304             $this->jerr(implode("\n<BR>", $errs));
305         }
306         $this->jok("Deleted");
307         
308     }
309     
310     function logDeleteEvent($object)
311     {
312         
313         DB_DataObject::Factory('Events')->logDeletedRecord($object);
314         
315         $this->addEvent("DELETE", $object);
316           
317         
318     }
319     
320     
321     function update($x, $req,  $with_perm_check = true)
322     {
323         if ( $with_perm_check && !$this->checkPerm($x,'E', $req) )  {
324             $this->jerr("PERMISSION DENIED - No Edit permissions on this element");
325         }
326        
327         // check any locks..
328         // only done if we recieve a lock_id.
329         // we are very trusing here.. that someone has not messed around with locks..
330         // the object might want to check in their checkPerm - if locking is essential..
331         $lock = $this->updateLock($x,$req);
332         
333         $old = clone($x);
334         $this->old = $x;
335         // this lot is generic.. needs moving 
336         if (method_exists($x, 'setFromRoo')) {
337             $res = $x->setFromRoo($req, $this);
338             if (is_string($res)) {
339                 $this->jerr($res);
340             }
341         } else {
342             $x->setFrom($req);
343         }
344       
345         
346         
347         //echo '<PRE>';print_r($old);print_r($x);exit;
348         //print_r($old);
349         
350         $cols = $x->table();
351         //print_r($cols);
352         if (isset($cols['modified'])) {
353             $x->modified = date('Y-m-d H:i:s');
354         }
355         if (isset($cols['modified_dt'])) {
356             $x->modified_dt = date('Y-m-d H:i:s');
357         }
358         if (isset($cols['modified_by']) && $this->authUser) {
359             $x->modified_by = $this->authUser->id;
360         }
361         
362         if (isset($cols['updated'])) {
363             $x->updated = date('Y-m-d H:i:s');
364         }
365         if (isset($cols['updated_dt'])) {
366             $x->updated_dt = date('Y-m-d H:i:s');
367         }
368         if (isset($cols['updated_by']) && $this->authUser) {
369             $x->updated_by = $this->authUser->id;
370         }
371         
372         if (method_exists($x, 'beforeUpdate')) {
373             $x->beforeUpdate($old, $req, $this);
374         }
375         
376         if ($with_perm_check && !empty($_FILES) && method_exists($x, 'onUpload')) {
377             $x->onUpload($this, $_REQUEST);
378         }
379         
380         //DB_DataObject::DebugLevel(1);
381         $res = $x->update($old);
382         if ($res === false) {
383             $this->jerr($x->_lastError->toString());
384         }
385         
386         if (method_exists($x, 'onUpdate')) {
387             $x->onUpdate($old, $req, $this);
388         }
389         $ev = $this->addEvent("EDIT", $x);
390         if ($ev) { 
391             $ev->audit($x, $old);
392         }
393         
394         
395         return $this->selectSingle(
396             DB_DataObject::factory($x->tableName()),
397             $x->{$this->key}
398         );
399         
400     }
401     
402     function updateLock($x, $req )
403     {
404         $this->permitError = true; // allow it to fail without dieing
405         
406         $lock = DB_DataObjecT::factory('core_locking');
407         $this->permitError = false; 
408         if (is_a($lock,'DB_DataObject') && $this->authUser)  {
409                  
410             $lock->on_id = $x->{$this->key};
411             $lock->on_table= strtolower($x->tableName());
412             if (!empty($_REQUEST['_lock_id'])) {
413                 $lock->whereAdd('id != ' . ((int)$_REQUEST['_lock_id']));
414             } else {
415                 $lock->whereAdd('person_id !=' . $this->authUser->id);
416             }
417             
418             $llc = clone($lock);
419             $exp = date('Y-m-d', strtotime('NOW - 1 WEEK'));
420             $llc->whereAdd("created < '$exp'");
421             if ($llc->count()) {
422                 $llc->find();
423                 while($llc->fetch()) {
424                     $llcd = clone($llc);
425                     $llcd->delete();
426                 }
427             }
428             
429             $lock->limit(1);
430             if ($lock->find(true)) {
431                 // it's locked by someone else..
432                $p = $lock->person();
433                
434                
435                $this->jerr( "Record was locked by " . $p->name . " at " .$lock->created.
436                            " - Please confirm you wish to save" 
437                            , array('needs_confirm' => true)); 
438           
439               
440             }
441             // check the users lock.. - no point.. ??? - if there are no other locks and it's not the users, then they can 
442             // edit it anyways...
443             
444             // can we find the user's lock.
445             $lock = DB_DataObjecT::factory('core_locking');
446             $lock->on_id = $x->{$this->key};
447             $lock->on_table= strtolower($x->tableName());
448             $lock->person_id = $this->authUser->id;
449             $lock->orderBy('created DESC');
450             $lock->limit(1);
451             
452             if (
453                     $lock->find(true) &&
454                     isset($x->modified_dt) &&
455                     strtotime($x->modified_dt) > strtotime($lock->created) &&
456                     empty($req['_submit_confirmed']) &&
457                     $x->modified_by != $this->authUser->id      
458                 )
459             {
460                 $p = DB_DataObject::factory('core_person');
461                 $p->get($x->modified_by);
462                 $this->jerr($p->name . " saved the record since you started editing,\nDo you really want to update it?", array('needs_confirm' => true)); 
463                 
464             }
465         }
466         
467         return $lock;
468         
469     }
470     
471     function insert($x, $req, $with_perm_check = true)
472     {   
473         if (method_exists($x, 'setFromRoo')) {
474             $res = $x->setFromRoo($req, $this);
475             if (is_string($res)) {
476                 $this->jerr($res);
477             }
478         } else {
479             $x->setFrom($req);
480         }
481         
482         if ( $with_perm_check &&  !$this->checkPerm($x,'A', $req))  {
483             $this->jerr("PERMISSION DENIED (i)");
484         }
485         $cols = $x->table();
486      
487         if (isset($cols['created'])) {
488             $x->created = date('Y-m-d H:i:s');
489         }
490         if (isset($cols['created_dt'])) {
491             $x->created_dt = date('Y-m-d H:i:s');
492         }
493         if (isset($cols['created_by'])) {
494             $x->created_by = $this->authUser->id;
495         }
496         
497      
498         if (isset($cols['modified'])) {
499             $x->modified = date('Y-m-d H:i:s');
500         }
501         if (isset($cols['modified_dt'])) {
502             $x->modified_dt = date('Y-m-d H:i:s');
503         }
504         if (isset($cols['modified_by'])) {
505             $x->modified_by = $this->authUser->id;
506         }
507         
508         if (isset($cols['updated'])) {
509             $x->updated = date('Y-m-d H:i:s');
510         }
511         if (isset($cols['updated_dt'])) {
512             $x->updated_dt = date('Y-m-d H:i:s');
513         }
514         if (isset($cols['updated_by'])) {
515             $x->updated_by = $this->authUser->id;
516         }
517         
518         if (method_exists($x, 'beforeInsert')) {
519             $x->beforeInsert($_REQUEST, $this);
520         }
521         
522         $res = $x->insert();
523         if ($res === false) {
524             $this->jerr($x->_lastError->toString());
525         }
526         if (method_exists($x, 'onInsert')) {
527             $x->onInsert($_REQUEST, $this);
528         }
529         $ev = $this->addEvent("ADD", $x);
530         if ($ev) { 
531             $ev->audit($x);
532         }
533         
534         // note setFrom might handle this before hand...!??!
535         if (!empty($_FILES) && method_exists($x, 'onUpload')) {
536             $x->onUpload($this, $_REQUEST);
537         }
538         
539         return $this->selectSingle(
540             DB_DataObject::factory($x->tableName()),
541             $x->pid()
542         );
543         
544     }
545 }