3d7e2403ed8f5d088caeda2adb957933018f409c
[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     function jdata($ar,$total=false, $extra=array(), $cachekey = false)
179     {
180         // should do mobile checking???
181         if ($total == false) {
182             $total = count($ar);
183         }
184         $extra=  $extra ? $extra : array();
185         require_once 'Services/JSON.php';
186         $json = new Services_JSON();
187         
188         $retHTML = isset($_SERVER['CONTENT_TYPE']) && 
189                 preg_match('#multipart/form-data#i', $_SERVER['CONTENT_TYPE']);
190         
191         if ($retHTML){
192             if (isset($_REQUEST['returnHTML']) && $_REQUEST['returnHTML'] == 'NO') {
193                 $retHTML = false;
194             }
195         } else {
196             $retHTML = isset($_REQUEST['returnHTML']) && $_REQUEST['returnHTML'] !='NO';
197         }
198         
199         if ($retHTML) {
200             
201             header('Content-type: text/html');
202             echo "<HTML><HEAD></HEAD><BODY>";
203             // encode html characters so they can be read..
204             echo  str_replace(array('<','>'), array('\u003c','\u003e'),
205                         $json->encodeUnsafe(array('success' =>  true, 'total'=> $total, 'data' => $ar) + $extra));
206             echo "</BODY></HTML>";
207             exit;
208         }
209         
210         
211         // see if trimming will help...
212         if (!empty($_REQUEST['_pman_short'])) {
213             $nar = array();
214             
215             foreach($ar as $as) {
216                 $add = array();
217                 foreach($as as $k=>$v) {
218                     if (is_string($v) && !strlen(trim($v))) {
219                         continue;
220                     }
221                     $add[$k] = $v;
222                 }
223                 $nar[] = $add;
224             }
225             $ar = $nar;
226               
227         }
228         
229       
230         $ret =  $json->encode(array('success' =>  true, 'total'=> $total, 'data' => $ar) + $extra);  
231         
232         if (!empty($cachekey)) {
233             
234             $fn = ini_get('session.save_path') . '/json-cache'.date('/Y/m/d').'.'. $cachekey . '.cache.json';
235             if (!file_exists(dirname($fn))) {
236                 mkdir(dirname($fn), 0777,true);
237             }
238             file_put_contents($fn, $ret);
239         }
240         echo $ret;
241         exit;
242     }
243     
244     /** a daily cache **/
245     function jdataCache($cachekey)
246     {
247         $fn = ini_get('session.save_path') . '/json-cache'.date('/Y/m/d').'.'. $cachekey . '.cache.json';
248         if (file_exists($fn)) {
249             header('Content-type: application/json');
250             echo file_get_contents($fn);
251             exit;
252         }
253         return false;
254         
255     }
256 }