RooPostTrait.php
[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)
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         if (!empty($_REQUEST['_ids'])) {
126             $ids = explode(',',$_REQUEST['_ids']);
127             $x->whereAddIn($this->key, $ids, 'int');
128             $ar = $x->fetchAll();
129             
130             foreach($ar as $x) {
131                 $this->update($x, $_REQUEST);
132                 
133             }
134             // all done..
135             $this->jok("UPDATED");
136             
137             
138         }
139          
140         if (!empty($_REQUEST[$this->key])) {
141             // it's a create..
142             if (!$x->get($this->key, $_REQUEST[$this->key]))  {
143                 $this->jerr("Invalid request");
144             }
145             $this->jok($this->update($x, $_REQUEST));
146         } else {
147             
148             if (empty($_POST)) {
149                 $this->jerr("No data recieved for inserting");
150             }
151             
152             $this->jok($this->insert($x, $_REQUEST));
153             
154         }
155         
156         
157         
158     }
159     
160     function delete($x, $req)
161     {
162         // do we really delete stuff!?!?!?
163         if (empty($req['_delete'])) {
164             $this->jerr("Delete Requested with no value");
165         }
166         // build a list of tables to queriy for dependant data..
167         $map = $x->links();
168         
169         $affects  = array();
170         
171         $all_links = $GLOBALS['_DB_DATAOBJECT']['LINKS'][$x->_database];
172         foreach($all_links as $tbl => $links) {
173             foreach($links as $col => $totbl_col) {
174                 $to = explode(':', $totbl_col);
175                 if ($to[0] != $x->tableName()) {
176                     continue;
177                 }
178                 
179                 $affects[$tbl .'.' . $col] = true;
180             }
181         }
182         // collect tables
183
184        // echo '<PRE>';print_r($affects);exit;
185        // DB_Dataobject::debugLevel(1);
186        
187         
188         $clean = create_function('$v', 'return (int)$v;');
189         
190         $bits = array_map($clean, explode(',', $req['_delete']));
191         
192        // print_r($bits);exit;
193          
194         // let's assume it has a key!!!
195         
196         
197         $x->whereAdd($this->key .'  IN ('. implode(',', $bits) .')');
198         if (!$x->find()) {
199             $this->jerr("Nothing found to delete");
200         }
201         $errs = array();
202         while ($x->fetch()) {
203             $xx = clone($x);
204             
205            
206             // perms first.
207             
208             if (!$this->checkPerm($x,'D') )  {
209                 $this->jerr("PERMISSION DENIED (d)");
210             }
211             
212             $match_ar = array();
213             foreach($affects as $k=> $true) {
214                 $ka = explode('.', $k);
215                 
216                 $chk = DB_DataObject::factory($ka[0]);
217                 if (!is_a($chk,'DB_DataObject')) {
218                     $this->jerr('Unable to load referenced table, check the links config: ' .$ka[0]);
219                 }
220                // print_r(array($chk->tablename() , $ka[1] ,  $xx->tablename() , $this->key ));
221                 $chk->{$ka[1]} =  $xx->{$this->key};
222                 
223                 if (count($chk->keys())) {
224                     $matches = $chk->count();
225                 } else {
226                     //DB_DataObject::DebugLevel(1);
227                     $matches = $chk->count($ka[1]);
228                 }
229                 
230                 if ($matches) {
231                     $chk->_match_key = $ka[1];
232                     $match_ar[] = clone($chk);
233                     continue;
234                 }          
235             }
236             
237             $has_beforeDelete = method_exists($xx, 'beforeDelete');
238             // before delte = allows us to trash dependancies if needed..
239             $match_total = 0;
240             
241             if ( $has_beforeDelete ) {
242                 if ($xx->beforeDelete($match_ar, $this) === false) {
243                     $errs[] = "Delete failed ({$xx->id})\n".
244                         (isset($xx->err) ? $xx->err : '');
245                     continue;
246                 }
247                 // refetch affects..
248                 
249                 $match_ar = array();
250                 foreach($affects as $k=> $true) {
251                     $ka = explode('.', $k);
252                     $chk = DB_DataObject::factory($ka[0]);
253                     if (!is_a($chk,'DB_DataObject')) {
254                         $this->jerr('Unable to load referenced table, check the links config: ' .$ka[0]);
255                     }
256                     $chk->{$ka[1]} =  $xx->{$this->key};
257                     $matches = $chk->count();
258                     $match_total += $matches;
259                     if ($matches) {
260                         $chk->_match_key = $ka[1];
261                         $match_ar[] = clone($chk);
262                         continue;
263                     }          
264                 }
265                 
266             }
267             
268             if (!empty($match_ar)) {
269                 $chk = $match_ar[0];
270                 $chk->limit(1);
271                 $o = $chk->fetchAll();
272                 $key = isset($chk->_match_key) ?$chk->_match_key  : '?unknown column?';
273                 $desc =  $chk->tableName(). '.' . $key .'='.$xx->{$this->key} ;
274                 if (method_exists($chk, 'toEventString')) {
275                     $desc .=  ' : ' . $o[0]->toEventString();
276                 }
277                     
278                 $this->jerr("Delete Dependant records ($match_total  found),  " .
279                              "first is ( $desc )");
280           
281             }
282             
283             DB_DataObject::Factory('Events')->logDeletedRecord($x);
284             
285             $this->addEvent("DELETE", $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 }