fnando / voodoo

Another microframework for PHP

This URL has Read+Write access

voodoo / voodoo.php
100644 788 lines (668 sloc) 19.979 kb
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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
<?php
/**
* The framework options holder
*/
$VOODOO_OPTIONS = array();
 
// disable magic quote runtime
set_magic_quotes_runtime(0);
 
/**
* Set a framework option
* Available options:
* assets: path to the assets directory (it holds javascript, style and image files)
* base_path: great for using within subfolders; should be a regular expression without the trailing slash
* debug: enables debug support
* encoding: set the content type encoding; defaults to UTF-8
* gzip: enables gzip support
* log_file: specify the debug log file; debug option should be enabled
* views_directory: specify the views directory; is a view directory relative to the voodoo.php file
* @param string $option The option name
* @param mixed $value The option value
* @return void
*/
function set($option, $value) {
    global $VOODOO_OPTIONS;
    $VOODOO_OPTIONS[$option] = $value;
}
 
/**
* Get a framework option
* Check the set method to view the available options
* @param string $option The option name
* @return mixed
*/
function option($option) {
    global $VOODOO_OPTIONS;
    
    return $VOODOO_OPTIONS[$option];
}
 
/**
* Set a new HTTP Header
* Check the set method to view the available options
* @param string $name The header name
* @param string $value The header value
* @return void
*/
function http_header($name, $value=null) {
    if ($value) {
        header($name . ':' . $value);
    } else {
        header("HTTP/1.1 {$name}");
    }
}
 
/**
* Render the views/404.php file without any layout. Set headers for page not found.
* @return void
* @uses http_header, status, call_before, render, call_after
*/
function notfound() {
    http_header("404 Not Found");
    status("404 Not Found");
    render("404", array(), null);
    echo option("content");
    die;
}
 
/**
* Set the content type header.
* @param string $type The content type header
* @return void
* @uses http_header
*/
function content_type($type="text/html") {
    if (strpos($type, "charset") === false) {
        $type .= "; charset=" . option("encoding");
    }
    
    set("content_type", $type);
    http_header("Content-Type", $type);
}
 
/**
* Set the status header
* @param string $status
* @return void
* @uses http_header
*/
function status($status) {
    http_header("Status", $status);
}
 
/**
* Redirect to the specified $url
* @param string $url
* @param string $status
* @return void
* @uses http_header, status
*/
function redirect($url, $status="301 Moved Permanently") {
    if ($status) {
        http_header($status);
        status($status);
    }
     
    http_header("Location", $url);
    die;
}
 
/**
* Verify if $func is a function and call it if so
* @param $func A function name to be called
* @return void
*/
function call_func($func) {
    if ($func) {
        if (function_exists($func)) {
            call_user_func($func);
        }
    }
}
 
/**
* Merges the GET and POST variables.
* POST will override GET variables with the same name.
* @return array
*/
function params($name=null) {
    $params = array_merge($_GET, $_POST);
        
    if ($name) {
        return $params[$name];
    } else {
        return $params;
    }
}
 
/**
* Get the request method.
* If is a POST request and $param["_method"] is a valid verb,
* use it as the current request method (browser tweak).
* @return string A HTTP verb
* @uses params
*/
function request_method() {
    $params = params();
    $request_method = $_SERVER["REQUEST_METHOD"];
    $method_param = $params["_method"];
    
    if (in_array($method_param, array("GET", "POST", "PUT", "DELETE", "HEAD")) && $request_method == "POST") {
        return $method_param;
    } else {
        return $request_method;
    }
}
 
function detect_route($request_path, $method, $path, $options) {
    $request_method = request_method();
    $base_path = preg_replace("/\/$/", "", option("base_path"));
    
    // remove slashes from beginning and end
    $path = preg_replace("/^\//", "", $path);
    $path = preg_replace("/\/$/", "", $path);
    
    // force requirements to be an array
    $requirements = (array)$options["requirements"];
    
    // build the whole url
    $url = "{$base_path}/{$path}";
    
    // escape special characters and build regex
    $regex = str_replace("/", "\\/", $url);
    $regex = str_replace(".", "\\.", $regex);
    $regex = preg_replace("/(:[0-9a-z_]+)/sim", "([^\/]+)", $regex);
    $regex = "/^{$regex}\/?$/sm";
    
    // retrieve all named params
    preg_match_all("/(:[a-z0-9_]+)/sim", $url, $matches);
    $names = $matches[1];
    
    // check if this is correct route and set the values array
    $recognized = preg_match_all($regex, $request_path, $matches) && $request_method == strtoupper($method);
    $values = (array)$matches[1];
    
    // decode all retrieved values
    foreach($values as $index => $value) {
        $values[$index] = urldecode($value);
    }
    
    if (!$recognized) {
        return false;
    } else if (empty($names)) {
        return true;
    } else {
        foreach($names as $index => $name) {
            $name = str_replace(":", "", $name);
            $names[$index] = $name;
            
            if (array_key_exists($name, $requirements)) {
                $requirement = $requirements[$name];
                
                if ($requirement) {
                    if (!preg_match($requirement, (string)$values[$index])) {
                        return false;
                    }
                }
            }
            
            $_GET[$name] = $values[$index];
        }
        
        return array_combine($names, $values);
    }
}
 
/**
* Specify a new route.
* There are helpers for all verbs, so you probably won't call this function by yourself.
* @param string $re The route regex
* @param string $func The function that will be dispatched if is valid route
* @param string $method The request method that will be accepted
* @param array $options Specify before and after filters
* @return void
* @uses call_before, call_after, call_func, request_method, detect_route
*/
function route($path, $func, $method, $options=array()) {
    $uri = parse_url($_SERVER["REQUEST_URI"]);
    $request_path = $uri["path"];
    $detected = detect_route($request_path, $method, $path, $options);
    
    if ($detected) {
        call_func("before");
        call_func($options["before"]);
        
        call_user_func_array($func, array($detected));
        
        call_func("after");
        call_func($options["after"]);
        
        if (option("gzip")) {
            /* From the documentation:
Before ob_gzhandler() actually sends compressed data, it determines what type of content
encoding the browser will accept ("gzip", "deflate" or none at all) and will return its
output accordingly. All browsers are supported since it's up to the browser to send the
correct header saying that it accepts compressed web pages. If a browser doesn't support
compressed pages this function returns FALSE. */
            ob_start("ob_gzhandler");
        }
        
        if (option("environment") != "test") {
            echo option("content");
        }
        
        // if you don't want to die after rendering and dispatching
        // callbacks, set $options["keep_alive"] to true
        if (!$options["keep_alive"] && option("environment") != "test") {
            die;
        }
    }
}
 
/**
* Specify a new GET route.
* @see route
* @return void
* @uses route
*/
function get($re, $func, $options=array()) {
    route($re, $func, "GET", $options);
}
 
/**
* Specify a new POST route.
* @see route
* @return void
* @uses route
*/
function post($re, $func, $options=array()) {
    route($re, $func, "POST", $options);
}
 
/**
* Specify a new PUT route.
* @see route
* @return void
* @uses route
*/
function put($re, $func, $options=array()) {
    route($re, $func, "PUT", $options);
}
 
/**
* Specify a new DELETE route.
* @see route
* @return void
* @uses route
*/
function delete($re, $func, $options=array()) {
    route($re, $func, "DELETE", $options);
}
 
/**
* Specify a new HEAD route.
* @see route
* @return void
* @uses route
*/
function head($re, $func, $options=array()) {
    route($re, $func, "HEAD", $options);
}
 
/**
* Render a view. It dies after displaying the content.
* @param string $filename The file that should be fetched, without the extension.
* @param array $vars The variables that will be sent to the view.
* @param string $layout The layout file that should be fetched, without the extension.
* @return void
* @uses fetch
*/
function render($filename, $vars=array(), $layout="layout") {
    if (is_valid_format()) {
        set("variables", $filename);
        $content = respond_to();
    } else {
        set("variables", $vars);
        $content = fetch($filename, $vars);
        
        if ($layout) {
            $content = fetch($layout, array_merge($vars, array("content" => $content)));
        }
    }
    
    set("content", $content);
}
 
/**
* Render option("variables") accordingly to the request format.
*
* @return string
* @uses option
*/
function respond_to() {
    switch (params("format")) {
        case "json":
            return json_encode(option("variables"));
            break;
        
        default:
            return option("variables");
    }
}
 
/**
* Verify is a valid format.
*
* @return bool
* @uses params
*/
function is_valid_format() {
    $formats = array("json");
    return in_array(params("format"), $formats);
}
 
/**
* Fetch the specified template file and send variables to it.
* @param string $filename The file that should be fetched, without the extension.
* @param array $vars The variables that will be sent to the view.
* @return string
* @uses option
*/
function fetch($filename, $vars=array()) {
    ob_start();
    extract($vars, EXTR_REFS | EXTR_OVERWRITE);
    
    $path = option("views_directory") . "/{$filename}.php";
    
    require_once $path;
    
    $content = ob_get_contents();
    ob_end_clean();
    
    debug("fetching {$path}... " . ($content? "has content" : "is empty"));
    
    return $content;
}
 
/**
* Write messages to voodoo.log if $VOODOO_OPTIONS["debug"] is true.
* @param string $message The file that should be logged.
* @return void
* @uses option
*/
function debug($message) {
    if (!option("debug")) {
        return;
    }
    
    $date = date("Y-m-d H:i:s");
    $message = "[{$date}] {$message}\n";
    
    file_put_contents(option("log_file"), $message, FILE_APPEND);
}
 
/**
* Set a new flash message.
* @param string $name The flash message key name.
* @param string $message
* @return string
*/
function flash($name, $message=null) {
    if ($message) {
        $_SESSION["flash"][$name] = $message;
    } else {
        $message = $_SESSION["flash"][$name];
        unset($_SESSION["flash"][$name]);
        return $message;
    }
}
 
/**
* Retrieve all flash messages
* @return array
*/
function flash_messages() {
    $messages = (array)$_SESSION["flash"];
    $_SESSION["flash"] = array();
    return $messages;
}
 
/**
* A utility function for escaping HTML tag characters.
* @param string $html
* @return string
*/
function h($html) {
    return preg_replace('/([&"><])/e', 'htmlentities("$1")', $html);
}
 
/**
* A utility function for creating HTML tags.
* @param string $tag
* @param string $content The content that will be wrapped with the tag
* @param array $attrs The tag attributes
* @param bool $opened Specify if will be an opened tag like <br/>
* @return string
* @uses html_attrs
*/
function tag($tag, $content="", $attrs=array(), $opened=false) {
    $attrs = html_attrs($attrs);
    
    if ($attrs) {
        $attrs = " " . $attrs;
    }
    
    if ($opened) {
        return "<{$tag}{$attrs}/>";
    } else {
        return "<{$tag}{$attrs}>{$content}</{$tag}>";
    }
}
 
/**
* A utility function for creating opened HTML tags like <br/>.
* @param string $tag
* @param array $attrs The tag attributes
* @return string
* @uses tag
*/
function opened_tag($tag, $attrs=array()) {
    return tag($tag, null, $attrs, true);
}
 
/**
* A utility function for creating HTML tags.
* @param array $attrs The tag attributes
* @return string
* @uses h
* @access private
*/
function html_attrs($attrs) {
    $h = array();
    
    foreach ($attrs as $name => $value) {
        $h[] = sprintf('%s="%s"', $name, h($value));
    }
    
    return join(" ", $h);
}
 
/**
* Build the path for an asset (image, javascript or stylesheet file, etc.)
* @param string $path The path to the asset
* @param string $dir The directory inside asset path
* @return string
* @uses option
*/
function asset_path($asset, $dir=null) {
    if (!preg_match("/^(\/|https?)/i", $asset)) {
        
        if (option("base_path")) {
            $path = option("base_path");
        }
        
        $path .= option("assets");
        
        if ($dir) {
            $path .= "/{$dir}";
        }
        
        $path .= "/{$asset}";
    } else {
        $path = $asset;
    }
    
    return $path;
}
 
/**
* Build an image tag
* @param string $path The path to the image
* @param array $attrs The image attributes
* @return string
* @uses asset_path, opened_tag
*/
function img($path, $attrs=array()) {
    $src = asset_path($path, "images");
    $defaults = array("src" => $src, "alt" => "");
    $attrs = array_merge($defaults, $attrs);
    
    return opened_tag("img", $attrs);
}
 
/**
* Build an link stylesheet tag
* @param string $path The path to the stylesheet
* @param array $attrs The stylesheet attributes
* @return string
* @uses asset_path, opened_tag
*/
function css($path, $attrs=array()) {
    if (!preg_match("/\.css$/i", $path)) {
        $path .= ".css";
    }
    
    $href = asset_path($path, "stylesheets");
    $defaults = array("href" => $href, "rel" => "stylesheet", "type" => "text/css", "media" => "screen");
    $attrs = array_merge($defaults, $attrs);
    
    return opened_tag("link", $attrs);
}
 
/**
* Build an javascript tag
* @param string $path The path to the stylesheet
* @param array $attrs The stylesheet attributes
* @return string
* @uses asset_path, tag
*/
function js($path, $attrs=array()) {
    if (!preg_match("/\.js$/i", $path)) {
        $path .= ".js";
    }
    
    $src = asset_path($path, "javascripts");
    $defaults = array("src" => $src, "type" => "text/javascript");
    $attrs = array_merge($defaults, $attrs);
    
    return tag("script", null, $attrs);
}
 
/**
* Return an URL for this stylesheet bundle.
* If files are not specified, load all in arbitrary order.
* @param string $file1..$fileN The stylesheet name
* @return string
* @author Nando Vieira
**/
function css_bundle () {
    $files = func_get_args();
    
    if (func_num_args() == 0) {
        $files = glob(option("assets_directory") . "/stylesheets/*.css");
        
        foreach ($files as $index => $file) {
            $files[$index] = basename($file);
        }
    }
    
    foreach ($files as $index => $file) {
        $files[$index] = preg_replace("/\.css$/i", "", $file);
    }
    
    $path = "bundle.css?n=" . join(",", $files);
    
    $href = asset_path($path, "stylesheets");
    $attrs = array("href" => $href, "rel" => "stylesheet", "type" => "text/css", "media" => "screen");
    return opened_tag("link", $attrs);
}
 
/**
* Return an URL for this javascript bundle.
* If files are not specified, load all in arbitrary order.
* @param string $file1..$fileN The javascript name
* @return string
* @author Nando Vieira
**/
function js_bundle () {
    $files = func_get_args();
    
    if (func_num_args() == 0) {
        $files = glob(option("assets_directory") . "/javascripts/*.js");
        
        foreach ($files as $index => $file) {
            $files[$index] = basename($file);
        }
    }
    
    foreach ($files as $index => $file) {
        $files[$index] = preg_replace("/\.js$/i", "", $file);
    }
    
    $path = "bundle.js?n=" . join(",", $files);
    
    $src = asset_path($path, "javascripts");
    $attrs = array("src" => $src, "type" => "text/javascript");
    return tag("script", null, $attrs);
}
 
/**
* Retrieve the specified param and if it's null, return the default value
* @param string $name
* @param mixed $default
* @return mixed
* @uses params
*/
function param_or_default($name, $default) {
    if (params($name)) {
        return params($name);
    } else {
        return $default;
    }
}
 
/**
* Build an URL considering the base path. It also escapes each param value.
* To build an URL with multiple parts, just call url_for passing several
* arguments.
*
* @param string $param The path to the stylesheet
* @return string
* @uses option
*/
function url_for() {
    $args = func_get_args();
    
    foreach($args as $index => $arg) {
        $args[$index] = rawurlencode((string)$arg);
    }
    
    $base = preg_replace("/\/$/", "", (string)option("base_path"));
    
    return $base . "/" . join("/", $args);
}
 
/**
* Build a link tag using url_for helper
* @param string $title
* @param mixed $path When is an array, calls url_for
* @param array $attrs
* @return string
* @uses url_for, tag
*/
function link_to($title, $path, $attrs=array()) {
    if (is_array($path)) {
        $path = call_user_func_array("url_for", $path);
    }
    
    $attrs["href"] = $path;
    
    return tag("a", $title, $attrs);
}
 
/**
* Remove quotes
*
* @param array $array
* @return array
* @author Nando Vieira
**/
function strip_gpc_quotes ($array) {
    foreach ($array as $index => $item) {
        $array[$index] = is_array($item)? strip_gpc_quotes($item) : stripslashes($item);
    }
    
    return $array;
}
 
/**
* Render all stylesheets as a bundle
*
* @return void
* @author Nando Vieira
**/
function render_stylesheet_bundle () {
    render_bundle("stylesheets", "css", "text/css");
}
 
/**
* Render all javascripts as a bundle
*
* @return void
* @author Nando Vieira
**/
function render_javascript_bundle () {
    render_bundle("javascripts", "js", "text/javascript");
}
 
/**
* Render the specified bundle
*
* @return void
* @author Nando Vieira
**/
function render_bundle ($directory, $extension, $content_type) {
    $names = params("n");
    $content = "";
    
    debug("render bundle with [{$directory}, {$extension}, {$content_type}] => '{$names}'");
    
    if ($names) {
        $names = split(",", $names);
        
        foreach ($names as $name) {
            $path = option("assets_directory") . "/{$directory}/{$name}.{$extension}";
            
            if (is_file($path)) {
                $content .= file_get_contents($path);
            }
        }
    }
    
    set("content", $content);
    content_type($content_type);
}
 
/**
* Set default routes for bundles
* @return void
* @author Nando Vieira
**/
function use_bundle_routes() {
    get("/assets/javascripts/bundle.js", "render_javascript_bundle");
    get("/assets/stylesheets/bundle.css", "render_stylesheet_bundle");
}
 
// strip slashes from $_GET and $_POST variables
if (get_magic_quotes_gpc()) {
    $_GET = strip_gpc_quotes($_GET);
    $_POST = strip_gpc_quotes($_POST);
}
 
// set the root directory
$trace = debug_backtrace();
set("voodoo_root", dirname($trace[0]["file"]));
define("VOODOO_ROOT", option("voodoo_root"));
 
// set the default views directory
set("views_directory", VOODOO_ROOT . "/views");
 
// set the default log file
set("log_file", VOODOO_ROOT . "/voodoo.log");
 
// enables gzip
set("gzip", true);
 
// set the default assets path
set("assets", "/assets");
 
// set the default assets directory
set("assets_directory", VOODOO_ROOT . "/assets");
 
// set encoding
set("encoding", "UTF-8");
 
// set default routing
use_bundle_routes();
?>