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      * Recomended JSON error indicator
64      *
65      * 
66      * @param string $type  - normally 'ERROR' - you can use this to track error types.
67      * @param string $message - error message displayed to user.
68      * @param array $errors - optioanl data to pass to front end.
69      * @param string $content_type - use text/plain to return plan text - ?? not sure why...
70      *
71      */
72     
73     function jerror($type, $str, $errors=array(), $content_type = false) // standard error reporting..
74     {
75         if ($this->transObj) {
76             $this->transObj->query('ROLLBACK');
77         }
78         
79         $cli = HTML_FlexyFramework::get()->cli;
80         if ($cli) {
81             echo "ERROR: " .$str . "\n"; // print the error first, as DB might fail..
82         }
83         $pman = HTML_FlexyFramework::get();
84         
85        
86         
87
88         
89         if ($type !== false  &&  empty($pman->nodatabase)) {
90             
91             if(!empty($errors)){
92                 DB_DataObject::factory('Events')->writeEventLogExtra($errors);
93             }
94             // various codes that are acceptable.
95             // 
96             if (!preg_match('/^(ERROR|NOTICE|LOG)/', $type )) {
97                 $type = 'ERROR-' . $type;
98             }
99             
100             $this->addEvent($type, false, $str);
101             
102         }
103          
104         $cli = HTML_FlexyFramework::get()->cli;
105         if ($cli) {
106             exit(1); // cli --- exit code to stop shell execution if necessary.
107         }
108         
109         
110         if ($content_type == 'text/plain') {
111             header('Content-Disposition: attachment; filename="error.txt"');
112             header('Content-type: '. $content_type);
113             echo "ERROR: " .$str . "\n";
114             exit;
115         } 
116         
117      // log all errors!!!
118         
119         $retHTML = isset($_SERVER['CONTENT_TYPE']) && 
120                 preg_match('#multipart/form-data#i', $_SERVER['CONTENT_TYPE']);
121         
122         if ($retHTML){
123             if (isset($_REQUEST['returnHTML']) && $_REQUEST['returnHTML'] == 'NO') {
124                 $retHTML = false;
125             }
126         } else {
127             $retHTML = isset($_REQUEST['returnHTML']) && $_REQUEST['returnHTML'] !='NO';
128         }
129         
130         
131         if ($retHTML) {
132             header('Content-type: text/html');
133             echo "<HTML><HEAD></HEAD><BODY>";
134             echo  $this->jsencode(array(
135                     'success'=> false, 
136                     'errorMsg' => $str,
137                     'message' => $str, // compate with exeption / loadexception.
138
139                     'errors' => $errors ? $errors : true, // used by forms to flag errors.
140                     'authFailure' => !empty($errors['authFailure']),
141                 ), false);
142             echo "</BODY></HTML>";
143             exit;
144         }
145         
146         if (isset($_REQUEST['_debug'])) {
147             echo '<PRE>'.htmlspecialchars(print_r(array(
148                 'success'=> false, 
149                 'data'=> array(), 
150                 'errorMsg' => $str,
151                 'message' => $str, // compate with exeption / loadexception.
152                 'errors' => $errors ? $errors : true, // used by forms to flag errors.
153                 'authFailure' => !empty($errors['authFailure']),
154             ),true));
155             exit;
156                 
157         }
158         
159         echo $this->jsencode(array(
160             'success'=> false, 
161             'data'=> array(),
162             'code' => $type,
163             'errorMsg' => $str,
164             'message' => $str, // compate with exeption / loadexception.
165             'errors' => $errors ? $errors : true, // used by forms to flag errors.
166             'authFailure' => !empty($errors['authFailure']),
167         ),true);
168         
169         
170         exit;
171         
172     }
173     
174      
175    
176     
177     
178     
179     /**
180      * output data for grids or tree
181      * @ar {Array} ar Array of data
182      * @total {Number|false} total number of records (or false to return count(ar)
183      * @extra {Array} extra key value list of data to pass as extra data.
184      * 
185      */
186     function jdata($ar,$total=false, $extra=array(), $cachekey = false)
187     {
188         // should do mobile checking???
189         if ($total == false) {
190             $total = count($ar);
191         }
192         $extra=  $extra ? $extra : array();
193         
194         
195         $retHTML = isset($_SERVER['CONTENT_TYPE']) && 
196                 preg_match('#multipart/form-data#i', $_SERVER['CONTENT_TYPE']);
197         
198         if ($retHTML){
199             if (isset($_REQUEST['returnHTML']) && $_REQUEST['returnHTML'] == 'NO') {
200                 $retHTML = false;
201             }
202         } else {
203             $retHTML = isset($_REQUEST['returnHTML']) && $_REQUEST['returnHTML'] !='NO';
204         }
205         
206         if ($retHTML) {
207             
208             header('Content-type: text/html');
209             echo "<HTML><HEAD></HEAD><BODY><![CDATA[";
210             // encode html characters so they can be read..
211             echo  str_replace(array('<','>'), array('\u003c','\u003e'),
212                         $this->jsencode(array('success' =>  true, 'total'=> $total, 'data' => $ar) + $extra, false));
213             echo "]]></BODY></HTML>";
214             exit;
215         }
216         
217         
218         // see if trimming will help...
219         if (!empty($_REQUEST['_pman_short'])) {
220             $nar = array();
221             
222             foreach($ar as $as) {
223                 $add = array();
224                 foreach($as as $k=>$v) {
225                     if (is_string($v) && !strlen(trim($v))) {
226                         continue;
227                     }
228                     $add[$k] = $v;
229                 }
230                 $nar[] = $add;
231             }
232             $ar = $nar;
233               
234         }
235         
236       
237         $ret =  $this->jsencode(array('success' =>  true, 'total'=> $total, 'data' => $ar) + $extra,true);  
238         
239         if (!empty($cachekey)) {
240             
241             $fn = ini_get('session.save_path') . '/json-cache'.date('/Y/m/d').'.'. $cachekey . '.cache.json';
242             if (!file_exists(dirname($fn))) {
243                 mkdir(dirname($fn), 0777,true);
244             }
245             file_put_contents($fn, $ret);
246         }
247         
248         echo $ret;
249         exit;
250     }
251     
252     
253    
254     /** a daily cache **/
255     function jdataCache($cachekey)
256     {
257         $fn = ini_get('session.save_path') . '/json-cache'.date('/Y/m/d').'.'. $cachekey . '.cache.json';
258         if (file_exists($fn)) {
259             header('Content-type: application/json');
260             echo file_get_contents($fn);
261             exit;
262         }
263         return false;
264         
265     }
266     
267 }