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