Template engine {var} doesnt work - php

I have made a template system but the {var} doesnt output the worth.
It just output {var}.
Here is my template class:
<?php
class Template {
public $assignedValues = array();
public $tpl;
function __construct($_path = '')
{
if(!empty($_path))
{
if(file_exists($_path))
{
$this->tpl = file_get_contents($_path);
}
else
{
echo 'Error: No template found. (code 25)';
}
}
}
function assign($_searchString, $_replaceString)
{
if(!empty($_searchString))
{
$this->assignedValues[strtoupper($_searchString)] = $_replaceString;
}
}
function show()
{
if(count($this->assignedValues) > 0)
{
foreach ($this->assignedValues as $key => $value)
{
$this->tpl = str_replace('{'.$key.'}', $value, $this->tpl);
}
}
echo $this->tpl;
}
}
?>
And here is what I execute on the index:
<?php
require_once('inc/classes/class.template.php');
define('PATH', 'tpl');
//new object
$template = new Template(PATH.'/test.tpl.html');
//assign values
$template->assign('title', 'Yupa');
$template->assign('about', 'Hello!');
//show the page
$template->show();
?>
I really need some help, if you can help I'd would be very grateful.

Instead of line:
$this->assignedValues[strtoupper($_searchString)] = $_replaceString;
You should have:
$this->assignedValues[$_searchString] = $_replaceString;
and it will work.
Of course I assume that inside your template file you have content:
{title} {about}

You should change
$this->assignedValues[strtoupper($_searchString)] = $_replaceString;
to this:
$this->assignedValues["{".$_searchString . "}"] = $_replaceString ;
this will only replace your keywords with values.

Related

PHP get link from txtfile, unset this link inside the array and get random array value

I'm trying to load a website url from a textfile, then unset this string from an array and pick a random website from the array.
But once I try to access the array from my function the array would return NULL, does someone know where my mistake is located at?
My current code looks like the following:
<?php
$activeFile = 'activeSite.txt';
$sites = array(
'http://wwww.google.com',
'http://www.ebay.com',
'http://www.icloud.com',
'http://www.hackforums.net',
'http://www.randomsite.com'
);
function getActiveSite($file)
{
$activeSite = file_get_contents($file, true);
return $activeSite;
}
function unsetActiveSite($activeSite)
{
if(($key = array_search($activeSite, $sites)) !== false)
{
unset($sites[$key]);
return true;
}
else
{
return false;
}
}
function updateActiveSite($activeFile)
{
$activeWebsite = getActiveSite($activeFile);
if(!empty($activeWebsite))
{
$unsetActive = unsetActiveSite($activeWebsite);
if($unsetActive == true)
{
$randomSite = $sites[array_rand($sites)];
return $randomSite;
}
else
{
echo 'Could not unset the active website.';
}
}
else
{
echo $activeWebsite . ' did not contain any active website.';
}
}
$result = updateActiveSite($activeFile);
echo $result;
?>
$sites is not avaliable in unsetActiveSite function you need to create a function called "getSites" which return the $sites array and use it in unsetActiveSite
function getSites(){
$sites = [
'http://wwww.google.com',
'http://www.ebay.com',
'http://www.icloud.com',
'http://www.hackforums.net',
'http://www.randomsite.com'
];
return $sites;
}
function unsetActiveSite($activeSite)
{
$sites = getSites();
if(($key = array_search($activeSite, $sites)) !== false)
{
unset($sites[$key]);
return true;
}
else
{
return false;
}
}

Get the function result from a class

I have a function inside a class, and I would like to get the result of this function, something like:
Returned dangerous functions are: dl, system
Here is my code
public final function filterFile(){
$disabled_functions = ini_get('disable_functions');
$disFunctionsNoSpace = str_replace(' ', '', $disabled_functions);
$disFunctions = explode(',', $disFunctionsNoSpace);
$this->disFunctions = $disFunctions;
// get file content of the uploaded file (renamed NOT the temporary)
$cFile = file_get_contents($this->fileDestination, FILE_USE_INCLUDE_PATH);
$found = array();
foreach($this->disFunctions as $kkeys => $vvals)
{
if(preg_match('#'.$vvals.'#i', $cFile))
{
array_push($found, $vvals);
}
} // end foreach
} // end filterFile
// calling the class
$up = new uploadFiles($filename);
$fileterringFile = $up->filterFile();
print_r($fileterringFile);
var_dump($fileterringFile);
EDIT: add 2 functions for errors:
// check if any uErrors
public final function checkErrors(){
$countuErrors = count($this->uErrors);
if((IsSet($this->uErrors) && (is_array($this->uErrors) && ($countuErrors > 0))))
{
return true;
}
return false;
} // end checkErrors()
// print user errors
public final function printErrors(){
$countuErrors = count($this->uErrors);
if((IsSet($this->uErrors) && (is_array($this->uErrors) && ($countuErrors > 0))))
{
echo '<ul>';
foreach($this->uErrors as $uV)
{
echo '<li>';
echo $uV;
echo '</li>';
}
echo '</ul>';
}
} // end printErrors()
Thanks in advance
at the end of end filterFile, add:
return 'Returned dangerous functions are: '.implode(',',$found);

Unable to load page with codeigniter

On my codeigniter HMVC project. When I try to run my first isset statement in modules foreach section. If I uncomment the code below then, fire fox loads page error The connection was reset.
But if I comment out the code like below the page loads fine very strange.
//if (isset($part[0]) && $this->setting->get($part[0] . '_status')) {
// $data['modules'][] = Modules::run('catalog/module/'.$part[0].'/index');
//}
For some reason does not like using isset($part[0])
How code works
$part[0] it returns the module name example category
$part[1] it returns the module number example 66 category.66
$this->setting->get($part[0] . '_status') returns either 1 if
enabled or 0 if disabled.
What could be the cause of page not loading when I uncomment the code above. Any suggestions
Controller
<?php
class Column_left extends MX_Controller {
public function index() {
$this->load->model('catalog/extension/model_extension_extension');
$this->load->model('catalog/design/model_design_layout');
$route = $this->uri->segment(1).'/'.$this->uri->segment(2);
// $route outputs like pages/category
$layout_id = 0;
if (!$layout_id) {
$layout_id = $this->model_design_layout->get_layout($route);
}
if (!$layout_id) {
// Setting library autoloaded
$layout_id = $this->setting->get('config_layout_id');
}
$data['modules'] = array();
$modules = $this->model_design_layout->get_layout_modules($layout_id, 'column_left');
foreach ($modules as $module) {
$part = explode('.', $module['code']);
echo $part[0];
// Setting library autoloaded
if (isset($part[0]) && $this->setting->get($part[0] . '_status')) {
$data['modules'][] = Modules::run('catalog/module/'.$part[0].'/index');
}
if (isset($part[1])) {
$setting_info = $this->model_extension_module->get_module($part[1]);
if ($setting_info && $setting_info['status']) {
$data['modules'][] = Modules::run('catalog/module/'.$part[0].'/index', $setting_info);
}
}
}
// Setting library autoloaded
if (file_exists(DIR_TEMPLATE .$this->setting->get('config_template'). '/template/common/column_left_view.php')) {
$this->load->view('theme/'.$this->setting->get('config_template').'/template/common/column_left_view', $data);
} else {
$this->load->view('theme/default/template/common/column_left_view', $data);
}
}
}
View
<?php if ($modules) { ?>
<column id="column-left" class="col-sm-3 hidden-xs">
<?php foreach ($modules as $module) { ?>
<?php echo $module; ?>
<?php } ?>
</column>
<?php } ?>
After working on it all after noon, was able to find the cause of the issue.
In my catalog modules folder I had 2 controllers named the same in different folders, catalog/category & module/category. Even though they were in different folders one was over riding other and causing page load error on fire fox.
How I solved problem. By renaming the controller in subfolder catalog to categories I refreshed page and then works.
I also cleaned up code here.
<?php
class Column_left extends MX_Controller {
public function index() {
$this->load->model('catalog/design/model_design_layout');
$route = $this->uri->segment(1).'/'.$this->uri->segment(2);
$layout_id = 0;
if (!$layout_id) {
$layout_id = $this->model_design_layout->get_layout($route);
}
if (!$layout_id) {
$layout_id = $this->setting->get('config_layout_id');
}
$data['modules'] = array();
$results = $this->model_design_layout->get_layout_modules($layout_id);
foreach ($results as $result) {
$part = explode('.', $result['code']);
if (isset($part[0]) && $this->setting->get($part[0] . '_status')) {
$data['modules'][] = Modules::run('catalog/module/'.$part[0].'/index');
}
if (isset($part[1])) {
$this->load->model('catalog/extension/model_extension_module');
$setting_info = $this->model_extension_module->get_module($part[1]);
if ($setting_info && $setting_info['status']) {
$data['modules'][] = Modules::run('catalog/module/'.$part[0].'/index', $setting_info);
}
}
}
$this->load->view('theme/default/template/common/column_left_view', $data);
}
}

my custom function not working

i create function called empty_fields but i can't figure out, to make it work..
<?php
function empty_fields($field_name)
{
if(!empty($order[$field_name]))
{
$output = "<li>Indigofera - " . $order[$field_name] . "Kg</li>";
} else { $output = null; }
return $output;
}
to display in html
<?php empty_fields('indigofera'); ?>
Change
if(!empty($order['$field_name'])){
to
if(!empty($order[$field_name])){
'$field_name' does not evaluate to anything and it will search for
key '$field_name' in the $orders array everytime, hence will not work.
Hope it works.
If you use $order as a global variable, use:
function empty_fields($field_name)
{
global $order;
$output = null;
if(!empty($order[$field_name]))
{
$output = "<li>Indigofera - " . $order[$field_name] . "Kg</li>";
}
return $output;
}
and use it:
<?php echo empty_fields('indigofera'); ?>
EDIT: the OOP way:
class Orders
{
private $order = null;
public function get_order()
{
$this->order = //....
}
public function empty_fields($field_name)
{
if(!isset($this->order) || empty($order[$field_name])) return;
return "<li>Indigofera - " . $order[$field_name] . "Kg</li>";
}
}
and use it:
<?php
$orders = new Orders();
$orders->get_order();
echo $orders->empty_fields("indigofera");

Pass MySQL Variable to Joomla Module instead of using default field for Twitter Search

It seems I've hit a wall here and could use some help
Would like to pass a MySql variable to a Joomla Module
Im using Yootheme's Widget-kit to display tweets from a search term. Works great and all but you need to enter the twitter search term in the Module back end.
Instead I would like to use a variable ( already used on the page) and pass that variable to the Twitter module so it can display the tweets I want
Here are some lines of PHP with the variable I'd like to use
$document->setTitle(JText::sprintf('COVERAGE_DATA_PLACE', $this->country->country_name, $this->city->city_name));
$text = JString::str_ireplace('%city_name%',$this->city->city_name,$text);
$this->setBreadcrumbs(array('country','city'));
Is there any way to take the "City" variable and send it to the 'word" field found in the twitter module?
Here is the Code for the twitter module
<?php
Class: TwitterWidgetkitHelper
Twitter helper class
*/
class TwitterWidgetkitHelper extends WidgetkitHelper {
/* type */
public $type;
/* options */
public $options;
/*
Function: Constructor
Class Constructor.
*/
public function __construct($widgetkit) {
parent::__construct($widgetkit);
// init vars
$this->type = strtolower(str_replace('WidgetkitHelper', '', get_class($this)));
$this->options = $this['system']->options;
// create cache
$cache = $this['path']->path('cache:');
if ($cache && !file_exists($cache.'/twitter')) {
mkdir($cache.'/twitter', 0777, true);
}
// register path
$this['path']->register(dirname(__FILE__), $this->type);
}
/*
Function: site
Site init actions
Returns:
Void
*/
public function site() {
// add translations
foreach (array('LESS_THAN_A_MINUTE_AGO', 'ABOUT_A_MINUTE_AGO', 'X_MINUTES_AGO', 'ABOUT_AN_HOUR_AGO', 'X_HOURS_AGO', 'ONE_DAY_AGO', 'X_DAYS_AGO') as $key) {
$translations[$key] = $this['system']->__($key);
}
// add stylesheets/javascripts
$this['asset']->addFile('css', 'twitter:styles/style.css');
$this['asset']->addFile('js', 'twitter:twitter.js');
$this['asset']->addString('js', sprintf('jQuery.trans.addDic(%s);', json_encode($translations)));
// rtl
if ($this['system']->options->get('direction') == 'rtl') {
$this['asset']->addFile('css', 'twitter:styles/rtl.css');
}
}
/*
Function: render
Render widget on site
Returns:
String
*/
public function render($options) {
if ($tweets = $this->_getTweets($options)) {
// get options
extract($options);
return $this['template']->render("twitter:styles/$style/template", compact('tweets', 'show_image', 'show_author', 'show_date', 'image_size'));
}
return 'No tweets found.';
}
/*
Function: _getURL
Create Twitter Query URL
Returns:
String
*/
protected function _getURL($options) {
// get options
extract($options);
// clean options
foreach (array('from_user', 'to_user', 'ref_user', 'word', 'nots', 'hashtag') as $var) {
$$var = preg_replace('/[##]/', '', preg_replace('/\s+/', ' ', trim($$var)));
}
// build query
$query = array();
if ($from_user) {
$query[] = 'from:'.str_replace(' ', ' OR from:', $from_user);
}
if ($to_user) {
$query[] = 'to:'.str_replace(' ', ' OR to:', $to_user);
}
if ($ref_user) {
$query[] = '#'.str_replace(' ', ' #', $ref_user);
}
if ($word) {
$query[] = $word;
}
if ($nots) {
$query[] = '-'.str_replace(' ', ' -', $nots);
}
if ($hashtag) {
$query[] = '#'.str_replace(' ', ' #', $hashtag);
}
$limit = min($limit ? intval($limit) : 5, 100);
// build timeline url
if ($from_user && !strpos($from_user, ' ') && count($query) == 1) {
$url = 'http://twitter.com/statuses/user_timeline/'.strtolower($from_user).'.json';
if ($limit > 15) {
$url .= '?count='.$limit;
}
return $url;
}
// build search url
if (count($query)) {
$url = 'http://search.twitter.com/search.json?q='.urlencode(implode(' ', $query));
if ($limit > 15) {
$url .= '&rpp='.$limit;
}
return $url;
}
return null;
}
/*
Function: _getTweets
Get Tweet Object Array
Returns:
Array
*/
protected function _getTweets($options) {
// init vars
$tweets = array();
// query twitter
if ($url = $this->_getURL($options)) {
if ($path = $this['path']->path('cache:twitter')) {
$file = rtrim($path, '/').sprintf('/twitter-%s.php', md5($url));
// is cached ?
if (file_exists($file)) {
$response = file_get_contents($file);
}
// refresh cache ?
if (!file_exists($file) || (time() - filemtime($file)) > 300) {
// send query
$request = $this['http']->get($url);
if (isset($request['status']['code']) && $request['status']['code'] == 200) {
$response = $request['body'];
file_put_contents($file, $response);
}
}
}
}
// create tweets
if (isset($response)) {
$response = json_decode($response, true);
if (is_array($response)) {
if (isset($response['results'])) {
foreach ($response['results'] as $res) {
$tweet = new WidgetkitTweet();
$tweet->user = $res['from_user'];
$tweet->name = $res['from_user'];
$tweet->image = $res['profile_image_url'];
$tweet->text = $res['text'];
$tweet->created_at = $res['created_at'];
$tweets[] = $tweet;
}
} else {
foreach ($response as $res) {
$tweet = new WidgetkitTweet();
$tweet->user = $res['user']['screen_name'];
$tweet->name = $res['user']['name'];
$tweet->image = $res['user']['profile_image_url'];
$tweet->text = $res['text'];
$tweet->created_at = $res['created_at'];
$tweets[] = $tweet;
}
}
}
}
return array_slice($tweets, 0, $options['limit'] ? intval($options['limit']) : 5);
}
}
class WidgetkitTweet {
public $user;
public $name;
public $image;
public $text;
public $created_at;
public function getLink() {
return 'http://twitter.com/'.$this->user;
}
public function getText() {
// format text
$text = preg_replace('#(https?://([-\w\.]+)+(/([\w/_\.]*(\?\S+)?(#\S+)?)?)?)#', '$1', $this->text);
$text = preg_replace('/#(\w+)/', '#$1', $text);
$text = preg_replace('/\s+#(\w+)/', ' #$1', $text);
return $text;
}
}
// bind events
$widgetkit = Widgetkit::getInstance();
$widgetkit['event']->bind('site', array($widgetkit['twitter'], 'site'));
I believe you can do what you want with this:
http://www.j-plant.com/joomla-extensions/free-extensions/26-module-plant.html
This plugin supports module parameters overriding. Use the next code
for overriding parameters:
[moduleplant id="77" <param_name_1>="<param_value_1>" <param_name_N>="<param_value_N>"]
replace and with the necessary parameter name and value.
You can override as many parameters as you want.
Available module parameters can be found in module XML manifest
file. A manifest file is usually located in the next path:
modules/<module_type>/<module_type>.xml

Categories