JsonOutputTrait.php
[Pman.Core] / JsonOutputTrait.php
1 <?php
2
3 trait Pman_Core_JsonOutputTrait {
4     
5     function jok($str)
6     {
7         if ($this->transObj ) {
8             $this->transObj->query( connection_aborted() ? 'ROLLBACK' :  'COMMIT');
9         }
10         
11         $cli = HTML_FlexyFramework::get()->cli;
12         if ($cli) {
13             echo "OK: " .$str . "\n";
14             exit;
15         }
16         
17         $retHTML = isset($_SERVER['CONTENT_TYPE']) && 
18                 preg_match('#multipart/form-data#i', $_SERVER['CONTENT_TYPE']);
19         
20         if ($retHTML){
21             if (isset($_REQUEST['returnHTML']) && $_REQUEST['returnHTML'] == 'NO') {
22                 $retHTML = false;
23             }
24         } else {
25             $retHTML = isset($_REQUEST['returnHTML']) && $_REQUEST['returnHTML'] !='NO';
26         }
27         
28         if ($retHTML) {
29             header('Content-type: text/html');
30             echo "<HTML><HEAD></HEAD><BODY>";
31             // encode html characters so they can be read..
32             echo  str_replace(array('<','>'), array('\u003c','\u003e'),
33                         $this->jsencode(array('success'=> true, 'data' => $str), false));
34             echo "</BODY></HTML>";
35             exit;
36         }
37         
38         
39         echo  $this->jsencode(array('success'=> true, 'data' => $str),true);
40         
41         exit;
42         
43     }
44     
45     
46       /**
47      * ---------------- Standard JSON outputers. - used everywhere
48      * JSON error - simple error with logging.
49      * @see Pman::jerror
50      */
51     
52     function jerr($str, $errors=array(), $content_type = false) // standard error reporting..
53     {
54         return $this->jerror('ERROR', $str,$errors,$content_type);
55     }
56     
57     function jnotice($type, $str, $errors=array(), $content_type = false)
58     {
59         return $this->jerror('NOTICE-' . $type, $str, $errors, $content_type);
60     }
61     
62      /**
63      * jerrAuth: standard auth failure - with data that let's the UI know..
64      */
65     function jerrAuth()
66     {
67         $au = $this->authUser;
68         if ($au) {
69             // is it an authfailure?
70             $this->jerror("LOGIN-NOPERM", "Permission denied to view this resource", array('authFailure' => true));
71         }
72         $this->jerror("LOGIN-NOAUTH", "Not authenticated", array('authFailure' => true));
73     }
74      
75      
76     /**
77      * Recomended JSON error indicator
78      *
79      * 
80      * @param string $type  - normally 'ERROR' - you can use this to track error types.
81      * @param string $message - error message displayed to user.
82      * @param array $errors - optioanl data to pass to front end.
83      * @param string $content_type - use text/plain to return plan text - ?? not sure why...
84      *
85      */
86     
87     function jerror($type, $str, $errors=array(), $content_type = false) // standard error reporting..
88     {
89         if ($this->transObj) {
90             $this->transObj->query('ROLLBACK');
91         }
92         
93         $cli = HTML_FlexyFramework::get()->cli;
94         if ($cli) {
95             echo "ERROR: " .$str . "\n"; // print the error first, as DB might fail..
96         }
97         $pman = HTML_FlexyFramework::get();
98         
99        
100         
101
102         
103         if ($type !== false  &&  empty($pman->nodatabase)) {
104             
105             if(!empty($errors)){
106                 DB_DataObject::factory('Events')->writeEventLogExtra($errors);
107             }
108             // various codes that are acceptable.
109             // 
110             if (!preg_match('/^(ERROR|NOTICE|LOG)/', $type )) {
111                 $type = 'ERROR-' . $type;
112             }
113             
114             $this->addEvent($type, false, $str);
115             
116         }
117          
118         $cli = HTML_FlexyFramework::get()->cli;
119         if ($cli) {
120             exit(1); // cli --- exit code to stop shell execution if necessary.
121         }
122         
123         
124         if ($content_type == 'text/plain') {
125             header('Content-Disposition: attachment; filename="error.txt"');
126             header('Content-type: '. $content_type);
127             echo "ERROR: " .$str . "\n";
128             exit;
129         } 
130         
131      // log all errors!!!
132         
133         $retHTML = isset($_SERVER['CONTENT_TYPE']) && 
134                 preg_match('#multipart/form-data#i', $_SERVER['CONTENT_TYPE']);
135         
136         if ($retHTML){
137             if (isset($_REQUEST['returnHTML']) && $_REQUEST['returnHTML'] == 'NO') {
138                 $retHTML = false;
139             }
140         } else {
141             $retHTML = isset($_REQUEST['returnHTML']) && $_REQUEST['returnHTML'] !='NO';
142         }
143         
144         
145         if ($retHTML) {
146             header('Content-type: text/html');
147             echo "<HTML><HEAD></HEAD><BODY>";
148             echo  $this->jsencode(array(
149                     'success'=> false, 
150                     'errorMsg' => $str,
151                     'message' => $str, // compate with exeption / loadexception.
152
153                     'errors' => $errors ? $errors : true, // used by forms to flag errors.
154                     'authFailure' => !empty($errors['authFailure']),
155                 ), false);
156             echo "</BODY></HTML>";
157             exit;
158         }
159         
160         if (isset($_REQUEST['_debug'])) {
161             echo '<PRE>'.htmlspecialchars(print_r(array(
162                 'success'=> false, 
163                 'data'=> array(), 
164                 'errorMsg' => $str,
165                 'message' => $str, // compate with exeption / loadexception.
166                 'errors' => $errors ? $errors : true, // used by forms to flag errors.
167                 'authFailure' => !empty($errors['authFailure']),
168             ),true));
169             exit;
170                 
171         }
172         
173         echo $this->jsencode(array(
174             'success'=> false, 
175             'data'=> array(),
176             'code' => $type,
177             'errorMsg' => $str,
178             'message' => $str, // compate with exeption / loadexception.
179             'errors' => $errors ? $errors : true, // used by forms to flag errors.
180             'authFailure' => !empty($errors['authFailure']),
181         ),true);
182         
183         
184         exit;
185         
186     }
187     
188      
189    
190     
191     
192     
193     /**
194      * output data for grids or tree
195      * @ar {Array} ar Array of data
196      * @total {Number|false} total number of records (or false to return count(ar)
197      * @extra {Array} extra key value list of data to pass as extra data.
198      * 
199      */
200     function jdata($ar,$total=false, $extra=array(), $cachekey = false)
201     {
202         // should do mobile checking???
203         if ($total == false) {
204             $total = count($ar);
205         }
206         $extra=  $extra ? $extra : array();
207         
208         
209         $retHTML = isset($_SERVER['CONTENT_TYPE']) && 
210                 preg_match('#multipart/form-data#i', $_SERVER['CONTENT_TYPE']);
211         
212         if ($retHTML){
213             if (isset($_REQUEST['returnHTML']) && $_REQUEST['returnHTML'] == 'NO') {
214                 $retHTML = false;
215             }
216         } else {
217             $retHTML = isset($_REQUEST['returnHTML']) && $_REQUEST['returnHTML'] !='NO';
218         }
219         
220         if ($retHTML) {
221             
222             header('Content-type: text/html');
223             echo "<HTML><HEAD></HEAD><BODY><![CDATA[";
224             // encode html characters so they can be read..
225             echo  str_replace(array('<','>'), array('\u003c','\u003e'),
226                         $this->jsencode(array('success' =>  true, 'total'=> $total, 'data' => $ar) + $extra, false));
227             echo "]]></BODY></HTML>";
228             exit;
229         }
230         
231         
232         // see if trimming will help...
233         if (!empty($_REQUEST['_pman_short'])) {
234             $nar = array();
235             
236             foreach($ar as $as) {
237                 $add = array();
238                 foreach($as as $k=>$v) {
239                     if (is_string($v) && !strlen(trim($v))) {
240                         continue;
241                     }
242                     $add[$k] = $v;
243                 }
244                 $nar[] = $add;
245             }
246             $ar = $nar;
247               
248         }
249         
250       
251         $ret =  $this->jsencode(array('success' =>  true, 'total'=> $total, 'data' => $ar) + $extra,true);  
252         
253         if (!empty($cachekey)) {
254             
255             $fn = ini_get('session.save_path') . '/json-cache'.date('/Y/m/d').'.'. $cachekey . '.cache.json';
256             if (!file_exists(dirname($fn))) {
257                 mkdir(dirname($fn), 0777,true);
258             }
259             file_put_contents($fn, $ret);
260         }
261         
262         echo $ret;
263         exit;
264     }
265     
266     
267    
268     /** a daily cache **/
269     function jdataCache($cachekey)
270     {
271         $fn = ini_get('session.save_path') . '/json-cache'.date('/Y/m/d').'.'. $cachekey . '.cache.json';
272         if (file_exists($fn)) {
273             header('Content-type: application/json');
274             echo file_get_contents($fn);
275             exit;
276         }
277         return false;
278         
279     }
280     
281 }