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);
Related
I have a PHP class that highlights names mentioned in a text as links.It can search for #character in a given text and check the names that follow that character.
Theproblem is that the return value from class does not get printed out when I echo the method (public function process_text ($text_txt){}) that is responsible for processing the text. But when I change the return language construct to print or echo, then the parsing is successful and the processed string is printed out. I need to return and not print so as to be able to store the return string in a comments table of my CMS.
Kindly see full code below and advise:
class mentions {
public $print_content = '';
private $m_names = array();
private $m_denied_chars = array(
"#",
"#",
"?",
"¿"
);
private $m_link = "http://example.com/"; // + name of the username, link or whatever
/*
* this class can also be used for specific links
* start editing from here
* */
public function add_name ($name) {
array_push($this->m_names, $name);
}
public function process_text ($text_txt) {
$expl_text = explode(" ", $text_txt);
/*
* a character will be ignores which can be specified next this comment
* :)
* */
$sp_sign = "#"; // this is what you can change freely...
for ($i = 0; $i < count($expl_text); ++$i) {
$spec_w = $expl_text[$i];
$print_link = false;
$name_link = "";
if ($spec_w[0] == $sp_sign) { // then can be a mention...
$name = "";
$break_b = false;
for ($x = 1; $x < strlen($spec_w); ++$x) {
if ($spec_w[$x] == '.' || $spec_w[$x] == ",") {
if (in_array($name, $this->m_names)) {
$print_link = true;
$name_link = $name;
break;
}
}
if (in_array($spec_w[$x], $this->m_denied_chars)) {
$break_b = true;
break;
}
$name .= $spec_w[$x];
}
if ($break_b == true) {
$print_link = false;
break;
} else {
if (in_array($name, $this->m_names)) {
$print_link = true;
$name_link = $name;
}
}
}
if ($print_link == true) {
$this->print_content = "".$spec_w."";
if ($i < count($expl_text)) $this->print_content .= " ";
} else {
$this->print_content = $spec_w;
if ($i < count($expl_text)) $this->print_content .= " ";
}
return $this->print_content;
}
}
}
###### create new class object and process raw data ######
$mentions = new mentions;
$raw_data = 'Hello, #Angelina. I am #Bob_Marley.';
$expr = '#(?:^|\W)#([\w-]+)#i';
preg_match_all($expr, $raw_data, $results);
if( !empty($results[1]) ) {
foreach( $results[1] as $user ) {
$mentions->add_name($user);
}
/*
------------------------------------
*/
$commenData = $mentions->process_text($raw_data);
echo $commenData;
}
answer by #Terminus. If you have a return inside of a loop, the loop (and the entire function) will be interrupted and the value being returned will immediately be returned. That's just how it works. Was trying to write that as a good answer but couldn't. Did end up rewriting your class a bit. ideone.com/vaV0d2 note that i left in a test var_dump and that the output provided by ideone doesn't allow link tags to be displayed as html but if you run it from a server, it'll be correct
I have a function
function getImg($img,$str,$input){
// dd($img);
$img_path = public_path().'/images/photos/devices/'.$img.'.jpg';
if(file_exists($img_path)){
if(strpos($input,$str)){
return $img;
}else{
return 'no-img';
}
}else{
return 'no-img';
}
}
Then, I call it like this
getImg('phone','phone',$input);
Why do I keep getting this error ?
Cannot redeclare App\getImg()
The whole function
public static function img($input){
$img_path = public_path().'/images/photos/devices/';
$images = scandir($img_path, 1);
$devices = [];
foreach($images as $i=>$image){
if($image != '.' && $image != '..' && $image != '.DS_Store'){
$name = str_replace('.jpg', '', $image);
$devices[$i]['name'] = $name;
}
}
// dd($devices);
// dd($input);
foreach ($devices as $i=>$device) {
$matches = array_filter($devices, function($device) use ($input) {
return strpos($input, $device['name']) !== FALSE;
});
if(count($matches) > 0){
foreach ($matches as $match) {
$input = $match['name'];
$img_path = public_path().'/images/photos/devices/'.$input.'.jpg';
if(file_exists($img_path)){
return $input;
}else{
return 'no-img';
}
}
}else{
// dd($input);
function getImg($img,$str,$input){
// dd($img);
$img_path = public_path().'/images/photos/devices/'.$img.'.jpg';
if(file_exists($img_path)){
if(strpos($input,$str)){
return $img;
}else{
return 'no-img';
}
}else{
return 'no-img';
}
}
getImg('phone','phone',$input);
getImg('ipad','ipad',$input);
getImg('iphone','iphone',$input);
// getImg('imac','imac');
}
}
}
Your function should be declared outside the foreach loop like so
function getImg($img,$str,$input){
// dd($img);
$img_path = public_path().'/images/photos/devices/'.$img.'.jpg';
if(file_exists($img_path)){
if(strpos($input,$str)){
return $img;
}else{
return 'no-img';
}
}else{
return 'no-img';
}
}
foreach ($devices as $i=>$device) {
..........
}
In PHP a function is always in the global scope, this is different from JavaScript, where functions in functions are common.
So when you call your function img a second time it will try to redeclare the function getImg.
You should define your function outside of the first one, or wrap it in :
if ( ! function_exists('getImg')) {
...declare function
}
From the doc:
All functions and classes in PHP have the global scope - they can be
called outside a function even if they were defined inside and vice
versa.
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.
hi all when Using exif_imagetype() [function.exif-imagetype]: function for checking images if the user hits the submit button without uploading anything the exif function returns an error in the webpage itself. my question is how to get rid of this error. am pasting the error below
Warning: exif_imagetype() [function.exif-imagetype]: Filename cannot be empty in /mounted- storage/home98a/sub009/sc61374-HGPS/sitakalyanam.com/newsita/php4upload.class.php on line 88
<?php
/*
- PHP4 Image upload script
*/
class imageupload
{
//pblic variables
var $path = '';
var $errorStr = '';
var $imgurl = '';
//private variables
var $_errors = array();
var $_params = array();
var $_lang = array();
var $_maxsize = 1048576;
var $_im_status = false;
//public methods
function imageupload ()
{
//require 'photouploadconfig.php';
if($_GET['Choice']=="1")
{
require 'Photouploddir1.php';
}
elseif ($_GET['Choice']=="2")
{
require 'Photouploddir2.php';
}
elseif ($_GET['Choice']=="3")
{
require 'Photouploddir3.php';
}
elseif ($_GET['horoschoice']=="1")
{
require 'horosuploaddir.php';
}
elseif ($_GET['videoChoice']=="5")
{
require 'videouploaddir.php';
}
$this->_types = $types;
$this->_lang = $lang;
$this->_upload_dir = $upload_dir;
$this->_maxsize = $maxsize;
$this->path = $PHP_SELF;
if (is_array($_FILES['__upload']))
{
$this->_params = $_FILES['__upload'];
if (function_exists('exif_imagetype'))
$this->_doSafeUpload();
else
$this->_doUpload();
if (count($this->_errors) > 0)
$this->_errorMsg();
}
}
function allowTypes ()
{
$str = '';
if (count($this->_types) > 0) {
$str = 'Allowed types: (';
$str .= implode(', ', $this->_types);
$str .= ')';
}
return $str;
}
// private methods
function _doSafeUpload ()
{
preg_match('/\.([a-zA-Z]+?)$/', $this->_params['name'], $matches);
if (exif_imagetype($this->_params['tmp_name']) && in_a rray(strtolower($matches[1]), $this->_types))
{
if ($this->_params['size'] > $this->_maxsize)
$this->_errors[] = $this->_lang['E_SIZE'];
else
$this->_im_status = true;
if ($this->_im_status == true)
{
$ext = substr($this->_params['name'], -4);
$this->new_name = md5(time()).$ext;
move_uploaded_file($this->_params['tmp_name'], $this->_up load_dir.$this->new_name);
$this->imgurl =$this->new_name;
//$this->imgurl = .$this->new_name;
}
}
else
$this->_errors[] = $this->_lang['E_TYPE'];
}
function _doUpload ()
{
preg_match('/\.([a-zA-Z]+?)$/', $this->_params['name'], $matches);
if(in_array(strtolower($matches[1]), $this->_types))
{
if ($this->_params['size'] > $this->_maxsize)
$this->_errors[] = $this->_lang['E_SIZE'];
else
$this->_im_status = true;
if ($this->_im_status == true)
{
$ext = substr($this->_params['name'], -3);
$this->new_name = md5(time()).$ext;
move_uploaded_file($this->_params['tmp_name'], $this- >_upload_dir.$this->new_name);
$this->imgurl = ''.$this->new_name;
//$this->imgurl = ''.$this->_upload_dir.''.$this->new_name;
//$this->imgurl = ''.$this->new_name;
//$this->imgurl = $this->_upload_dir.'/'.$this->new_name;
}
}
else
$this->_errors[] = $this->_lang['E_TYPE'];
}
function _errorMsg()
{
$this->errorStr = implode('<br />', $this->_errors);
}
}
?>
You are getting that message because you are never checking if the user uploaded a file or not, you're just assuming they are. When the user does not upload a file then $_FILES will be an empty array.
That means that $this->_params['tmp_name'] won't exist. You need to check if a file was uploaded, not just assume one was.
Just simply check the size of $_FILES.
if(count($_FILES) === 0){
echo "no file uploaded";
}
Change your code to this one and then try
if (isset($_FILES['__upload']))
{
$this->_params = $_FILES['__upload'];
if (function_exists('exif_imagetype'))
$this->_doSafeUpload();
else
$this->_doUpload();
if (count($this->_errors) > 0)
$this->_errorMsg();
}
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