Example #1
0
/**
 * Reads a file
 * <pre>
 *  * file : path or URI of the file to read (however reading from another website is not recommended for performance reasons)
 *  * assign : if set, the file will be saved in this variable instead of being output
 * </pre>
 * This software is provided 'as-is', without any express or implied warranty.
 * In no event will the authors be held liable for any damages arising from the use of this software.
 *
 * @author     Jordi Boggiano <*****@*****.**>
 * @copyright  Copyright (c) 2008, Jordi Boggiano
 * @license    http://dwoo.org/LICENSE   Modified BSD License
 * @link       http://dwoo.org/
 * @version    1.1.0
 * @date       2009-07-18
 * @package    Dwoo
 */
function Dwoo_Plugin_fetch(Dwoo_Core $dwoo, $file, $assign = null)
{
    if ($file === '') {
        return;
    }
    if ($policy = $dwoo->getSecurityPolicy()) {
        while (true) {
            if (preg_match('{^([a-z]+?)://}i', $file)) {
                return $dwoo->triggerError('The security policy prevents you to read files from external sources.', E_USER_WARNING);
            }
            $file = realpath($file);
            $dirs = $policy->getAllowedDirectories();
            foreach ($dirs as $dir => $dummy) {
                if (strpos($file, $dir) === 0) {
                    break 2;
                }
            }
            return $dwoo->triggerError('The security policy prevents you to read <em>' . $file . '</em>', E_USER_WARNING);
        }
    }
    $file = str_replace(array("\t", "\n", "\r"), array('\\t', '\\n', '\\r'), $file);
    $out = file_get_contents($file);
    if ($assign === null) {
        return $out;
    }
    $dwoo->assignInScope($out, $assign);
}
Example #2
0
/**
 * Evaluates the given string as if it was a template
 *
 * Although this plugin is kind of optimized and will
 * not recompile your string each time, it is still not
 * a good practice to use it. If you want to have templates
 * stored in a database or something you should probably use
 * the Dwoo_Template_String class or make another class that
 * extends it
 * <pre>
 *  * var : the string to use as a template
 *  * assign : if set, the output of the template will be saved in this variable instead of being output
 * </pre>
 * This software is provided 'as-is', without any express or implied warranty.
 * In no event will the authors be held liable for any damages arising from the use of this software.
 *
 * @author     Jordi Boggiano <*****@*****.**>
 * @copyright  Copyright (c) 2008, Jordi Boggiano
 * @license    http://dwoo.org/LICENSE   Modified BSD License
 * @link       http://dwoo.org/
 * @version    1.0.0
 * @date       2008-10-23
 * @package    Dwoo
 */
function Dwoo_Plugin_eval(Dwoo_Core $dwoo, $var, $assign = null)
{
    if ($var == '') {
        return;
    }
    $tpl = new Dwoo_Template_String($var);
    $clone = clone $dwoo;
    $out = $clone->get($tpl, $dwoo->readVar('_parent'));
    if ($assign !== null) {
        $dwoo->assignInScope($out, $assign);
    } else {
        return $out;
    }
}
Example #3
0
function Dwoo_Plugin_rss(Dwoo_Core $dwoo, $feed, $assign = 'rss_items', $limit = 5, $cacheTime = 60)
{
    $cacheKey = 'rss:' . $feed;
    if (false === ($rss = Cache::fetch($cacheKey))) {
        $rss = new RssReader();
        $rss->load($feed);
        Cache::store($cacheKey, $rss, $cacheTime);
    }
    if ($limit) {
        $dwoo->assignInScope(array_slice($rss->getItems(), 0, $limit), $assign);
    } else {
        $dwoo->assignInScope($rss->getItems(), $assign);
    }
    return '';
}
Example #4
0
/**
 * Reverses a string or an array
 * <pre>
 *  * value : the string or array to reverse
 *  * preserve_keys : if value is an array and this is true, then the array keys are left intact
 * </pre>
 * This software is provided 'as-is', without any express or implied warranty.
 * In no event will the authors be held liable for any damages arising from the use of this software.
 *
 * @author     Jordi Boggiano <*****@*****.**>
 * @copyright  Copyright (c) 2008, Jordi Boggiano
 * @license    http://dwoo.org/LICENSE   Modified BSD License
 * @link       http://dwoo.org/
 * @version    1.0.0
 * @date       2008-10-23
 * @package    Dwoo
 */
function Dwoo_Plugin_reverse(Dwoo_Core $dwoo, $value, $preserve_keys = false)
{
    if (is_array($value)) {
        return array_reverse($value, $preserve_keys);
    } elseif (($charset = $dwoo->getCharset()) === 'iso-8859-1') {
        return strrev((string) $value);
    } else {
        $strlen = mb_strlen($value);
        $out = '';
        while ($strlen--) {
            $out .= mb_substr($value, $strlen, 1, $charset);
        }
        return $out;
    }
}
Example #5
0
/**
 * Inserts another template into the current one
 * <pre>
 *  * file : the resource name of the template
 *  * cache_time : cache length in seconds
 *  * cache_id : cache identifier for the included template
 *  * compile_id : compilation identifier for the included template
 *  * data : data to feed into the included template, it can be any array and will default to $_root (the current data)
 *  * assign : if set, the output of the included template will be saved in this variable instead of being output
 *  * rest : any additional parameter/value provided will be added to the data array
 * </pre>
 * This software is provided 'as-is', without any express or implied warranty.
 * In no event will the authors be held liable for any damages arising from the use of this software.
 *
 * @author     Jordi Boggiano <*****@*****.**>
 * @copyright  Copyright (c) 2008, Jordi Boggiano
 * @license    http://dwoo.org/LICENSE   Modified BSD License
 * @link       http://dwoo.org/
 * @version    1.1.0
 * @date       2009-07-18
 * @package    Dwoo
 */
function Dwoo_Plugin_include(Dwoo_Core $dwoo, $file, $cache_time = null, $cache_id = null, $compile_id = null, $data = '_root', $assign = null, array $rest = array())
{
    if ($file === '') {
        return;
    }
    if (preg_match('#^([a-z]{2,}):(.*)$#i', $file, $m)) {
        // resource:identifier given, extract them
        $resource = $m[1];
        $identifier = $m[2];
    } else {
        // get the current template's resource
        $resource = $dwoo->getTemplate()->getResourceName();
        $identifier = $file;
    }
    try {
        $include = $dwoo->templateFactory($resource, $identifier, $cache_time, $cache_id, $compile_id);
    } catch (Dwoo_Security_Exception $e) {
        return $dwoo->triggerError('Include : Security restriction : ' . $e->getMessage(), E_USER_WARNING);
    } catch (Dwoo_Exception $e) {
        return $dwoo->triggerError('Include : ' . $e->getMessage(), E_USER_WARNING);
    }
    if ($include === null) {
        return $dwoo->triggerError('Include : Resource "' . $resource . ':' . $identifier . '" not found.', E_USER_WARNING);
    } elseif ($include === false) {
        return $dwoo->triggerError('Include : Resource "' . $resource . '" does not support includes.', E_USER_WARNING);
    }
    if (is_string($data)) {
        $vars = $dwoo->readVar($data);
    } else {
        $vars = $data;
    }
    if (count($rest)) {
        $vars = $rest + $vars;
    }
    $clone = clone $dwoo;
    $out = $clone->get($include, $vars);
    if ($assign !== null) {
        $dwoo->assignInScope($out, $assign);
    }
    foreach ($clone->getReturnValues() as $name => $value) {
        $dwoo->assignInScope($value, $name);
    }
    if ($assign === null) {
        return $out;
    }
}
Example #6
0
/**
 * Capitalizes the first letter of each word
 * <pre>
 *  * value : the string to capitalize
 *  * numwords : if true, the words containing numbers are capitalized as well
 * </pre>
 * This software is provided 'as-is', without any express or implied warranty.
 * In no event will the authors be held liable for any damages arising from the use of this software.
 *
 * @author     Jordi Boggiano <*****@*****.**>
 * @copyright  Copyright (c) 2008, Jordi Boggiano
 * @license    http://dwoo.org/LICENSE   Modified BSD License
 * @link       http://dwoo.org/
 * @version    1.1.0
 * @date       2009-07-18
 * @package    Dwoo
 */
function Dwoo_Plugin_capitalize(Dwoo_Core $dwoo, $value, $numwords = false)
{
    if ($numwords || preg_match('#^[^0-9]+$#', $value)) {
        return mb_convert_case((string) $value, MB_CASE_TITLE, $dwoo->getCharset());
    } else {
        $bits = explode(' ', (string) $value);
        $out = '';
        while (list(, $v) = each($bits)) {
            if (preg_match('#^[^0-9]+$#', $v)) {
                $out .= ' ' . mb_convert_case($v, MB_CASE_TITLE, $dwoo->getCharset());
            } else {
                $out .= ' ' . $v;
            }
        }
        return substr($out, 1);
    }
}
Example #7
0
function Dwoo_Plugin_twitter(Dwoo_Core $dwoo, $username = false, $query = false, $assign = 'tweets', $count = 5, $cacheTime = 60)
{
    if ($query) {
        $cacheKey = sprintf('twitter?query=%s', urlencode($query));
        $feedURL = sprintf('http://search.twitter.com/search.json?q=%s', urlencode($query));
        $twitterData = Twitter::getFeedData($feedURL, $cacheKey, $cacheTime);
        $results = $twitterData['results'];
    } elseif ($username) {
        $cacheKey = sprintf('twitter?username=%s', urlencode($username));
        $feedURL = sprintf('http://api.twitter.com/1/statuses/user_timeline/%s.json', urlencode($username));
        $twitterData = Twitter::getFeedData($feedURL, $cacheKey, $cacheTime);
        $results = $twitterData;
    }
    if (!empty($results) && is_array($results)) {
        $dwoo->assignInScope(array_slice($results, 0, $count), $assign);
    } else {
        $dwoo->assignInScope(array(), $assign);
    }
    return '';
}
Example #8
0
    public function testHtmlFormat()
    {
        $tpl = new Dwoo_Template_String("<html><body><div><p>a<em>b</em>c<hr /></p><textarea>a\n  b</textarea></div></body><html>");
        $tpl->forceCompilation();
        $dwoo = new Dwoo_Core(DWOO_COMPILE_DIR, DWOO_CACHE_DIR);
        $dwoo->addFilter('html_format', true);
        $this->assertEquals(str_replace("\r", '', <<<SNIPPET

<html>
<body>
\t<div>
\t\t<p>
\t\t\ta<em>b</em>c
\t\t\t<hr />
\t\t</p><textarea>a
  b</textarea>
\t</div>
</body>
<html>
SNIPPET
), $dwoo->get($tpl, array(), $this->compiler));
    }
Example #9
0
/**
 * Applies various escaping schemes on the given string
 * <pre>
 *  * value : the string to process
 *  * format : escaping format to use, valid formats are : html, htmlall, url, urlpathinfo, quotes, hex, hexentity, javascript and mail
 *  * charset : character set to use for the conversion (applies to some formats only), defaults to the current Dwoo charset
 * </pre>
 * This software is provided 'as-is', without any express or implied warranty.
 * In no event will the authors be held liable for any damages arising from the use of this software.
 *
 * @author     Jordi Boggiano <*****@*****.**>
 * @copyright  Copyright (c) 2008, Jordi Boggiano
 * @license    http://dwoo.org/LICENSE   Modified BSD License
 * @link       http://dwoo.org/
 * @version    1.0.0
 * @date       2008-10-23
 * @package    Dwoo
 */
function Dwoo_Plugin_escape(Dwoo_Core $dwoo, $value = '', $format = 'html', $charset = null)
{
    if ($charset === null) {
        $charset = $dwoo->getCharset();
    }
    switch ($format) {
        case 'html':
            return htmlspecialchars((string) $value, ENT_QUOTES, $charset);
        case 'htmlall':
            return htmlentities((string) $value, ENT_QUOTES, $charset);
        case 'url':
            return rawurlencode((string) $value);
        case 'urlpathinfo':
            return str_replace('%2F', '/', rawurlencode((string) $value));
        case 'quotes':
            return preg_replace("#(?<!\\\\)'#", "\\'", (string) $value);
        case 'hex':
            $out = '';
            $cnt = strlen((string) $value);
            for ($i = 0; $i < $cnt; $i++) {
                $out .= '%' . bin2hex((string) $value[$i]);
            }
            return $out;
        case 'hexentity':
            $out = '';
            $cnt = strlen((string) $value);
            for ($i = 0; $i < $cnt; $i++) {
                $out .= '&#x' . bin2hex((string) $value[$i]) . ';';
            }
            return $out;
        case 'javascript':
            return strtr((string) $value, array('\\' => '\\\\', "'" => "\\'", '"' => '\\"', "\r" => '\\r', "\n" => '\\n', '</' => '<\\/'));
        case 'mail':
            return str_replace(array('@', '.'), array('&nbsp;(AT)&nbsp;', '&nbsp;(DOT)&nbsp;'), (string) $value);
        default:
            return $dwoo->triggerError('Escape\'s format argument must be one of : html, htmlall, url, urlpathinfo, hex, hexentity, javascript or mail, "' . $format . '" given.', E_USER_WARNING);
    }
}
 /**
  * Constructor for the DwooTemplate engine
  *
  */
 public function __construct()
 {
     // Call parents constructor
     parent::__construct();
     // Set the config settings
     $this->initialize();
     // Assign some defaults to dwoo
     $CI = get_instance();
     $this->dwoo_data = new Dwoo_Data();
     $this->dwoo_data->js_files = array();
     $this->dwoo_data->css_files = array();
     $this->dwoo_data->CI = $CI;
     $this->dwoo_data->site_url = $CI->config->site_url();
     // so we can get the full path to CI easily
     $this->dwoo_data->uniqid = uniqid();
     $this->dwoo_data->timestamp = mktime();
     log_message('debug', "Dwoo Template Class Initialized");
 }
Example #11
0
 protected function initRuntimeVars(\Dwoo_ITemplate $tpl)
 {
     // call parent
     parent::initRuntimeVars($tpl);
     // set site information
     $this->globals['Site'] = array('title' => Site::$title, 'degredations' => Site::getConfig('degredations'));
     // add magic globals
     foreach (self::$magicGlobals as $name) {
         if (isset($GLOBALS[$name])) {
             $this->globals[$name] =& $GLOBALS[$name];
         } else {
             $this->globals[$name] = false;
         }
     }
     // set user
     $this->globals['User'] = !empty($GLOBALS['Session']) && $GLOBALS['Session']->Person ? $GLOBALS['Session']->Person : null;
     if (is_callable(static::$onGlobalsSet)) {
         call_user_func(static::$onGlobalsSet, $this);
     }
 }
Example #12
0
 /**
  * returns the full compiled file name and assigns a default value to it if
  * required
  *
  * @param Dwoo_Core $dwoo the dwoo instance that requests the file name
  * @return string the full path to the compiled file
  */
 protected function getCompiledFilename(Dwoo_Core $dwoo)
 {
     // no compile id was provided, set default
     if ($this->compileId === null) {
         $this->compileId = str_replace('../', '__', strtr($this->getResourceIdentifier(), '\\:', '/-'));
     }
     return $dwoo->getCompileDir() . $this->compileId . '.d' . Dwoo_Core::RELEASE_TAG . '.php';
 }
Example #13
0
 /**
  * returns the full compiled file name and assigns a default value to it if
  * required
  *
  * @param Dwoo_Core $dwoo the dwoo instance that requests the file name
  * @return string the full path to the compiled file
  */
 protected function getCompiledFilename(Dwoo_Core $dwoo)
 {
     // no compile id was provided, set default
     if ($this->compileId === null) {
         $this->compileId = $this->name;
     }
     return $dwoo->getCompileDir() . $this->compileId . '.d' . Dwoo_Core::RELEASE_TAG . '.php';
 }
Example #14
0
function Dwoo_Plugin_refill(Dwoo_Core $dwoo, $field = null, $assign = null, $modifier = null, $default = null, $selected = NULL, $checked = NULL, $escape = 'html', $value = null)
{
    // determine refill value
    if ($field && isset($_REQUEST[$field])) {
        $value = $_REQUEST[$field];
    } elseif ($field && ($req_value = refill_resolve_array_dot_path($field, $_REQUEST))) {
        $value = $req_value;
    } elseif (!isset($value) && isset($default)) {
        $value = $default;
    }
    // handle modifier
    if (!empty($modifier)) {
        if (function_exists($modifier)) {
            // run simple PHP function
            $value = call_user_func($modifier, $value);
        } else {
            // load Dwoo plugin
            if (function_exists('Dwoo_Plugin_' . $modifier) === false) {
                $dwoo->getLoader()->loadPlugin($modifier);
            }
            $value = call_user_func('Dwoo_Plugin_' . $modifier, $dwoo, $value);
        }
    }
    // handle selection
    if (isset($selected)) {
        if ($value == $selected || is_array($value) && in_array($selected, $value)) {
            return 'selected="SELECTED"';
        } else {
            return '';
        }
    } elseif (isset($checked)) {
        if ($value == $checked || is_array($value) && in_array($checked, $value)) {
            return 'checked="CHECKED"';
        } else {
            return '';
        }
    }
    // handle assignment
    if (isset($assign)) {
        $dwoo->assignInScope($value, $assign);
        return '';
    } elseif (empty($value)) {
        return '';
    } else {
        if ($escape == 'html') {
            return htmlspecialchars($value);
        } elseif ($escape == 'url') {
            return urlencode($value);
        } else {
            return $value;
        }
    }
    /*
    if(isset($params['checked'])) {
        if(is_array($value)) {
            $return = in_array($params['checked'], $value) ? 'checked="checked"' : '';
        } else {
            $return = ($value == $params['checked']) ? 'checked="checked"' : '';
        }
    } elseif(isset($params['selected'])) {
        if(is_array($value)) {
            $return = in_array($params['selected'], $value) ? 'selected="selected"' : '';
        } else {
            $return = ($value == $params['selected']) ? 'selected="selected"' : '';
        }
    } else {
        $return = (!empty($params['encode']) && ($params['encode'] == 'url')) ? urlencode($value) : htmlspecialchars($value);
    }
    
    //Return value
    if(empty($params['assign'])) {
        return $return;
    } else {
        $smarty->assign($params['assign'], $return);
    }
    */
}
Example #15
0
/**
 * Outputs a mailto link with optional spam-proof (okay probably not) encoding
 * <pre>
 *  * address : target email address
 *  * text : display text to show for the link, defaults to the address if not provided
 *  * subject : the email subject
 *  * encode : one of the available encoding (none, js, jscharcode or hex)
 *  * cc : address(es) to carbon copy, comma separated
 *  * bcc : address(es) to blind carbon copy, comma separated
 *  * newsgroups : newsgroup(s) to post to, comma separated
 *  * followupto : address(es) to follow up, comma separated
 *  * extra : additional attributes to add to the &lt;a&gt; tag
 * </pre>
 * This software is provided 'as-is', without any express or implied warranty.
 * In no event will the authors be held liable for any damages arising from the use of this software.
 *
 * @author     Jordi Boggiano <*****@*****.**>
 * @copyright  Copyright (c) 2008, Jordi Boggiano
 * @license    http://dwoo.org/LICENSE   Modified BSD License
 * @link       http://dwoo.org/
 * @version    1.1.0
 * @date       2009-07-18
 * @package    Dwoo
 */
function Dwoo_Plugin_mailto(Dwoo_Core $dwoo, $address, $text = null, $subject = null, $encode = null, $cc = null, $bcc = null, $newsgroups = null, $followupto = null, $extra = null)
{
    if (empty($address)) {
        return '';
    }
    if (empty($text)) {
        $text = $address;
    }
    // build address string
    $address .= '?';
    if (!empty($subject)) {
        $address .= 'subject=' . rawurlencode($subject) . '&';
    }
    if (!empty($cc)) {
        $address .= 'cc=' . rawurlencode($cc) . '&';
    }
    if (!empty($bcc)) {
        $address .= 'bcc=' . rawurlencode($bcc) . '&';
    }
    if (!empty($newsgroups)) {
        $address .= 'newsgroups=' . rawurlencode($newsgroups) . '&';
    }
    if (!empty($followupto)) {
        $address .= 'followupto=' . rawurlencode($followupto) . '&';
    }
    $address = rtrim($address, '?&');
    // output
    switch ($encode) {
        case 'none':
        case null:
            return '<a href="mailto:' . $address . '" ' . $extra . '>' . $text . '</a>';
        case 'js':
        case 'javascript':
            $str = 'document.write(\'<a href="mailto:' . $address . '" ' . $extra . '>' . $text . '</a>\');';
            $len = strlen($str);
            $out = '';
            for ($i = 0; $i < $len; $i++) {
                $out .= '%' . bin2hex($str[$i]);
            }
            return '<script type="application/javascript">eval(unescape(\'' . $out . '\'));</script>';
            break;
        case 'javascript_charcode':
        case 'js_charcode':
        case 'jscharcode':
        case 'jschar':
            $str = '<a href="mailto:' . $address . '" ' . $extra . '>' . $text . '</a>';
            $len = strlen($str);
            $out = '<script type="application/javascript">' . "\n<!--\ndocument.write(String.fromCharCode(";
            for ($i = 0; $i < $len; $i++) {
                $out .= ord($str[$i]) . ',';
            }
            return rtrim($out, ',') . "));\n-->\n</script>\n";
            break;
        case 'hex':
            if (strpos($address, '?') !== false) {
                return $dwoo->triggerError('Mailto: Hex encoding is not possible with extra attributes, use one of : <em>js, jscharcode or none</em>.', E_USER_WARNING);
            }
            $out = '<a href="&#109;&#97;&#105;&#108;&#116;&#111;&#58;';
            $len = strlen($address);
            for ($i = 0; $i < $len; $i++) {
                if (preg_match('#\\w#', $address[$i])) {
                    $out .= '%' . bin2hex($address[$i]);
                } else {
                    $out .= $address[$i];
                }
            }
            $out .= '" ' . $extra . '>';
            $len = strlen($text);
            for ($i = 0; $i < $len; $i++) {
                $out .= '&#x' . bin2hex($text[$i]);
            }
            return $out . '</a>';
        default:
            return $dwoo->triggerError('Mailto: <em>encode</em> argument is invalid, it must be one of : <em>none (= no value), js, js_charcode or hex</em>', E_USER_WARNING);
    }
}
Example #16
0
 public function testIsTraversableCountableIterator()
 {
     $dwoo = new Dwoo_Core();
     $data = new TestCountableIterator(array());
     $this->assertEquals(true, $dwoo->isTraversable($data));
     $this->assertEquals(0, $dwoo->isTraversable($data, true));
     $data = new TestCountableIterator(array('moo'));
     $this->assertEquals(true, $dwoo->isTraversable($data));
     $this->assertEquals(1, $dwoo->isTraversable($data, true));
 }
Example #17
0
 public function testCustomClassPluginInstanceAsModifier()
 {
     $dwoo = new Dwoo_Core(DWOO_COMPILE_DIR, DWOO_CACHE_DIR);
     $dwoo->addPlugin('CustomClassPlugin', array(new custom_class_plugin_obj(), 'call'));
     $tpl = new Dwoo_Template_String('{$foo=4}{$foo|CustomClassPlugin:5}');
     $tpl->forceCompilation();
     $this->assertEquals('20', $dwoo->get($tpl, array(), $this->compiler));
 }
Example #18
0
 /**
  * this is used at run time to check whether method calls are allowed or not
  *
  * @param Dwoo_Core $dwoo dwoo instance that calls this
  * @param object $obj any object on which the method must be called
  * @param string $method lowercased method name
  * @param array $args arguments array
  * @return mixed result of method call or unll + E_USER_NOTICE if not allowed
  */
 public function callMethod(Dwoo_Core $dwoo, $obj, $method, $args)
 {
     foreach ($this->allowedMethods as $class => $methods) {
         if (!isset($methods[$method])) {
             continue;
         }
         if ($obj instanceof $class) {
             return call_user_func_array(array($obj, $method), $args);
         }
     }
     $dwoo->triggerError('The current security policy prevents you from calling ' . get_class($obj) . '::' . $method . '()');
     return null;
 }
Example #19
0
 public function testCallingMethodOnProperty()
 {
     $tpl = new Dwoo_Template_String('{getobj()->instance->Bar("hoy")}');
     $tpl->forceCompilation();
     $dwoo = new Dwoo_Core(DWOO_COMPILE_DIR, DWOO_CACHE_DIR);
     $dwoo->addPlugin('getobj', array(new PluginHelper(), 'call'));
     $this->assertEquals('HOY', $dwoo->get($tpl, array(), $this->compiler));
 }