<?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();
?>