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 checkDebugPost()
72     {
73         return (!empty($_GET['_post']) || !empty($_GET['_debug_post'])) && 
74                     $this->authUser && 
75                     method_exists($this->authUser,'groups') &&
76                     in_array('Administrators', $this->authUser->groups('name')); 
77         
78     }
79     
80     function dataObject($tab)
81     {
82         if (is_array($this->validTables) &&  !in_array($tab, $this->validTables)) {
83             $this->jerr("Invalid url - not listed in validTables");
84         }
85         
86         $tab = str_replace('/', '',$tab); // basic protection??
87         
88         $x = DB_DataObject::factory($tab);
89         
90         if (!is_a($x, 'DB_DataObject')) {
91             $this->jerr('invalid url - no dataobject');
92         }
93     
94         return $x;
95     }
96     
97     /*
98      * From Pman.php
99      */
100     
101     static $permitError = false;
102     
103     function onPearError($err)
104     {
105         static $reported = false;
106         if ($reported) {
107             return;
108         }
109         
110         if (Pman::$permitError) {
111              
112             return;
113             
114         }
115         
116         $reported = true;
117         $out = $err->toString();
118         
119         $ret = array();
120         $n = 0;
121         
122         foreach($err->backtrace as $b) {
123             $ret[] = @$b['file'] . '(' . @$b['line'] . ')@' .   @$b['class'] . '::' . @$b['function'];
124             if ($n > 20) {
125                 break;
126             }
127             $n++;
128         }
129         //convert the huge backtrace into something that is readable..
130         $out .= "\n" . implode("\n",  $ret);
131      
132         print_R($out);exit;
133         
134         $this->jerr($out);
135         
136     }
137     
138     function jok($str)
139     {
140         if ($this->transObj ) {
141             $this->transObj->query( connection_aborted() ? 'ROLLBACK' :  'COMMIT');
142         }
143         
144         $cli = HTML_FlexyFramework::get()->cli;
145         
146         if ($cli) {
147             echo "OK: " .$str . "\n";
148             exit;
149         }
150         require_once 'Services/JSON.php';
151         $json = new Services_JSON();
152         
153         $retHTML = isset($_SERVER['CONTENT_TYPE']) && 
154                 preg_match('#multipart/form-data#i', $_SERVER['CONTENT_TYPE']);
155         
156         if ($retHTML){
157             if (isset($_REQUEST['returnHTML']) && $_REQUEST['returnHTML'] == 'NO') {
158                 $retHTML = false;
159             }
160         } else {
161             $retHTML = isset($_REQUEST['returnHTML']) && $_REQUEST['returnHTML'] !='NO';
162         }
163         
164         if ($retHTML) {
165             header('Content-type: text/html');
166             echo "<HTML><HEAD></HEAD><BODY>";
167             // encode html characters so they can be read..
168             echo  str_replace(array('<','>'), array('\u003c','\u003e'),
169                         $json->encodeUnsafe(array('success'=> true, 'data' => $str)));
170             echo "</BODY></HTML>";
171             exit;
172         }
173         
174         
175         echo  $json->encode(array('success'=> true, 'data' => $str));
176         
177         exit;
178     }
179     
180     
181     function jerr($str, $errors=array(), $content_type = false)
182     {
183         if ($this->transObj) {
184             $this->transObj->query('ROLLBACK');
185         }
186         
187         return $this->jerror('ERROR', $str,$errors,$content_type);
188     }
189     
190     function jerror($type, $str, $errors=array(), $content_type = false) // standard error reporting..
191     {
192         if ($type !== false) {
193             $this->addEvent($type, false, $str);
194         }
195          
196         $cli = HTML_FlexyFramework::get()->cli;
197         if ($cli) {
198             echo "ERROR: " .$str . "\n";
199             exit;
200         }
201         
202         
203         if ($content_type == 'text/plain') {
204             header('Content-Disposition: attachment; filename="error.txt"');
205             header('Content-type: '. $content_type);
206             echo "ERROR: " .$str . "\n";
207             exit;
208         } 
209         
210         require_once 'Services/JSON.php';
211         $json = new Services_JSON();
212         
213         $retHTML = isset($_SERVER['CONTENT_TYPE']) && 
214                 preg_match('#multipart/form-data#i', $_SERVER['CONTENT_TYPE']);
215         
216         if ($retHTML){
217             if (isset($_REQUEST['returnHTML']) && $_REQUEST['returnHTML'] == 'NO') {
218                 $retHTML = false;
219             }
220         } else {
221             $retHTML = isset($_REQUEST['returnHTML']) && $_REQUEST['returnHTML'] !='NO';
222         }
223         
224         if ($retHTML) {
225             header('Content-type: text/html');
226             echo "<HTML><HEAD></HEAD><BODY>";
227             echo  $json->encodeUnsafe(array(
228                     'success'=> false, 
229                     'errorMsg' => $str,
230                     'message' => $str, // compate with exeption / loadexception.
231
232                     'errors' => $errors ? $errors : true, // used by forms to flag errors.
233                     'authFailure' => !empty($errors['authFailure']),
234                 ));
235             echo "</BODY></HTML>";
236             exit;
237         }
238         
239         if (isset($_REQUEST['_debug'])) {
240             echo '<PRE>'.htmlspecialchars(print_r(array(
241                 'success'=> false, 
242                 'data'=> array(), 
243                 'errorMsg' => $str,
244                 'message' => $str, // compate with exeption / loadexception.
245                 'errors' => $errors ? $errors : true, // used by forms to flag errors.
246                 'authFailure' => !empty($errors['authFailure']),
247             ),true));
248             exit;
249                 
250         }
251         
252         echo $json->encode(array(
253             'success'=> false, 
254             'data'=> array(), 
255             'errorMsg' => $str,
256             'message' => $str, // compate with exeption / loadexception.
257             'errors' => $errors ? $errors : true, // used by forms to flag errors.
258             'authFailure' => !empty($errors['authFailure']),
259         ));
260         
261         exit;
262         
263     }
264     
265     function jdata($ar,$total=false, $extra=array(), $cachekey = false)
266     {
267         // should do mobile checking???
268         if ($total == false) {
269             $total = count($ar);
270         }
271         $extra=  $extra ? $extra : array();
272         require_once 'Services/JSON.php';
273         $json = new Services_JSON();
274         
275         $retHTML = isset($_SERVER['CONTENT_TYPE']) && 
276                 preg_match('#multipart/form-data#i', $_SERVER['CONTENT_TYPE']);
277         
278         if ($retHTML){
279             if (isset($_REQUEST['returnHTML']) && $_REQUEST['returnHTML'] == 'NO') {
280                 $retHTML = false;
281             }
282         } else {
283             $retHTML = isset($_REQUEST['returnHTML']) && $_REQUEST['returnHTML'] !='NO';
284         }
285         
286         if ($retHTML) {
287             
288             header('Content-type: text/html');
289             echo "<HTML><HEAD></HEAD><BODY>";
290             // encode html characters so they can be read..
291             echo  str_replace(array('<','>'), array('\u003c','\u003e'),
292                         $json->encodeUnsafe(array('success' =>  true, 'total'=> $total, 'data' => $ar) + $extra));
293             echo "</BODY></HTML>";
294             exit;
295         }
296         
297         
298         // see if trimming will help...
299         if (!empty($_REQUEST['_pman_short'])) {
300             $nar = array();
301             
302             foreach($ar as $as) {
303                 $add = array();
304                 foreach($as as $k=>$v) {
305                     if (is_string($v) && !strlen(trim($v))) {
306                         continue;
307                     }
308                     $add[$k] = $v;
309                 }
310                 $nar[] = $add;
311             }
312             $ar = $nar;
313               
314         }
315         
316       
317         $ret =  $json->encode(array('success' =>  true, 'total'=> $total, 'data' => $ar) + $extra);  
318         
319         if (!empty($cachekey)) {
320             
321             $fn = ini_get('session.save_path') . '/json-cache'.date('/Y/m/d').'.'. $cachekey . '.cache.json';
322             if (!file_exists(dirname($fn))) {
323                 mkdir(dirname($fn), 0777,true);
324             }
325             file_put_contents($fn, $ret);
326         }
327         echo $ret;
328         exit;
329     }
330     
331     /** a daily cache **/
332     function jdataCache($cachekey)
333     {
334         $fn = ini_get('session.save_path') . '/json-cache'.date('/Y/m/d').'.'. $cachekey . '.cache.json';
335         if (file_exists($fn)) {
336             header('Content-type: application/json');
337             echo file_get_contents($fn);
338             exit;
339         }
340         return false;
341         
342     }
343     
344     function addEvent($act, $obj = false, $remarks = '') 
345     {
346         
347         if (!empty(HTML_FlexyFramework::get()->Pman['disable_events'])) {
348             return;
349         }
350         
351         $au = $this->getAuthUser();
352        
353         $e = DB_DataObject::factory('Events');
354         $e->init($act,$obj,$remarks); 
355          
356         $e->event_when = date('Y-m-d H:i:s');
357         
358         $eid = $e->insert();
359         
360         // fixme - this should be in onInsert..
361         $wa = DB_DataObject::factory('core_watch');
362         if (method_exists($wa,'notifyEvent')) {
363             $wa->notifyEvent($e); // trigger any actions..
364         }
365         
366         
367         $e->onInsert(isset($_REQUEST) ? $_REQUEST : array() , $this);
368         
369         return $e;
370         
371     }
372     
373     function getAuthUser()
374     {
375         if (!empty($this->authUser)) {
376             return $this->authUser;
377         }
378         $ff = HTML_FlexyFramework::get();
379         $tbl = empty($ff->Pman['authTable']) ? 'Person' : $ff->Pman['authTable'];
380         
381         $u = DB_DataObject::factory( $tbl );
382         if (!$u->isAuth()) {
383             return false;
384         }
385         $this->authUser =$u->getAuthUser();
386         return $this->authUser ;
387     }
388 }