1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
|
<?php
/** Rendering System
* ---
* this is the View part of the MVC framework.
* Decided not to make it a Class
***/
/** load template
* ---
* TODO:
* explain/document the difference between a template and a view
*
* TODO:
* Implementing the Render/View operation as a class, using the same-
* name methods with Laraver or CodeIgniter could be good idea;
* and get rid of if(!defined('VIEW_LOADED')) define('VIEW_LOADED',1);
*/
function load_template($template, $data) {
$file = VIEWS_DIRECTORY . $template . '.php';
if (file_exists($file)) {
if (!defined('VIEW_LOADED')) define('VIEW_LOADED', 1);
ob_start();
extract( sanitize_output($data) );
require( $file );
ob_flush();
} else if (!PRODUCTION) {
echo "<!-- view ". $file ." is missing -->";
}
}
/** parse_sections
* ---
* parse a group of views (sections)
* @param $sections: an array of sections
*
* each section group is an array with view, key and data properties
* + view: defines the view template/file
* + key: the variable name that view uses to parse data OR empty-string*
* * if key is an empty then $data should be an array (which
* includes all [variable-name:data] pairs utilized by the view)
* + data: holds the actual data
*/
function parse_sections($sections) {
foreach($sections as $sect) {
if ($sect['key'] == '') {
render_view( $sect['view'], $sect['data'] );
} else {
render_view( $sect['view'], [ $sect['key'] => $sect['data']] );
}
}
}
/** render function
* ---
* uses php's short-tag syntax for templating system
* extract data into template
* @param $view: view-template filename
* @param $data: data to embed into view-template
* @param $sanitize: of true then sanitize data.
* important NOTE: data is an array [key => value]
*/
function render_view($view, $data, $sanitize = false) {
$file = VIEWS_DIRECTORY . $view . '.php';
if (file_exists($file)) {
if (!defined('VIEW_LOADED')) define('VIEW_LOADED', 1);
extract( $sanitize ? sanitize_output($data) : $data );
require( $file );
} else if (!PRODUCTION) {
echo "<!-- view ". $file ." is missing -->";
}
}
/** render asap
* ---
* render_view then output code
* so that client will get html to render
* while server calculates next html
*/
function render_asap($view, $data, $sanitize = false) {
render_view($view, $data, $sanitize);
ob_flush();
}
/** render text
* ---
* This function simply echoes text
* with Content-Type and Cache Headers
* @param $data : the text to echo
* @param $cType : Content-Type header
* @param $ttl : cache-contol headers; if false response is not-cached; else (int) chache for $ttl seconds
*/
function render_text( $data, $contentType = 'text/html; charset=UTF-8', $ttl = false ) {
header('Content-Type: '. $contentType);
if ($ttl) {
$ts = gmdate("D, d M Y H:i:s", time() + $ttl) . " GMT";
header("Expires: {$ts}");
header("Pragma: cache");
header("Cache-Control: max-age={$ttl}");
} else {
$ts = gmdate("D, d M Y H:i:s") . " GMT";
header("Expires: {$ts}");
header("Last-Modified: {$ts}");
header("Pragma: no-cache");
header("Cache-Control: no-cache, must-revalidate");
}
echo htmlspecialchars($data);
}
/** reply_json
* ---
* transform a php-array to json and echo to client
* Can be used for API calls
*
* @param $data : the php array)
* @param $ttl : cache-contol headers; if false response is not-cached; else chache for $ttl seconds
*/
function reply_json( $data, $ttl = false ) {
header('Content-Type: application/json');
if ($ttl) {
$ts = gmdate("D, d M Y H:i:s", time() + $ttl) . " GMT";
header("Expires: {$ts}");
header("Pragma: cache");
header("Cache-Control: max-age={$ttl}");
} else {
$ts = gmdate("D, d M Y H:i:s") . " GMT";
header("Expires: {$ts}");
header("Last-Modified: {$ts}");
header("Pragma: no-cache");
header("Cache-Control: no-cache, must-revalidate");
}
echo json_encode($data, JSON_UNESCAPED_UNICODE);
}
// HELPER FUNCTIONS
// -----------------------------------------------------------------------------
/** link asset
* ---
* the function defines the assets (css or js)
* to be loaded on the client (creates the HTML)
* @param $type : type of asset [css|js]
* @param $assetIDs : an array of ('assetID' => 'paramaters')
*
* example calls:
* load_asset('css', ['main' => 'media="all"', 'filters' => 'media="all"']);
* load_asset( 'js', ['jquery' => '', 'lazyloader' => 'async']);
*/
function link_asset( $type, $assetIDs, $paramatres = '' ) {
$code = ""; // code to return
// make sure $assetIDs is array (for coding simplicity)
if (!is_array($assetIDs)) {
$assetIDs = [ $assetIDs ];
}
// check asset type and construct all asset inserts
switch ($type) {
case 'font':
foreach($assetIDs as $asset) {
$code .= "\n\t<link href='". FONTS_DIR . FONT_FILES[$asset] ."' as='font' type='font/woff2' {$paramatres}/>";
}
break;
case 'js':
foreach($assetIDs as $asset) {
$code .= "\n\t<script src='". JS_DIR . JS_LIBRARIES[$asset] ."' id='{$asset}' {$paramatres}></script>";
}
break;
case 'css':
default:
foreach($assetIDs as $asset) {
$code .= "\n\t<link rel='stylesheet' href='". CSS_DIR . CSS_FILES[$asset] ."' id='{$asset}' {$paramatres} />";
}
}
echo $code;
}
/** sanitize_output (recursive)
* ---
* Sanitizes data that are about to rendered
* (usually when render_view() is called).
* NOTE: mitigates XSS attachs
* @param $data: (array)
*/
function sanitize_output($data) {
//// // check https://stackoverflow.com/questions/2002710/php-how-to-perform-htmlspecialchar-on-an-array-of-arrays
//// $output = array_map("myFunc", $data);
global $secure;
$output = array();
foreach($data as $key => $val) {
if (is_string($val)) {
$output[$key] = htmlspecialchars(remove_invisible_characters($val));
} else if (is_array($val)) {
$output[$key] = sanitize_output($val);
} else {
$output[$key] = $val;
}
}
return $output;
}
/** remove_invisible_characters()
* ---
* @used by sanitize_output()
*/
function remove_invisible_characters($str, $url_encoded = TRUE)
{
$non_displayables = array();
// every control character except newline (dec 10),
// carriage return (dec 13) and horizontal tab (dec 09)
if ($url_encoded) {
$non_displayables[] = '/%0[0-8bcef]/i'; // url encoded 00-08, 11, 12, 14, 15
$non_displayables[] = '/%1[0-9a-f]/i'; // url encoded 16-31
$non_displayables[] = '/%7f/i'; // url encoded 127
}
$non_displayables[] = '/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+/S'; // 00-08, 11, 12, 14-31, 127
do {
$str = preg_replace($non_displayables, '', $str, -1, $count);
} while ($count);
return $str;
}
/** html
* ---
* outputs code as html
*
* @param $str (string)
* @return html5 (string)
*/
function html($str) {
if (!isset($str) || $str== null) return;
if (($str == '') || is_numeric($str)) return $str;
return htmlspecialchars_decode($str, ENT_QUOTES|ENT_HTML5);
}
/** set_headers
* ---
* set custom response-Headers
*
* @param $contentType
* @param $ttl: int or false)
* @param $more: array of (content-type => content-value) pairs
*/
function set_headers($contentType = 'text/html; charset=UTF-8', $ttl = false, $more = [] ) {
// handle common content-type shorcuts
switch ($contentType) {
case 'text':
case 'html':
$contentType = 'text/html; charset=UTF-8';
break;
case 'json':
$contentType = 'application/json; charset=utf-8';
break;
case 'js':
$contentType = 'application/javascript; charset=utf-8';
break;
case 'css':
$contentType = 'text/css';
break;
default:
// $contentType stays as-is
break;
}
// send headers
header('Content-Type: '. $contentType);
if ($ttl) {
$ts = gmdate("D, d M Y H:i:s", time() + $ttl) . " GMT";
header("Expires: {$ts}");
header("Pragma: cache");
header("Cache-Control: max-age={$ttl}");
} else {
$ts = gmdate("D, d M Y H:i:s") . " GMT";
header("Expires: {$ts}");
header("Last-Modified: {$ts}");
header("Pragma: no-cache");
header("Cache-Control: no-cache, must-revalidate");
}
// send more headers
if ($more != []) {
foreach($more as $header => $value) {
header($header .': '. $value);
}
}
}
|