Using symfony UnicodeString on laravel - php

I want to use unicodeString from symfoni in laravel controller
protected function validateWaWebhook($known_token, Request $request)
{
if (($signature = $request->headers->get('X-Hub-Signature-256')) == null) {
// throw new BadRequestHttpException('Header not set');
return "header not set";
}
$signature_parts = explode('=', $signature);
if (count($signature_parts) != 2) {
// throw new BadRequestHttpException('signature has invalid format');
return "Signature invalid format";
}
$type = UnicodeString($request->getContent())->normalize(UnicodeString::NFC);
$known_signature = hash_hmac('sha256', $type, $known_token,false);
if (! hash_equals($known_signature, $signature_parts[1])) {
// throw new UnauthorizedException('Could not verify request signature ' . $signature_parts[1]);
return "Could not verify signature";
}
return "Valid signature";
}
When i try it it show
Error: Call to undefined function App\Http\Controllers\UnicodeString()
I've called the symphony
use Symfony\Component\String\UnicodeString;

You need to instantiate the class first and then call normalize method like this.
$unicode = new UnicodeString($request->getContent());
$type = $unicode->normalize(UnicodeString::NFC);
or shorter
$type = (new UnicodeString($request->getContent()))->normalize(UnicodeString::NFC);

Related

PHP - ZF2 - render template from string variable

i have problem with rendering template in ZF2, where template is in string in variable. There is simple example:
$template = "<div>easy</div>";
$view = new \Zend\View\Model\ViewModel();
$view->setTemplate($template);
$renderer = new \Zend\View\Renderer\PhpRenderer();
$html = $renderer->render($view);
This code fail on rendering, the renderer think that the template is a path to file. And iam reallz not sure how to tell rendere its a string.
Thx for your time and respond.
You have to extend the PhpRenderer class and override the render method, in such a way that will use the string in the $template as the actual template:
class MyPhpRenderer extends PhpRenderer {
public function render($nameOrModel, $values = null)
{
if ($nameOrModel instanceof Model) {
$model = $nameOrModel;
$nameOrModel = $model->getTemplate();
if (empty($nameOrModel)) {
throw new Exception\DomainException(sprintf(
'%s: received View Model argument, but template is empty',
__METHOD__
));
}
$options = $model->getOptions();
foreach ($options as $setting => $value) {
$method = 'set' . $setting;
if (method_exists($this, $method)) {
$this->$method($value);
}
unset($method, $setting, $value);
}
unset($options);
// Give view model awareness via ViewModel helper
$helper = $this->plugin('view_model');
$helper->setCurrent($model);
$values = $model->getVariables();
unset($model);
}
// find the script file name using the parent private method
$this->addTemplate($nameOrModel);
unset($nameOrModel); // remove $name from local scope
$this->__varsCache[] = $this->vars();
if (null !== $values) {
$this->setVars($values);
}
unset($values);
// extract all assigned vars (pre-escaped), but not 'this'.
// assigns to a double-underscored variable, to prevent naming collisions
$__vars = $this->vars()->getArrayCopy();
if (array_key_exists('this', $__vars)) {
unset($__vars['this']);
}
extract($__vars);
unset($__vars); // remove $__vars from local scope
while ($this->__template = array_pop($this->__templates)) {
$this->__file = $this->resolver($this->__template);
try {
if (!$this->__file) {
$this->__content = $this->__template; // this line does what you need
}else{
ob_start();
$includeReturn = include $this->__file;
$this->__content = ob_get_clean();
}
} catch (\Exception $ex) {
ob_end_clean();
throw $ex;
}
if ($includeReturn === false && empty($this->__content)) {
throw new Exception\UnexpectedValueException(sprintf(
'%s: Unable to render template "%s"; file include failed',
__METHOD__,
$this->__file
));
}
}
$this->setVars(array_pop($this->__varsCache));
if ($this->__filterChain instanceof FilterChain) {
return $this->__filterChain->filter($this->__content); // filter output
}
return $this->__content;
}
}
and then you code should look like:
$template = "<div>easy</div>";
$view = new \Zend\View\Model\ViewModel();
$view->setTemplate($template);
$renderer = new MyPhpRenderer();
$html = $renderer->render($view);
Try by replacing '\' with _ underscore as Zend_View_Renderer_PhpRenderer

save form field in component params joomla

I am using joomla 2.5, I am working on custom component of joomla . I have created the form in backend admin page. what i need is , i want to save the post data of form in params row of that component in database of #_extensions.
Here is my tables/component.php
<?php defined('_JEXEC') or die('Restricted access');
jimport('joomla.database.table');
class componentTablecomponent extends JTable {
function __construct(&$db)
{
parent::__construct('#__extensions', 'extension_id', $db);
}
public function bind($array, $ignore = '')
{
if (isset($array['params']) && is_array($array['params']))
{
// Convert the params field to a string.
$parameter = new JRegistry;
$parameter->loadArray($array['params']);
$array['params'] = (string)$parameter;
}
return parent::bind($array, $ignore);
}
public function load($pk = null, $reset = true)
{
if (parent::load($pk, $reset))
{
// Convert the params field to a registry.
$params = new JRegistry;
$params->loadJSON($this->params);
$this->params = $params;
return true;
}
else
{
return false;
}
} public function store() {
parent::store(null);
}
}
Instead of saving the $data in params row of that component . This code is creating new empty rows in that table(data is saving in those params field).
Here is my save() function in controllers/component.php
public function save()
{
// Check for request forgeries.
JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN'));
// Check if the user is authorized to do this.
if (!JFactory::getUser()->authorise('core.admin'))
{
`JFactory::getApplication()->redirect('index.php',JText::_('JERROR_ALERTNOAUTHOR'));`
return;
}
// Initialise variables.
$app = JFactory::getApplication();
$model = $this->getModel('component');
$form = $model->getForm();
$data = JRequest::getVar('jform', array(), 'post', 'array');
print_r($data);
// Validate the posted data.
$return = $model->validate($form, $data);
// Check for validation errors.
if ($return === false)
{
// Get the validation messages.
$errors = $model->getErrors();
// Push up to three validation messages out to the user.
for ($i = 0, $n = count($errors); $i < $n && $i < 3; $i++) {
if ($errors[$i] instanceof Exception) {
$app->enqueueMessage($errors[$i]->getMessage(), 'warning');
} else {
$app->enqueueMessage($errors[$i], 'warning');
}
}
// Redirect back to the edit screen.
$this->setRedirect(JRoute::_('somelink',false));
return false;
}
// Attempt to save the configuration.
$data = $return;
$return = $model->save($data);
// Check the return value.
if ($return === false)
{
// Save failed, go back to the screen and display a notice.
$message = JText::sprintf('JERROR_SAVE_FAILED', $model->getError());
$this->setRedirect('index.php/somelink','error');
return false;
}
// Set the success message.
$message = JText::_('COM_CONFIG_SAVE_SUCCESS');
// Set the redirect based on the task.
switch ($this->getTask())
{
case 'apply':
$this->setRedirect('somelink',$message);
break;
case 'cancel':
case 'save':
default:
$this->setRedirect('index.php', $message);
break;
}
return true;
}
models/component.php
public function save($data) {
parent::save($data);
return true;
}
I thinks these codes are enough . I can add more codes if you need.
If you want to store params in the extension table, why not just use com_config for it?
See http://docs.joomla.org/J2.5:Developing_a_MVC_Component/Adding_configuration
Then you don't have to do anything besides creating the config.xml and adding a link to the config options in the toolbar.
I have come up with a solution . it works for me . By using this method you can control save () functions i.e. you can run your custom php scripts on save, apply toolbar buttons.
I copied save(),save($data), store($updateNulls = false) functions from com_config component , I have copied the layout from component view . Removed the buttons. Added toolbar buttons in .html.php file.
controllers/mycomponent.php
<?php
defined('_JEXEC') or die;
class componentControllermycomponent extends JControllerLegacy {
function __construct($config = array())
{
parent::__construct($config);
// Map the apply task to the save method.
$this->registerTask('apply', 'save');
}
function save()
{
// Check for request forgeries.
JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN'));
// Set FTP credentials, if given.
JClientHelper::setCredentialsFromRequest('ftp');
// Initialise variables.
$app = JFactory::getApplication();
$model = $this->getModel('mymodel');
$form = $model->getForm();
$data = JRequest::getVar('jform', array(), 'post', 'array');
$id = JRequest::getInt('id');
$option = 'com_mycomponent';
// Check if the user is authorized to do this.
if (!JFactory::getUser()->authorise('core.admin', $option))
{
JFactory::getApplication()->redirect('index.php', JText::_('JERROR_ALERTNOAUTHOR'));
return;
}
// Validate the posted data.
$return = $model->validate($form, $data);
// Check for validation errors.
if ($return === false) {
// Get the validation messages.
$errors = $model->getErrors();
// Push up to three validation messages out to the user.
for ($i = 0, $n = count($errors); $i < $n && $i < 3; $i++) {
if ($errors[$i] instanceof Exception) {
$app->enqueueMessage($errors[$i]->getMessage(), 'warning');
} else {
$app->enqueueMessage($errors[$i], 'warning');
}
}
// Save the data in the session.
$app->setUserState('com_iflychat.config.global.data', $data);
// Redirect back to the edit screen.
$this->setRedirect(JRoute::_('index.php?option=com_mycomponent&view=component&component='.$option.'&tmpl=component', false));
return false;
}
// Attempt to save the configuration.
$data = array(
'params' => $return,
'id' => $id,
'option' => $option
);
// print_r($data);
$return = $model->save($data);
// Check the return value.
if ($return === false)
{
// Save the data in the session.
$app->setUserState('com_config.config.global.data', $data);
// Save failed, go back to the screen and display a notice.
$message = JText::sprintf('JERROR_SAVE_FAILED', $model->getError());
$this->setRedirect('index.php?option=com_mycomponent&view=component&component='.$option.'&tmpl=component', $message, 'error');
return false;
}
// Set the redirect based on the task.
switch ($this->getTask())
{
case 'apply':
$message = JText::_('COM_MYCOMPONENT_SAVE_SUCCESS');
print_r($data);
$this->setRedirect('index.php?option=com_mycomponent&view=myview&layout=edit', $message);
break;
case 'save':
default:
$this->setRedirect('index.php');
break;
}
return true;
}
function cancel()
{
$this->setRedirect('index.php');
}
}
models/mymodel.php
<?php
defined('_JEXEC') or die;
jimport('joomla.application.component.modelform');
class componentModelmymodel extends JModelForm {
protected $event_before_save = 'onConfigurationBeforeSave';
protected $event_after_save = 'onConfigurationAfterSave';
public function getForm($data = array(), $loadData = true){
// Get the form.
$form = $this->loadForm('com_mycomponent.form', 'config',
array('control' => 'jform', 'load_data' => $loadData));
if (empty($form)){
return false;
}
return $form;
}
public function save($data)
{
$dispatcher = JDispatcher::getInstance();
$table = JTable::getInstance('extension');
$isNew = true;
// Save the rules.
if (isset($data['params']) && isset($data['params']['rules']))
{
$rules = new JAccessRules($data['params']['rules']);
$asset = JTable::getInstance('asset');
if (!$asset->loadByName($data['option']))
{
$root = JTable::getInstance('asset');
$root->loadByName('root.1');
$asset->name = $data['option'];
$asset->title = $data['option'];
$asset->setLocation($root->id, 'last-child');
}
$asset->rules = (string) $rules;
if (!$asset->check() || !$asset->store())
{
$this->setError($asset->getError());
return false;
}
// We don't need this anymore
unset($data['option']);
unset($data['params']['rules']);
}
// Load the previous Data
if (!$table->load($data['id']))
{
$this->setError($table->getError());
return false;
}
unset($data['id']);
// Bind the data.
if (!$table->bind($data))
{
$this->setError($table->getError());
return false;
}
// Check the data.
if (!$table->check())
{
$this->setError($table->getError());
return false;
}
// Trigger the oonConfigurationBeforeSave event.
$result = $dispatcher->trigger($this->event_before_save, array($this->option . '.' . $this->name, $table, $isNew));
if (in_array(false, $result, true))
{
$this->setError($table->getError());
return false;
}
// Store the data.
if (!$table->store())
{
$this->setError($table->getError());
return false;
}
// Clean the component cache.
$this->cleanCache('_system');
// Trigger the onConfigurationAfterSave event.
$dispatcher->trigger($this->event_after_save, array($this->option . '.' . $this->name, $table, $isNew));
return true;
}
function getComponent()
{
$result = JComponentHelper::getComponent('com_mycomponent');
return $result;
}
}
tables/mycomponent.php
<?php
// No direct access
defined('_JEXEC') or die('Restricted access');
// import Joomla table library
jimport('joomla.database.table');
/**
* Hello Table class
*/
class componentTableMycomponent extends JTable
{
function __construct(&$db)
{
parent::__construct('#__extensions', 'extension_id', $db);
}
public function bind($array, $ignore = '')
{
if (isset($array['params']) && is_array($array['params']))
{
// Convert the params field to a string.
$parameter = new JRegistry;
$parameter->loadArray($array['params']);
$array['params'] = (string)$parameter;
}
return parent::bind($array, $ignore);
}
public function load($pk = null, $reset = true)
{
if (parent::load($pk, $reset))
{
// Convert the params field to a registry.
$params = new JRegistry;
$params->loadJSON($this->params);
$this->params = $params;
return true;
}
else
{
return false;
}
}
public function store($updateNulls = false)
{
// Transform the params field
if (is_array($this->params)) {
$registry = new JRegistry();
$registry->loadArray($this->params);
$this->params = (string)$registry;
}
$date = JFactory::getDate();
$user = JFactory::getUser();
if ($this->id) {
// Existing item
$this->modified = $date->toSql();
$this->modified_by = $user->get('id');
} else {
// New newsfeed. A feed created and created_by field can be set by the user,
// so we don't touch either of these if they are set.
if (!intval($this->created)) {
$this->created = $date->toSql();
}
if (empty($this->created_by)) {
$this->created_by = $user->get('id');
}
}
// Verify that the alias is unique
$table = JTable::getInstance('Yourinstance', 'mycomponentTable');
if ($table->load(array('alias'=>$this->alias, 'catid'=>$this->catid)) && ($table->id != $this->id || $this->id==0)) {
$this->setError(JText::_('COM_CONTACT_ERROR_UNIQUE_ALIAS'));
return false;
}
// Attempt to store the data.
return parent::store($updateNulls);
}
}
Note : your config.xml file should be in models/forms folder.

method returns false when it should return true

I can't work out why this method keeps returning false. I'm checking the length of a password entered. It is definitely over 5 characters.The name of the input field is correct. But it always throws the exception throw new Exception("Password must contain at least 6 characters.");.
method:
public function checkPassword(){
if(strlen($this->post_data['register_password']) > 5){
}else{
throw new Exception("Password must contain at least 6 characters.");
}
}
calling:
if( isset($_POST['register-submit'])){
$error = '';
$register = new register($_POST, $dbh);
try {
if($register->checkUsername()){
if($register->checkPassword()){
}
}
} catch (Exception $e) {
$error .= '<span style="color:red;">' . $e->getMessage() . '</span>';
}
}
edit: added more of the class
public $post_data = array();
private $dbh;
public function __construct($post_data, PDO $dbh){
$this->error = array();
$this->post_data = array_map('trim', $post_data);
$this->dbh = $dbh;
}
Try putting var_dump($_POST) at the top of the calling code. Make sure you have the right variable name for password. I notice you have register-submit for the submit button and register_password for the password. Did you mix the hyphen (-) with an underscore (_)?
You create the class register, with $_POST, then use $this->post_data to fetch register_password. I doubt that there is something wrong with $this->post_data, add var_dump to debug:
public function checkPassword(){
if(strlen($_POST['register_password']) > 5){
return true;
}else{
// for debug
// var_dump($this->post_data['register_password']);
throw new Exception("Password must contain at least 6 characters.");
}
}
add var_dump to debug the __construct:
public function __construct($post_data, PDO $dbh){
$this->error = array();
$this->post_data = array_map('trim', $post_data);
var_dump($this->post_data);
$this->dbh = $dbh;
}

How can I return a data object when throwing a RestException?

function put($id, $name)
{
try
{
product::put($id, $name);
}
catch(\util\BadNameException $e)
{
throw new RestException(400, "Please supply a better name.");
}
}
When returning the error message I also want to include the result of (array)product::getNamingConvention() in the error. How can I do that?
I could just return a custom array with the error message and data, but I don't know how to set the status code to 400 in that case?
I'm using Restler 3.
Responder class is responsible for giving a structure to error response and success response
You can extend the Responder class as shown below to add data property
use \Luracast\Restler\Responder;
use \Luracast\Restler\Defaults;
class MyResponder extends Responder
{
public static $data = null;
public function formatError($statusCode, $message)
{
$r = array(
'error' => array(
'code' => $statusCode,
'message' => $message
)
);
if (isset(self::$data)) {
$r['data'] = self::$data;
}
return $r;
}
}
Defaults::$responderClass = 'MyResponder';
And then set the data from your class as shown below
function put($id, $name)
{
try
{
product::put($id, $name);
}
catch(\util\BadNameException $e)
{
MyResponder::$data = product::getNamingConvention();
throw new RestException(400, "Please supply a better name.");
}
}

PHP exception and user message

I have a project object.
A user can assign a worker object for it.
99% of the case the project object has all the proper fields set.
In some cases, the project is missing a field.
In order for a worker to be assign to a project the project must have all the required fields setup.
To solve this, I throw exceptions like this: ( don't try to find a pattern here, the real example is more complex )
if ($project->startDate == false ) {
throw new Exception("Missing startDate attribute for project id: $id");
}
if ($project->finishDate == false ) {
throw new Exception("Missing finishDate attribute for project id: $id");
}
if ($project->startDate > $project->finishDate ) {
throw new Exception("Invalid start date for project id: $id");
}
The problem with this is that I need to display a custom message to the user each time. For example if the first error is thrown the user should see: 'Please setup the project start date' and so on.
How can I do this ?
Just define your own exception class and your whole code in a try .. catch:
class FormException extends Exception {
private var $userMessage;
public function __construct($message, $userMessage) {
parent::__construct($message);
$this->userMessage = $userMessage;
}
public function getUserMessage() {return $this->userMessage;}
}
try {
// Whole code goes here, probably a function call
throw new FormException("Missing startDate attribute for project id: $id",
'Please setup the project start date');
} catch (FormException $e) {
echo $e->getUserMessage();
error_log($e->getMessage());
}
By the way, if you want to include variable contents in a string, either use double quotes ("id: $id") or concatenate ('id: ' . $id).
Try this:
try
{
$Message = '';
if ($project->startDate == false ) {
$Message = "Please setup the project start date\n";
throw new Exception("Missing startDate attribute for project id: $id");
}
if ($project->finishDate == false ) {
$Message = "Please setup the project finish date\n";
throw new Exception("Missing finishDate attribute for project id: $id");
}
if ($project->approved == false ) {
$Message = "Please setup the project approved field\n";
throw new Exception("Missing approved attribute for project id: $id");
}
}
catch(Exception $Ex)
{
// Log in some way you like the $Ex-getMessage();
echo nl2br($Message);
}
Inside your project class, create a new method, probably called getErrorMessage.
That function should do the checks (no need to have the concrete way of validation outside of project or create a validation object for project). Then:
if ($message = $project->getErrorMessage())
{
throw new Exception(sprintf('%s (project id: %d)', $message, $id));
}
If you decide to not throw exceptions for design reasons, this still is of use.
You gain more flexibility with a validator object that can naturally provide more detailed information than a single method. So it might be the better thing to do:
class ProjectValidator
{
private $project;
private $errors;
public function __construct($project)
{
$this->project = $project;
}
public function isValid()
{
// run your checks, add errors to the array as appropriate.
$errors = array();
if (!$this->project->startDate)
{
$errors[] = 'Missing startDate attribute';
}
if (!$this->project->finishDate)
{
$errors[] = 'Missing finishDate attribute';
}
if (!$this->project->approved)
{
$errors[] = 'Missing approved attribute';
}
$this->errors = $errors;
return (bool) count($this->errors);
}
public function getErrors()
{
return $this->errors;
}
}
$validator = new ProjectValidator($project);
if (!$validator->isValid())
{
// throw an exception or do whatever you want in case it's not valid
$errors = $validator->getMessages();
$message = sprintf("Project id: %d has the following %d error(s):\n", $id, count($errors));
foreach($errors as $index => $error)
{
$message .= sprintf("%d. %s\n", $index+1, $error);
}
throw new Exception($message);
}

Categories