Joomla3 custom server side form validation rule - php

I am new to joomla component development(J3 , MVC) and i am trying to create a custom server side form validation rule.
I added validate="machinename" to my forms field and created a the file models\rules\machinename.php
defined('_JEXEC') or die('Restricted access');
jimport('joomla.form.formrule');
class JFormRuleMachinename extends JFormRule
{
protected $regex = '/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/';
}
I have a empty controller in controllers\field.php
defined('_JEXEC') or die('Restricted access');
// import Joomla controllerform library
jimport('joomla.application.component.controllerform');
class SampleControllerField extends JControllerForm
{
}
and the model is in models\field.php
defined('_JEXEC') or die('Restricted access');
// import Joomla modelform library
jimport('joomla.application.component.modeladmin');
/**
* HelloWorld Model
*/
class SampleModelField extends JModelAdmin
{
public function getTable($type = 'Field', $prefix = 'SampleTable', $config = array())
{
return JTable::getInstance($type, $prefix, $config);
}
/**
* Method to get the record form.
*
* #param array $data Data for the form.
* #param boolean $loadData True if the form is to load its own data (default case), false if not.
* #return mixed A JForm object on success, false on failure
* #since 2.5
*/
public function getForm($data = array(), $loadData = true)
{
// Get the form.
$form = $this->loadForm('com_sample.field', 'field',
array('control' => 'jform', 'load_data' => $loadData));
if (empty($form))
{
return false;
}
return $form;
}
/**
* Method to get the data that should be injected in the form.
*
* #return mixed The data for the form.
* #since 2.5
*/
protected function loadFormData()
{
// Check the session for previously entered form data.
$data = JFactory::getApplication()->getUserState('com_sample.edit.field.data', array());
if (empty($data))
{
$data = $this->getItem();
}
return $data;
}
}
my components name is com_sample and everything was working fine (new,edit,delete) but then i added the validation rule to the form's field and now i am getting a error when submitting the form :
JForm::validateField() rule `machinename` missing.
my best guess is that i have a mistake in naming or the file location but i am not sure and can't find anything with googleing .
so help me pliz ...

Find the solution myself, it seems that you need to add the rules folder pathto the form definition so :
<form addrulepath="/administrator/components/com_sample/models/rules">
this solved my problem .

I was struggling with this problem. I read the error as meaning that Joomla couldn't find the rule file, but when I single-stepped through the core I realised that after loading the rule file, Jommla checks that an appropriately named class is within the rule. I'd introduced a typo to the class name. So my advice to anyone struggling with server-side validation is to check the rule file is where you'd expect, AND that the class name is correct. Obvious I know, but it took me ages to figure.

Related

Symfony 3.3 - Validation without form

I am trying to perform some validation for some query string parameters that were passed in. I want to do 3 things:
Check if firstname was passed.
If it was passed, validate that it is a string. Otherwise, throw an error.
If it isn't passed, assign a default name.
I want to re-use as much of the built-in Symfony validator functionality to do this and so far have something like the code below (but it is not working). Would anyone have suggestions?
Relevant References:
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Validator\Constraints\Collection
use Symfony\Component\Validator\Constraints\Type
Code:
public function testingAction(Request $request)
{
$parameters = $request->query->all();
// for this example, assume that $parameters contains 'firstname'=>123
$collectionConstraint = new Collection(array(
'firstname' => new Type(array('type'=>'string'))
);
$errors = $this->container->get('validator')->validate($parameters, $collectionConstraint);
return new Response('<html><body><pre>' . print_r($errors, TRUE) . '</pre></body></html>');
}
Symfony validation works on entity class. You need to create an entity class for your data with validation annotations.
// src/Entity/Author.php
// ...
use Symfony\Component\Validator\Constraints as Assert;
class Author
{
/**
* #Assert\NotBlank()
*/
public $name;
}
//then use this class for your data
use src/Entity/Auther.php;
public function testingAction(Request $request)
{
$parameters = $request->query->all();
$auther = new Auther();
$auther->setName($paramater['name']);
$errors = $this->container->get('validator')->validate($auther);
return new Response('<html><body><pre>' . print_r($errors, TRUE) . '</pre></body></html>');
}
Please follow the symfony link https://symfony.com/doc/current/validation.html

Zend Framework 2 Form, regex validation not being applied

I am using a stand alone Zend Form (I'm not using the full blown ZF2 MVC) and I have specified the following class to define the form:
use Zend\Form\Annotation;
/**
* #Annotation\Hydrator("Zend\Stdlib\Hydrator\ObjectProperty")
*/
class Student
{
/**
* #Annotation\Type("Zend\Form\Element\Text")
* #Annotation\Options({"label":"Student code"})
* #Annotations\Validator({"name":"Regex", "options":{"pattern":"/^[0-9]+$/"}})
* #Annotation\Required({"required":"true"})
*/
public $student_code;
}
This is the relevant code in my controller (simplified to only show the relevant parts)
public function createAction()
{
$request = $this->getRequest();
$student = new Student();
$builder = new AnnotationBuilder();
$form = $builder->createForm($student);
$form->bind($student);
$form->setData($request->getPost());
if ($form->isValid()) {
var_dump($form->getPost());
}
}
The problem is that when I submitt the form and with 'abc' as the value for student_code, the form is returning as valid. According to the Regex it should only accept numbers.
The required part works; the form is invalid if student_code is empty. My question is, what am I missing that the Regex is not working?
replace with:
#Annotation\Validator({"name":"Regex", "options":{"pattern":"/^[0-9]+$/"}})
Note that I have removed the s at the end from #Annotation

Is there any way to compile a blade template from a string?

How can I compile a blade template from a string rather than a view file, like the code below:
<?php
$string = '<h2>{{ $name }}</h2>';
echo Blade::compile($string, array('name' => 'John Doe'));
?>
http://paste.laravel.com/ujL
I found the solution by extending BladeCompiler.
<?php namespace Laravel\Enhanced;
use Illuminate\View\Compilers\BladeCompiler as LaravelBladeCompiler;
class BladeCompiler extends LaravelBladeCompiler {
/**
* Compile blade template with passing arguments.
*
* #param string $value HTML-code including blade
* #param array $args Array of values used in blade
* #return string
*/
public function compileWiths($value, array $args = array())
{
$generated = parent::compileString($value);
ob_start() and extract($args, EXTR_SKIP);
// We'll include the view contents for parsing within a catcher
// so we can avoid any WSOD errors. If an exception occurs we
// will throw it out to the exception handler.
try
{
eval('?>'.$generated);
}
// If we caught an exception, we'll silently flush the output
// buffer so that no partially rendered views get thrown out
// to the client and confuse the user with junk.
catch (\Exception $e)
{
ob_get_clean(); throw $e;
}
$content = ob_get_clean();
return $content;
}
}
Small modification to the above script.
You can use this function inside any class without extending the BladeCompiler class.
public function bladeCompile($value, array $args = array())
{
$generated = \Blade::compileString($value);
ob_start() and extract($args, EXTR_SKIP);
// We'll include the view contents for parsing within a catcher
// so we can avoid any WSOD errors. If an exception occurs we
// will throw it out to the exception handler.
try
{
eval('?>'.$generated);
}
// If we caught an exception, we'll silently flush the output
// buffer so that no partially rendered views get thrown out
// to the client and confuse the user with junk.
catch (\Exception $e)
{
ob_get_clean(); throw $e;
}
$content = ob_get_clean();
return $content;
}
For anyone still interested in this, they've added it to Laravel 9
use Illuminate\Support\Facades\Blade;
return Blade::render('Hello, {{ $name }}', ['name' => 'Julian Bashir']);
https://laravel.com/docs/9.x/blade#rendering-inline-blade-templates
I just stumbled upon the same requirement! For me, i had to fetch a blade template stored in DB & render it to send email notifications.
I did this in laravel 5.8 by kind-of Extending \Illuminate\View\View. So, basically i created the below class & named him StringBlade (I couldn't find a better name atm :/)
<?php
namespace App\Central\Libraries\Blade;
use Illuminate\Filesystem\Filesystem;
class StringBlade implements StringBladeContract
{
/**
* #var Filesystem
*/
protected $file;
/**
* #var \Illuminate\View\View|\Illuminate\Contracts\View\Factory
*/
protected $viewer;
/**
* StringBlade constructor.
*
* #param Filesystem $file
*/
public function __construct(Filesystem $file)
{
$this->file = $file;
$this->viewer = view();
}
/**
* Get Blade File path.
*
* #param $bladeString
* #return bool|string
*/
protected function getBlade($bladeString)
{
$bladePath = $this->generateBladePath();
$content = \Blade::compileString($bladeString);
return $this->file->put($bladePath, $content)
? $bladePath
: false;
}
/**
* Get the rendered HTML.
*
* #param $bladeString
* #param array $data
* #return bool|string
*/
public function render($bladeString, $data = [])
{
// Put the php version of blade String to *.php temp file & returns the temp file path
$bladePath = $this->getBlade($bladeString);
if (!$bladePath) {
return false;
}
// Render the php temp file & return the HTML content
$content = $this->viewer->file($bladePath, $data)->render();
// Delete the php temp file.
$this->file->delete($bladePath);
return $content;
}
/**
* Generate a blade file path.
*
* #return string
*/
protected function generateBladePath()
{
$cachePath = rtrim(config('cache.stores.file.path'), '/');
$tempFileName = sha1('string-blade' . microtime());
$directory = "{$cachePath}/string-blades";
if (!is_dir($directory)) {
mkdir($directory, 0777);
}
return "{$directory}/{$tempFileName}.php";
}
}
As you can already see from the above, below are the steps followed:
First converted the blade string to the php equivalent using \Blade::compileString($bladeString).
Now we have to store it to a physical file. For this storage, the frameworks cache directory is used - storage/framework/cache/data/string-blades/
Now we can ask \Illuminate\View\Factory native method 'file()' to compile & render this file.
Delete the temp file immediately (In my case i didn't need to keep the php equivalent file, Probably same for you too)
And Finally i created a facade in a composer auto-loaded file for easy usage like below:
<?php
if (! function_exists('string_blade')) {
/**
* Get StringBlade Instance or returns the HTML after rendering the blade string with the given data.
*
* #param string $html
* #param array $data
* #return StringBladeContract|bool|string
*/
function string_blade(string $html, $data = [])
{
return !empty($html)
? app(StringBladeContract::class)->render($html, $data)
: app(StringBladeContract::class);
}
}
Now i can call it from anywhere like below:
<?php
$html = string_blade('<span>My Name is {{ $name }}</span>', ['name' => 'Nikhil']);
// Outputs HTML
// <span>My Name is Nikhil</span>
Hope this helps someone or at-least maybe inspires someone to re-write in a better way.
Cheers!
I'm not using blade this way but I thought that the compile method accepts only a view as argument.
Maybe you're looking for:
Blade::compileString()
It's a old question. But I found a package which makes the job easier.
Laravel Blade String Compiler renders the blade templates from the string value. Check the documentation on how to install the package.
Here is an example:
$template = '<h1>{{ $name }}</h1>'; // string blade template
return view (['template' => $template], ['name' => 'John Doe']);
Note: The package is now updated to support till Laravel 6.
I know its pretty old thread, but today also requirement is same.
Following is the way I solved this on my Laravel 5.7 (but this will work with any laravel version greater than version 5), I used the knowledge gained from this thread and few other threads to get this working (will leave links to all threads at the end, if this help up-vote those too)
I added this to my helper.php (I used this technique to add helper to my project, but you can use this function directly as well)
if (! function_exists('inline_view')) {
/**
* Get the evaluated view contents for the given blade string.
*
* #param string $view
* #param array $data
* #param array $mergeData
* #return \Illuminate\View\View|\Illuminate\Contracts\View\Factory
*/
function inline_view($view = null, $data = [], $mergeData = [])
{
/* Create a file with name as hash of the passed string */
$filename = hash('sha1', $view);
/* Putting it in storage/framework/views so that these files get cleared on `php artisan view:clear*/
$file_location = storage_path('framework/views/');
$filepath = storage_path('framework/views/'.$filename.'.blade.php');
/* Create file only if it doesn't exist */
if (!file_exists($filepath)) {
file_put_contents($filepath, $view);
}
/* Add storage/framework/views as a location from where view files can be picked, used in make function below */
view()->addLocation($file_location);
/* call the usual view helper to render the blade file created above */
return view($filename, $data, $mergeData);
}
}
Usage is exactly same as laravel's view() helper, only that now first parameter is the blade string
$view_string = '#if(strlen($name_html)>6)
<strong>{{ $name_html }}</strong>
#else
{{$name_html}}
#endif';
return inline_view($view_string)->with('name_html', $user->name);
return inline_view($view_string, ['name_html' => $user->name]);
References:
https://stackoverflow.com/a/31435824/4249775
https://stackoverflow.com/a/33594452/4249775
Laravel 9 :
use Illuminate\Support\Facades\Blade;
return Blade::render('Your Blade Content {{ $parameter1}}', ['parameter1' => 'Name']);

filter methods in a controller

I want to create a filter for my add, update, and delete actions in my controllers to automatically check if they
were called in a POST, as opposed to GET or some other method
and have the pageInstanceIDs which I set in the forms on my views
protects against xss
protects against double submission of a form
from submit button double click
from back button pressed after a submision
from a url being saved or bookmarked
Currently I extended \lithium\action\Controller using an AppController and have my add, update, and delete actions defined in there.
I also have a boolean function in my AppController that checks if the appropriate pageInstanceIDs are in session or not.
Below is my code:
public function isNotPostBack() {
// pull in the session
$pageInstanceIDs = Session::read('pageInstanceIDs');
$pageInstanceID = uniqid('', true);
$this->set(compact('pageInstanceID'));
$pageInstanceIDs[] = $pageInstanceID;
Session::write('pageInstanceIDs', $pageInstanceIDs);
// checks if this is a save operation
if ($this->request->data){
$pageInstanceIDs = Session::read('pageInstanceIDs');
$pageIDIndex = array_search($this->request->data['pageInstanceID'], $pageInstanceIDs);
if ($pageIDIndex !== false) {
// remove the key
unset($pageInstanceIDs[$pageIDIndex]);
Session::write('pageInstanceIDs', $pageInstanceIDs);
return true;
}
else
return false;
} else {
return true;
}
}
public function add() {
if (!$this->request->is('post') && exist($this->request->data())) {
$msg = "Add can only be called with http:post.";
throw new DispatchException($msg);
}
}
Then in my controllers I inherit from AppController and implement the action like so:
public function add() {
parent::add();
if (parent::isNotPostBack()){
//do work
}
return $this->render(array('layout' => false));
}
which will ensure that the form used a POST and was not double submitted (back button or click happy users). This also helps protect against XSS.
I'm aware there is a plugin for this, but I want to implement this as a filter so that my controller methods are cleaner. Implented this way, the only code in my actions are the //do work portion and the return statement.
You should probably start with a filter on lithium\action\Dispatcher::run() here is some pseudo code. Can't help too much without seeing your parent::isNotPostBack() method but this should get you on the right track.
<?php
use lithium\action\Dispatcher;
Dispatcher::applyFilter('run', function($self, $params, $chain) {
$request = $params['request'];
// Request method is in $request->method
// Post data is in $request->data
if($not_your_conditions) {
return new Response(); // set up your custom response
}
return $chain->next($self, $params, $chain); // to continue on the path of execution
});
First of all, use the integrated CSRF (XSRF) protection.
The RequestToken class creates cryptographically-secure tokens and keys that can be used to validate the authenticity of client requests.
— http://li3.me/docs/lithium/security/validation/RequestToken
Check the CSRF token this way:
if ($this->request->data && !RequestToken::check($this->request)) {
/* do your stuff */
}
You can even check the HTTP method used via is()
$this->request->is('post');
The problem of filters (for that use case) is that they are very generic. So if you don't want to write all your actions as filterable code (which might be painful and overkill), you'll have to find a way to define which method blocks what and filter the Dispatcher::_call.
For CSRF protection, I use something similar to greut's suggestion.
I have this in my extensions/action/Controller.php
protected function _init() {
parent::_init();
if ($this->request->is('post') ||
$this->request->is('put') ||
$this->request->is('delete')) {
//on add, update and delete, if the security token exists, we will verify the token
if ('' != Session::read('security.token') && !RequestToken::check($this->request)) {
RequestToken::get(array('regenerate' => true));
throw new DispatchException('There was an error submitting the form.');
}
}
}
Of course, this means you'd have to also add the following to the top of your file:
use \lithium\storage\Session;
use lithium\security\validation\RequestToken;
use lithium\action\DispatchException;
With this, I don't have to repeatedly check for CSRF.
I implemented something similar in a recent project by subclassing \lithium\action\Controller as app\controllers\ApplicationController (abstract) and applying filters to invokeMethod(), as that's how the dispatcher invokes the action methods. Here's the pertinent chunk:
namespace app\controllers;
class ApplicationController extends \lithium\action\Controller {
/**
* Essential because you cannot invoke `parent::invokeMethod()` from within the closure passed to `_filter()`... But it makes me sad.
*
* #see \lithium\action\Controller::invokeMethod()
*
* #param string $method to be invoked with $arguments
* #param array $arguments to pass to $method
*/
public function _invokeMethod($method, array $arguments = array()) {
return parent::invokeMethod($method, $arguments);
}
/**
* Overridden to make action methods filterable with `applyFilter()`
*
* #see \lithium\action\Controller::invokeMethod()
* #see \lithium\core\Object::applyFilter()
*
* #param string $method to be invoked with $arguments
* #param array $arguments to pass to $method
*/
public function invokeMethod($method, array $arguments = array()) {
return $this->_filter(__METHOD__, compact('method', 'arguments'), function($self, $params){
return $self->_invokeMethod($params['method'], $params['arguments']);
});
}
}
Then you can use applyFilter() inside of _init() to run filters on your method. Instead of checking $method in every filter, you can opt to change _filter(__METHOD__, . . .) to _filter($method, . . .), but we chose to keep the more generic filter.

How to retrieve the current page from Zend_Navigation within a Controller Plugin

I am working on an Authentication Plugin using a Controller Plugin. I define my navigation config within the application.ini file, and then use that and the Database user records to dynamically load the ACL and apply it to Zend_Navigation. This bit works, as it successfully loads the menu and only displays the pages the user is allowed to see.
However, this doesn't stop the user from going to the page directly. What I want to do is identify when the user is going to a page they don't have access to within the Controller Plugin so I can redirect their request to the Authentication page.
I was thinking there must be a function to retrieve the current page from Zend_Navigation, but I can't find it... so maybe it doesn't exist.
Anyway, this is my full Controller Plugin. Anyone see a solution?
<?php
class Pog_Model_AuthPlugin extends Zend_Controller_Plugin_Abstract
{
public function preDispatch(Zend_Controller_Request_Abstract $oRequest)
{
/**
* Load user
*/
$oAuth = Zend_Auth::getInstance();
$oDbUsers = new Pog_Model_DbTable_Users();
if (!$oAuth->hasIdentity())
{
$oUser = $oDbUsers->createRow();
$oUser->name = "guest";
$oUser->setReadOnly(true);
}
else
{
$oUser = $oAuth->getIdentity();
$oUser->setTable($oDbUsers);
}
/**
* Load ACL
*/
$oAcl = new Zend_Acl();
$oAcl->addRole($oUser->name);
/**
* Add current user privileges
*/
$oPrivileges = $oUser->getPrivileges();
foreach ($oPrivileges as $oPrivilege)
{
if (!$oAcl->has($oPrivilege->resource))
$oAcl->addResource($oPrivilege->resource);
$oAcl->allow($oUser->name, $oPrivilege->resource, $oPrivilege->privilege);
}
/**
* Load Navigation view helper
*/
$oViewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('ViewRenderer');
$oNavigation = $oViewRenderer->view->navigation();
/**
* Add remaining Navigation resources
*/
foreach ($oNavigation->getPages() as $oPage)
{
if (!is_null($oPage->getResource()) && !$oAcl->has($oPage->getResource()))
$oAcl->addResource($oPage->getResource());
}
/**
* Set ACL and Role
*/
$oNavigation->setAcl($oAcl)->setRole($oUser->name);
/**
* Check if use is allowed to be here
*/
...MAGIC GOES HERE...
}
}
I think that you should be able to get current navigation page as follows:
/**
* Load Navigation view helper
*/
$oViewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('ViewRenderer');
$oNavigation = $oViewRenderer->view->navigation();
/*#var $active array */
$active = $oNavigation->findActive($oNavigation->getContainer());
/*#var $activePage Zend_Navigation_Page_Mvc */
$activePage = $active['page'];
// example of getting page info
var_dump($activePage->getLabel(), $activePage->getController(), $activePage->getAction());
Hope this helps.
This is the solution I used, since I can't get Marcin's solution working in my setup for some reason.
I did some more thinking and thought of a nice simple solution to the problem. Rather than use the Navigation module to find the Active page, I find it myself. Since I am already iterating through the pages, it's a piece of cake to compare the Controller and Action - if these both match I have my Active page!
The new getPages() foreach loop looks like this:
$oCurrentPage = null;
foreach ($oNavigation->getPages() as $oPage)
{
/**
* Check for Current Page
*/
if ($oPage->getController() == $oRequest->getControllerName()
&& $oPage->getAction() == $oRequest->getActionName())
$oCurrentPage = $oPage;
/**
* Add Resource, if missing
*/
if (!is_null($oPage->getResource()) && !$oAcl->has($oPage->getResource()))
$oAcl->addResource($oPage->getResource());
}

Categories