I am having troubles getting my redirectURL to grab the current URL inside of my IndexController. I have written something very similar that grabs the current product URL, but this is for the category. Can someone explain what I may have done wrong?
<?php
class Magestore_Categoryinquiry_IndexController extends Mage_Core_Controller_Front_Action
{
public function indexAction()
{
$this->_initLayoutMessages('catalog/session');
$this->loadLayout();
$this->renderLayout();
}
public function submitAction() {
$data = $this->getRequest()->getPost();
$error = false;
if($data) {
$category = Mage::getModel('catalog/category')->load($data['category_id']);
try {
$postObject = new Varien_Object();
$postObject->setData($data);
$error = false;
if (Mage::helper('categoryinquiry')->isRequireFname()) {
if (!Zend_Validate::is(trim($data['fname']) , 'NotEmpty')) {
$error = true;
}
}
if (Mage::helper('categoryinquiry')->isRequireLname()) {
if (!Zend_Validate::is(trim($data['lname']) , 'NotEmpty')) {
$error = true;
}
}
if (Mage::helper('categoryinquiry')->isRequireEmail()) {
if (!Zend_Validate::is(trim($data['customer_email']), 'EmailAddress')) {
$error = true;
}
}
if (Zend_Validate::is(trim($data['hideit']), 'NotEmpty')) {
$error = true;
}
if ($error) {
throw new Exception();
}
$model = Mage::getModel('categoryinquiry/categoryinquiry');
$data['store_id'] = Mage::app()->getStore()->getId();
$data['status'] = 1;
$data['created_time'] = now();
$data['updated_time'] = now();
$data['category_name'] = $category->getName();
$categoryinquiry = $this->getLayout()->createBlock('categoryinquiry/sendtocustomer')
->setInformation($data)
->setTemplate('categoryinquiry/email/sendtocustomer.phtml')
->toHtml();
$customercontact = $this->getLayout()->createBlock('categoryinquiry/sendtoadmin')
->setInformation($data)
->setTemplate('categoryinquiry/email/sendtoadmin.phtml')
->toHtml();
$model->setData($data)->save()
->sendMailToCustomer($model, $categoryinquiry)
->sendMailToAdmin($model, $customercontact)
;
Mage::getSingleton('catalog/session')->addSuccess(Mage::helper('categoryinquiry')->getSuccessMessage());
$this->_redirectUrl($category->getCategoryUrl());
return;
} catch (Exception $e) {
Mage::getSingleton('catalog/session')->addError(Mage::helper('categoryinquiry')->getErrorMessage());
$this->_redirectUrl($category->getCategoryUrl());
return;
}
}
}
}
I am trying to port my web app from laravel 4 to 5 but I am having issues in that one of my model classes is not found.
I have tried to utilize namespacing and have the following my Models which are located locally C:\xampp\htdocs\awsconfig\app\Models
the file which the error appears in looks like
<?php
use App\Models\SecurityGroup;
function from_camel_case($input)
{
preg_match_all('!([A-Z][A-Z0-9]*(?=$|[A-Z][a-z0-9])|[A-Za-z][a-z0-9]+)!', $input, $matches);
$ret = $matches[0];
foreach ($ret as &$match)
{
$match = $match == strtoupper($match) ? strtolower($match) : lcfirst($match);
}
return implode('_', $ret);
}
$resource_types = array();
$resource_types['AWS::EC2::Instance'] = 'EC2Instance';
$resource_types['AWS::EC2::NetworkInterface'] = 'EC2NetworkInterface';
$resource_types['AWS::EC2::VPC'] = 'VPC';
$resource_types['AWS::EC2::Volume'] = 'Volume';
$resource_types['AWS::EC2::SecurityGroup'] = 'SecurityGroup';
$resource_types['AWS::EC2::Subnet'] = 'Subnet';
$resource_types['AWS::EC2::RouteTable'] = 'RouteTable';
$resource_types['AWS::EC2::EIP'] = 'EIP';
$resource_types['AWS::EC2::NetworkAcl'] = 'NetworkAcl';
$resource_types['AWS::EC2::InternetGateway'] = 'InternetGateway';
$accounts = DB::table('aws_account')->get();
$account_list = array();
foreach(glob('../resources/sns messages/*.json') as $filename)
{
//echo $filename;
$data = file_get_contents($filename);
if($data!=null)
{
$decoded=json_decode($data,true);
if(isset($decoded["Message"]))
{
//echo "found message<br>";
$message= json_decode($decoded["Message"]);
if(isset($message->configurationItem))
{
// echo"found cfi<br>";
$insert_array = array();
$cfi = $message->configurationItem;
switch ($cfi->configurationItemStatus)
{
case "ResourceDiscovered":
//echo"found Resource Discovered<br>";
if (array_key_exists($cfi->resourceType,$resource_types))
{
//var_dump($cfi->resourceType);
$resource = new $resource_types[$cfi->resourceType];
foreach ($cfi->configuration as $key => $value)
{
if (in_array($key,$resource->fields))
{
$insert_array[from_camel_case($key)] = $value;
}
}
$resource->populate($insert_array);
if (!$resource->checkExists())
{
$resource->save();
if(isset($cfi->configuration->tags))
{
foreach ($cfi->configuration->tags as $t )
{
$tag= new Tag;
$tag->resource_type = "instance";
$tag->resource_id = $resource->id;
$tag->key = $t->key;
$tag->value = $t->value;
$tag->save();
/*if(isset($cfi->awsAccountId))
{
foreach ($accounts as $a)
{
$account_list = $a->account_id;
}
if (!in_array($account_id,$account_list))
{
$account_id = new Account;
$account_id->aws_account_id = $cfi->awsAccountId;
$account_list[] = $account_id;
$account_id->save();
}
} */
}
}
}
}
else
{
echo "Creating ".$cfi["resourceType"]." not yet supported<br>";
}
break;
case 'ResourceDeleted':
// echo"found Resource Deleted<br>";
//ITEM DELETED
if (array_key_exists($cfi->resourceType,$resource_types))
{
//var_dump($cfi->resourceType);
$resource = new $resource_types[$cfi->resourceType];
if ($resource->checkExists($cfi->resourceId))
{
$resource->delete();
if( isset($cfi->configuration->tags))
{
foreach ($cfi->configuration->tags as $t )
{
$tag= new Tag;
$tag->resource_type = "instance";
$tag->resource_id = $resource->id;
$tag->key = $t->key;
$tag->value = $t->value;
if ($tag->checkExists($cfi->configuration->tags))
{
$tag->delete();
}
}
}
}
}
else
{
echo "Deleting ".$cfi["resourceType"]." not yet supported<br>";
}
break;
case 'OK':
//echo"found Resource OK<br>";
//ITEM UPDATED
if (array_key_exists($cfi->resourceType, $resource_types))
{
//var_dump($cfi->resourceType);
$resource = new $resource_types[$cfi->resourceType];
if ($resource->checkExists($cfi->resourceId))
{
foreach ($cfi->configuration as $key => $value)
{
if (in_array($key,$resource->fields))
{
$update_array[from_camel_case($key)] = $value;
}
}
$resource->populate($update_array);
$resource->save();
}
}
else
{
echo "Updating ".$cfi["resourceType"]." not yet supported<br>";
}
break;
default:
echo "Status ".$cfi['configurationItemStatus']." not yet supported<br>";
break;
}
}
}
}
}
and the corresponding model whose class cannot be found looks like :
<?php namespace App\Models;
use Eloquent;
class SecurityGroup extends Eloquent
{
protected $table = 'security_group';
public $timestamps = false;
protected $guarded = array('id');
public $fields = array('groupId',
'groupName',
'description',
'ownerId'
);
public function checkExists()
{
return self::where('group_id', $this->group_id)->first();
}
public function populate($array)
{
foreach ($array as $k => $v)
{
$this->$k = $v;
}
}
}
I am lost as to what is causing the problem I don't see any typos but then again who knows as always thanks for any help given.
to solve the resource type needs the full namespace declaration
I am trying to search a value from database table and display result to web site using laravel. my controller.php code is here
else
{
try
{
$pname = Input::get('pname');
$parents = ForumParent::where('pname', $pname)->first();
if(empty($parents))
{
throw new \Exception("Parent not found");}
return Redirect::route('view',$parents->paddress);
}
catch (Exception $e)
{ return "not value";
//abort(404);
}
}
}
public function view($paddress)
{
$parents=ForumParent::find($paddress);
$users=User::all();
return View::make('search.viewsearch')
->with('parents',$parents)
->with('users',$users);
}
Change this:
$parents = ForumParent::where('pname', $pname)->first();
to this:
$parents = ForumParent::where('pname', '=', $pname)->first();
OR
$parents = ForumParent::where('pname','LIKE', '%' . $pname . '%')->first();
See, if that helps.
Is there any way in PHP to do static code analysis and detect reliance on the register_globals initiative? It's relatively straightforward to manually examine a file and look for variables which have not been initialized and infer from that that these may be relying on it, but I need to do this for many hundreds of scripts, so I'm looking for an automated solution.
My last resort is setting up a dev environment with the directive turned off and strict error reporting and letting QA play around for a long while, then fix the instances that the error log catches, but this is not guaranteed to find 100% of the cases, and certainly not a good use of resources if an automated solution exists.
A small script I just hacked together to detect simple undefined variables. You'll need PHP-Parser for this:
<?php
error_reporting(E_ALL);
$dir = './foo';
require_once './lib/bootstrap.php';
class Scope {
protected $stack;
protected $pos;
public function __construct() {
$this->stack = array();
$this->pos = -1;
}
public function addVar($name) {
$this->stack[$this->pos][$name] = true;
}
public function hasVar($name) {
return isset($this->stack[$this->pos][$name]);
}
public function pushScope() {
$this->stack[++$this->pos] = array();
}
public function popScope() {
--$this->pos;
}
}
class UndefinedVariableVisitor extends PHPParser_NodeVisitorAbstract {
protected $scope;
protected $parser;
protected $traverser;
public function __construct(Scope $scope, PHPParser_Parser $parser, PHPParser_NodeTraverser $traverser) {
$this->scope = $scope;
$this->parser = $parser;
$this->traverser = $traverser;
}
public function enterNode(PHPParser_Node $node) {
if (($node instanceof PHPParser_Node_Expr_Assign || $node instanceof PHPParser_Node_Expr_AssignRef)
&& $node->var instanceof PHPParser_Node_Expr_Variable
&& is_string($node->var->name)
) {
$this->scope->addVar($node->var->name);
} elseif ($node instanceof PHPParser_Node_Stmt_Global || $node instanceof PHPParser_Node_Stmt_Static) {
foreach ($node->vars as $var) {
if (is_string($var->name)) {
$this->scope->addVar($var->name);
}
}
} elseif ($node instanceof PHPParser_Node_Expr_Variable && is_string($node->name)) {
if (!$this->scope->hasVar($node->name)) {
echo 'Undefined variable $' . $node->name . ' on line ' . $node->getLine() . "\n";
}
} elseif ($node instanceof PHPParser_Node_Stmt_Function || $node instanceof PHPParser_Node_Stmt_ClassMethod) {
$this->scope->pushScope();
// params are always available
foreach ($node->params as $param) {
$this->scope->addVar($param->name);
}
// methods always have $this
if ($node instanceof PHPParser_Node_Stmt_ClassMethod) {
$this->scope->addVar('this');
}
} elseif ($node instanceof PHPParser_Node_Expr_Include && $node->expr instanceof PHPParser_Node_Scalar_String) {
$file = $node->expr->value;
$code = file_get_contents($file);
$stmts = $this->parser->parse($code);
// for includes within the file
$cwd = getcwd();
chdir(dirname($file));
$this->traverser->traverse($stmts);
chdir($cwd);
}
}
public function leaveNode(PHPParser_Node $node) {
if ($node instanceof PHPParser_Node_Stmt_Function || $node instanceof PHPParser_Node_Stmt_ClassMethod) {
$this->scope->popScope();
}
}
}
$parser = new PHPParser_Parser(new PHPParser_Lexer());
$scope = new Scope;
$traverser = new PHPParser_NodeTraverser;
$traverser->addVisitor(new UndefinedVariableVisitor($scope, $parser, $traverser));
foreach (new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($dir),
RecursiveIteratorIterator::LEAVES_ONLY)
as $file
) {
if (!preg_match('/\.php$/', $file)) continue;
echo 'Checking ' . $file . ':', "\n";
$code = file_get_contents($file);
$stmts = $parser->parse($code);
// for includes within the file
$cwd = getcwd();
chdir(dirname($file));
$scope->pushScope();
$traverser->traverse($stmts);
$scope->popScope();
chdir($cwd);
echo "\n";
}
It's just a very basic implementation and I did not test it extensively, but it should work for scripts that don't go wild with $GLOBALS and $$varVars. It does basic include resolution.
This should work (from one of the php manual comments):
if (ini_get('register_globals')) {
foreach ($GLOBALS as $int_temp_name => $int_temp_value) {
if (!in_array($int_temp_name, array (
'GLOBALS',
'_FILES',
'_REQUEST',
'_COOKIE',
'_SERVER',
'_ENV',
'_SESSION',
ini_get('session.name'),
'int_temp_name',
'int_temp_value'
))) {
unset ($GLOBALS[$int_temp_name]);
}
}
}
Tweaked the code above with the latest parser: used it to make 5.4 register_globals to 7.2
<?php
/*
* pgParser.php is a "Abstract syntax tree" progam based on the Nikic PHP-Parser https://github.com/nikic/PHP-Parser
* Tweaked for use to lose register global variables.
*/
use PhpParser\Node;
use PhpParser\NodeTraverser;
use PhpParser\NodeVisitorAbstract;
use PhpParser\Parser;
error_reporting(E_ALL);
/*
* $dir contains a base dir to use when no PARAM directory eq "php ./pgParser.php /home/hrobben/php/ > results.txt"
*/
$dir = '/home/hrobben/php/';
/*
* $nonecheck : variables not to check....
* e.g ['GLOBALS','_COOKIE', 'properties'] -> $GLOBALS, $_COOKIE, $properties >>>>> will not been checked.
*/
$nonecheck = ['_COOKIE', '_SERVER', '_SESSION'];
/*
* if those names part or directory not include...
* this can be usefull when certain users (developers) have own directories
* empty = [] no directories will be excluded
* e.g. ['george', 'henry'] all directories /tree/git/base/src/henry/ and /template/george/blog/ will be excluded.
*/
$nonesubdir = ['henry', 'ckeditor'];
/*
* $excludeMatch can be filled with text in directory plus file to exclude.
* e.q. _MA. will exclude the file index_MA.php3 to scan.
* e.g. _MA will exclude the file /git/src/test_MAIN/index.php3
* be carefull.
* Not for include files, only base files.
*/
$excludeMatch = ['_HR.', '_ed.'];
/*
* you can give a base directory to begin scanning.
*/
if (count($argv) > 0) {
$dir = $argv[1];
}
require_once './vendor/autoload.php';
class Scope
{
protected $stack;
protected $pos;
public function __construct()
{
$this->stack = array();
$this->pos = -1;
}
public function addVar($name)
{
$this->stack[$this->pos][$name] = true;
}
public function hasVar($name): bool
{
return isset($this->stack[$this->pos][$name]);
}
public function pushScope()
{
$this->stack[++$this->pos] = array();
}
public function popScope()
{
--$this->pos;
}
public function getPos()
{
return $this->pos;
}
}
class UndefinedVariableVisitor extends NodeVisitorAbstract
{
protected $scope;
protected $parser;
protected $traverser;
protected $nonecheck;
protected $isInclude = false;
public function __construct(Scope $scope, Parser $parser, NodeTraverser $traverser, array $nonecheck)
{
$this->scope = $scope;
$this->parser = $parser;
$this->traverser = $traverser;
$this->nonecheck = $nonecheck;
}
public function enterNode(Node $node)
{
$includePath = ['/home/hrobben/php/include/class/'];
$nonesubdir = ['jp', 'jp117']; // for the include exclusion directories.
if (($node instanceof PhpParser\Node\Expr\Assign || $node instanceof PhpParser\Node\Expr\AssignRef)
&& $node->var instanceof PhpParser\Node\Expr\Variable
&& is_string($node->var->name)
) {
// if preg_replace uses the same var name as second argument, its not setting a var, it must also be on the first level.
if ($node->expr->name->parts[0] == 'preg_replace' && $node->expr->args[2]->value->name == $node->var->name && $this->scope->getPos() == 0) {
//echo 'found $'.$node->expr->args[2]->value->name.' level '.$this->scope->getPos()."\n";
} else {
//echo 'add var $' . $node->var->name . "\n";
$this->scope->addVar($node->var->name);
}
} elseif ($node instanceof PhpParser\Node\Stmt\Global_ || $node instanceof PhpParser\Node\Stmt\Static_) {
foreach ($node->vars as $var) {
if (is_string($var->name)) {
$this->scope->addVar($var->name);
//echo 'add global or static var $' . $var->name . "\n";
}
}
} elseif ($node instanceof PhpParser\Node\Stmt\Foreach_) {
$this->scope->addVar($node->valueVar->name);
if ($node->keyVar) {
$this->scope->addVar($node->keyVar->name);
}
} elseif ($node instanceof PhpParser\Node\Stmt\StaticVar) {
$this->scope->addVar($node->var->name);
} elseif ($node instanceof PhpParser\Node\Expr\FuncCall && ($node->name->parts[0] == 'preg_match')) {
foreach ($node->args as $args) {
if ($node->args[2]) {
$this->scope->addVar($node->args[2]->value->name);
}
}
} elseif ($node instanceof PhpParser\Node\Expr\List_) {
foreach ($node->items as $item) {
$this->scope->addVar($item->value->name);
}
} elseif ($node instanceof PhpParser\Node\Expr\Closure) {
foreach ($node->params as $param) {
$this->scope->addVar($param->var->name);
}
} elseif ($node instanceof PhpParser\Node\Expr\Variable && is_string($node->name) && !$node instanceof PhpParser\Node\Const_) {
if (!$this->scope->hasVar($node->name) && !in_array($node->name, $this->nonecheck)) {
echo 'Undefined variable $' . $node->name . ' on line ' . $node->getLine() . "\n";
}
} elseif ($node instanceof PhpParser\Node\Stmt\Function_ || $node instanceof PhpParser\Node\Stmt\ClassMethod) {
$this->scope->pushScope();
// params are always available
foreach ($node->params as $param) {
//echo 'param name : '. $param->var->name. "\n";
$this->scope->addVar($param->var->name);
}
// methods always have $this
if ($node instanceof PhpParser\Node\Stmt\ClassMethod) {
$this->scope->addVar('this');
}
} elseif ($node instanceof PhpParser\Node\Expr\Include_ && $node->expr instanceof PhpParser\Node\Scalar\String_) {
$file = $node->expr->value;
$code = file_get_contents($file);
if (strlen($code) < 5) {
foreach ($includePath as $path) {
if (strlen($code) < 5) {
$code = file_get_contents($path . $file);
}
}
}
$match_string = implode("\/|", $nonesubdir);
if (preg_match("/$match_string\//", $file)) {
$code = '';
echo 'file skipped: ' . $file . "\n";
}
$stmts = $this->parser->parse($code);
// for includes within the file
$cwd = getcwd();
chdir(dirname($file));
$this->isInclude = true;
$this->traverser->traverse($stmts);
$this->isInclude = false;
chdir($cwd);
if (strlen($code) < 5) {
echo 'Include <- ' . $file . ' not found or empty.' . "\n";
} else {
echo 'Include <- ' . $file . "\n";
}
}
}
public function leaveNode(Node $node)
{
if ($node instanceof PhpParser\Node\Stmt\Function_ || $node instanceof PhpParser\Node\Stmt\ClassMethod) {
$this->scope->popScope();
}
}
}
$lexer = new PhpParser\Lexer();
$parser = (new PhpParser\ParserFactory)->create(
PhpParser\ParserFactory::PREFER_PHP7,
$lexer
);
$scope = new Scope;
$traverser = new NodeTraverser();
$traverser->addVisitor(new UndefinedVariableVisitor($scope, $parser, $traverser, $nonecheck));
foreach (new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($dir),
RecursiveIteratorIterator::LEAVES_ONLY)
as $file
) {
if (!preg_match('/\.php$|\.html$|\.php3$/', $file)) continue;
$match_string = implode("\/|\/", $nonesubdir);
if (preg_match("/\/$match_string\//", $file)) continue;
$match_string = implode("|", $excludeMatch);
if (preg_match("/$match_string/", $file)) continue;
echo 'Checking ' . $file . ':', "\n";
$code = file_get_contents($file);
$stmts = $parser->parse($code);
// print_r($stmts);
// for includes within the file
$cwd = getcwd();
chdir(dirname($file));
$scope->pushScope();
$traverser->traverse($stmts);
//print_r($stmts);
$scope->popScope();
chdir($cwd);
echo "\n";
}
Used this to make a big many script files holding code to go without global registered variables. We gone use it with PHP7.2
Try to make 'archive' for my blog. If the search run for unavaliable items the return is an empty object. Here is my code:
For example wrong input:
http://www.my-site.com/archive/2011/01/27 - in database no post with this date 2011-01-27
The controller action:
public function action_archive() {
$posts_model = new Model_Posts();
// Év pl.: 2012
if($year = $this->request->param("year")) {
// Hónap pl.: 2012-03
if($month = $this->request->param("month")) {
// Nap pl.: 2012-03-27
if($day = $this->request->param("day")) {
if ($posts = $posts_model->get_post_by_date($year . "-" . $month . "-" . $day)) {
$this->template->content = View::factory('posts/default')
->bind('posts', $posts);
} else
throw new HTTP_Exception_404;
} else {
if($posts = $posts_model->get_post_by_date($year . "-" . $month)) {
$this->template->content = View::factory('posts/default')
->bind('posts', $posts);
} else
throw new HTTP_Exception_404;
}
} else {
if($posts = $posts_model->get_post_by_date($year)) {
$this->template->content = View::factory('posts/default')
->bind('posts', $posts);
} else
throw new HTTP_Exception_404;
}
} else
// Nem található archívum
throw new HTTP_Exception_404;
return false;
}
I am try to throw 404 exception if the search fails. Here comes the model:
public function get_post_by_date($date) {
try {
return DB::select()
->from("posts")
->where("date", "like", "$date%")
->and_where("publish", "=", "1")
->as_object()
->execute();
} catch (Database_Exception $e) {
Kohana::$log->add(Log::ERROR, Database_Exception::text($e));
}
return false;
}
If you need just to check if there is a particular entry in the database use
->execute()->count();
In your case you will need the actual posts, so you can use the count method of the Database_Result class (it implements the Countable interface).
$posts = $posts_model->get_post_by_date($year . "-" . $month . "-" . $day);
if ($posts->count()) {
$this->template->content = View::factory('posts/default')
->bind('posts', $posts);
} else
throw new HTTP_Exception_404;
And remove that try-catch block. You don't need it if your query is correct.