RooTrait.php
[Pman.Core] / RooTrait.php
1 <?php
2
3 trait Pman_Core_RooTrait {
4     
5     var $validTables = false; 
6     
7     var $key;
8     
9     var $transObj = false;
10     
11     var $debugEnabled = true;
12     
13     function init() 
14     {
15         if (isset($this->_hasInit)) {
16             return;
17         }
18         
19         $this->_hasInit = true;
20         
21         $boot = HTML_FlexyFramework::get();
22         
23         $this->appName= $boot->appName;
24         $this->appNameShort= $boot->appNameShort;
25         $this->appModules= $boot->enable;
26         $this->isDev = empty($boot->Pman['isDev']) ? false : $boot->Pman['isDev'];
27         $this->appDisable = $boot->disable;
28         $this->appDisabled = explode(',', $boot->disable);
29         $this->version = $boot->version; 
30         $this->uiConfig = empty($boot->Pman['uiConfig']) ? false : $boot->Pman['uiConfig']; 
31         
32         if (!empty($ff->Pman['local_autoauth']) && 
33             ($_SERVER['SERVER_ADDR'] == '127.0.0.1') &&
34             ($_SERVER['REMOTE_ADDR'] == '127.0.0.1') 
35         ) {
36             $this->isDev = true;
37         }
38         
39     }
40     
41     function checkDebug($req = false)
42     {
43         $req =  $req === false  ? $_REQUEST : $req;
44         if (isset($req['_debug']) 
45                 && 
46                 $this->authUser
47                 &&
48                 (
49                     (
50                         method_exists($this->authUser,'canDebug')
51                         &&
52                         $this->authUser->canDebug()
53                     )
54                 ||
55                     (  
56                     
57                         method_exists($this->authUser,'groups') 
58                         &&
59                         is_a($this->authUser, 'Pman_Core_DataObjects_Person')
60                         &&
61                         in_array('Administrators', $this->authUser->groups('name'))
62                     )
63                 )
64                 
65             ){
66             DB_DAtaObject::debuglevel((int)$req['_debug']);
67         }
68         
69     }
70     
71     function dataObject($tab)
72     {
73         if (is_array($this->validTables) &&  !in_array($tab, $this->validTables)) {
74             $this->jerr("Invalid url - not listed in validTables");
75         }
76         
77         $tab = str_replace('/', '',$tab); // basic protection??
78         
79         $x = DB_DataObject::factory($tab);
80         
81         if (!is_a($x, 'DB_DataObject')) {
82             $this->jerr('invalid url - no dataobject');
83         }
84     
85         return $x;
86     }
87     
88     function selectSingle($x, $id, $req=false)
89     {
90         $_columns = !empty($req['_columns']) ? explode(',', $req['_columns']) : false;
91
92         if (!is_array($id) && empty($id)) {
93             
94             if (method_exists($x, 'toRooSingleArray')) {
95                 $this->jok($x->toRooSingleArray($this->getAuthUser(), $req));
96             }
97             
98             if (method_exists($x, 'toRooArray')) {
99                 $this->jok($x->toRooArray($req));
100             }
101             
102             $this->jok($x->toArray());
103         }
104         
105         $this->loadMap($x, array(
106             'columns' => $_columns,
107         ));
108         
109         if ($req !== false) { 
110             $this->setFilters($x, $req);
111         }
112         
113         if (is_array($id)) {
114             // lookup...
115             $x->setFrom($req['lookup'] );
116             $x->limit(1);
117             if (!$x->find(true)) {
118                 if (!empty($id['_id'])) {
119                     // standardize this?
120                     $this->jok($x->toArray());
121                 }
122                 $this->jok(false);
123             }
124             
125         } else if (!$x->get($id)) {
126             $this->jerr("selectSingle: no such record ($id)");
127         }
128         
129         // ignore perms if comming from update/insert - as it's already done...
130         if ($req !== false && !$this->checkPerm($x,'S'))  {
131             $this->jerr("PERMISSION DENIED - si");
132         }
133         // different symantics on all these calls??
134         if (method_exists($x, 'toRooSingleArray')) {
135             $this->jok($x->toRooSingleArray($this->getAuthUser(), $req));
136         }
137         if (method_exists($x, 'toRooArray')) {
138             $this->jok($x->toRooArray($req));
139         }
140         
141         $this->jok($x->toArray());
142         
143         
144     }
145     
146     var $cols = array();
147     
148     function loadMap($do, $cfg =array())
149     {
150         $onlycolumns    = !empty($cfg['columns']) ? $cfg['columns'] : false;
151         $distinct       = !empty($cfg['distinct']) ? $cfg['distinct'] : false;
152         $excludecolumns = !empty($cfg['exclude']) ? $cfg['exclude'] : array();
153           
154         $excludecolumns[] = 'passwd'; // we never expose passwords
155         
156         print_R($do);exit;
157         
158         $ret = $do->autoJoin(array(
159             'include' => $onlycolumns,
160             'exclude' => $excludecolumns,
161             'distinct' => $distinct
162         ));
163         
164         $this->countWhat = $ret['count'];
165         $this->cols = $ret['cols'];
166         $this->colsJname = $ret['join_names'];
167         
168         return;
169         
170     }
171     
172     function setFilters($x, $q)
173     {
174         if (method_exists($x, 'applyFilters')) {
175            // DB_DataObject::debugLevel(1);
176             if (false === $x->applyFilters($q, $this->getAuthUser(), $this)) {
177                 return; 
178             } 
179         }
180         $q_filtered = array();
181         
182         $keys = $x->keys();
183         // var_dump($keys);exit;
184         foreach($q as $key=>$val) {
185             
186             if (in_array($key,$keys) && !is_array($val)) {
187                
188                 $x->$key  = $val;
189             }
190             
191              // handles name[]=fred&name[]=brian => name in ('fred', 'brian').
192             // value is an array..
193             if (is_array($val) ) {
194                 
195                 $pref = '';
196                 
197                 if ($key[0] == '!') {
198                     $pref = '!';
199                     $key = substr($key,1);
200                 }
201                 
202                 if (!in_array( $key,  array_keys($this->cols))) {
203                     continue;
204                 }
205                 
206                 // support a[0] a[1] ..... => whereAddIn(
207                 $ar = array();
208                 $quote = false;
209                 foreach($val as $k=>$v) {
210                     if (!is_numeric($k)) {
211                         $ar = array();
212                         break;
213                     }
214                     // FIXME: note this is not typesafe for anything other than mysql..
215                     
216                     if (!is_numeric($v) || !is_long($v)) {
217                         $quote = true;
218                     }
219                     $ar[] = $v;
220                     
221                 }
222                 if (count($ar)) {
223                     
224                     
225                     $x->whereAddIn($pref . (
226                         isset($this->colsJname[$key]) ? 
227                             $this->colsJname[$key] :
228                             ($x->tableName(). '.'.$key)),
229                         $ar, $quote ? 'string' : 'int');
230                 }
231                 
232                 continue;
233             }
234             
235             
236             // handles !name=fred => name not equal fred.
237             if ($key[0] == '!' && in_array(substr($key, 1), array_keys($this->cols))) {
238                 
239                 $key  = substr($key, 1) ;
240                 
241                 $x->whereAdd(   (
242                         isset($this->colsJname[$key]) ? 
243                             $this->colsJname[$key] :
244                             $x->tableName(). '.'.$key ) . ' != ' .
245                     (is_numeric($val) ? $val : "'".  $x->escape($val) . "'")
246                 );
247                 continue;
248                 
249             }
250
251             switch($key) {
252                     
253                 // Events and remarks -- fixme - move to events/remarsk...
254                 case 'on_id':  // where TF is this used...
255                     if (!empty($q['query']['original'])) {
256                       //  DB_DataObject::debugLevel(1);
257                         $o = (int) $q['query']['original'];
258                         $oid = (int) $val;
259                         $x->whereAdd("(on_id = $oid  OR 
260                                 on_id IN ( SELECT distinct(id) FROM Documents WHERE original = $o ) 
261                             )");
262                         continue;
263                                 
264                     }
265                     $x->on_id = $val;
266                 
267                 
268                 default:
269                     if (strlen($val) && $key[0] != '_') {
270                         $q_filtered[$key] = $val;
271                     }
272                     
273                     // subjoined columns = check the values.
274                     // note this is not typesafe for anything other than mysql..
275                     
276                     if (isset($this->colsJname[$key])) {
277                         $quote = false;
278                         if (!is_numeric($val) || !is_long($val)) {
279                             $quote = true;
280                         }
281                         $x->whereAdd( "{$this->colsJname[$key]} = " . ($quote ? "'". $x->escape($val) ."'" : $val));
282                         
283                     }
284                     
285                     
286                     continue;
287             }
288         }
289         if (!empty($q_filtered)) {
290             $x->setFrom($q_filtered);
291         }
292         
293         if (!empty($q['query']['name'])) {
294             if (in_array( 'name',  array_keys($x->table()))) {
295                 $x->whereAdd($x->tableName().".name LIKE '". $x->escape($q['query']['name']) . "%'");
296             }
297         }
298         
299     }
300     
301     
302     /*
303      * From Pman.php
304      */
305     
306     static $permitError = false;
307     
308     function onPearError($err)
309     {
310         static $reported = false;
311         if ($reported) {
312             return;
313         }
314         
315         if (Pman::$permitError) {
316              
317             return;
318             
319         }
320         
321         $reported = true;
322         $out = $err->toString();
323         
324         $ret = array();
325         $n = 0;
326         
327         foreach($err->backtrace as $b) {
328             $ret[] = @$b['file'] . '(' . @$b['line'] . ')@' .   @$b['class'] . '::' . @$b['function'];
329             if ($n > 20) {
330                 break;
331             }
332             $n++;
333         }
334         //convert the huge backtrace into something that is readable..
335         $out .= "\n" . implode("\n",  $ret);
336      
337         print_R($out);exit;
338         
339         $this->jerr($out);
340         
341     }
342     
343     function addEvent($act, $obj = false, $remarks = '') 
344     {
345         if (!empty(HTML_FlexyFramework::get()->Pman['disable_events'])) {
346             return;
347         }
348         
349         $e = DB_DataObject::factory('Events');
350         $e->init($act,$obj,$remarks); 
351          
352         $e->event_when = date('Y-m-d H:i:s');
353         
354         $eid = $e->insert();
355         
356         // fixme - this should be in onInsert..
357         $wa = DB_DataObject::factory('core_watch');
358         if (method_exists($wa,'notifyEvent')) {
359             $wa->notifyEvent($e); // trigger any actions..
360         }
361         
362         $e->onInsert(isset($_REQUEST) ? $_REQUEST : array() , $this);
363         
364         return $e;
365         
366     }
367     
368     function checkPerm($obj, $lvl, $req= null)
369     {
370         if (!method_exists($obj, 'checkPerm')) {
371             return true;
372         }
373         if ($obj->checkPerm($lvl, $this->getAuthUser(), $req))  {
374             return true;
375         }
376         
377         return false;
378     }
379     
380     function hasPerm($name, $lvl)  // do we have a permission
381     {
382         static $pcache = array();
383         $au = $this->getAuthUser();
384         return $au && $au->hasPerm($name, $lvl);
385         
386     }
387     
388     function getAuthUser()
389     {
390         die('Get auth user is not implement.');
391     }
392     
393 }