detect if core flash messages in cakephp is an error or success message - cakephp

I have copied the SesionHelper from the core into myapp/View/Helper so I can alter the div structure around the message outputted.
My problem is that I cant seem to detect if the message is an error or success message from the default cakephp message. I know I can set a flash message in my controller and add an attribute. But there doesn't seem to be any extra data that I can see from the core messages.
Example if the data is saved to the database i wish to show the message as green. Or if the data could not be saved then as red message.
public function flash($key = 'flash', $attrs = array()) {
$out = false;
if (CakeSession::check('Message.' . $key)) {
$flash = CakeSession::read('Message.' . $key);
$message = $flash['message'];
unset($flash['message']);
if (!empty($attrs)) {
$flash = array_merge($flash, $attrs);
}
if ($flash['element'] === 'default') {
$class = 'message';
if (!empty($flash['params']['class'])) {
$class = $flash['params']['class'];
}
$out = '<div id="' . $key . 'Message" class="' . $class . '">' . $message . '</div>';
} elseif (!$flash['element']) {
$out = $message;
} else {
$options = array();
if (isset($flash['params']['plugin'])) {
$options['plugin'] = $flash['params']['plugin'];
}
$tmpVars = $flash['params'];
$tmpVars['message'] = $message;
$out = $this->_View->element($flash['element'], $tmpVars, $options);
}
CakeSession::delete('Message.' . $key);
}
return $out;
}

What you are doing is reinventing the wheel as far as CakePHP is concerned.
You can specify an element as the second argument when you set a flash message in your controller method:
$this->Session->setFlash('Your record has been saved', 'flash_success');
Then in elements create an element Element/flash_success.ctp like this:
<div class="alert-success"><?php echo $message;?></div>
And finally in your view:
<?php echo $this->Session->flash()?>
Here is the section that deals with this in detail from the official documentation:
http://book.cakephp.org/2.0/en/core-libraries/components/sessions.html#creating-notification-messages

Related

How to fetch all the coinbase pro transactions correctly in php

I have a question of coinbase pro,
How can I get all the orders/transactions from coinbase pro using php without any limit , or with any limit parameter.
I am using the following library to fetch all the coinbase pro orders , but it only gives me 100 orders from the below method.
fetch_orders
Here is the method,
$CoinbaseProtrans = $CoinbasePro->fetch_orders('ETH/USD',"",150,array('limit'=>100,'after'=>1));
echo "<pre>";print_r($CoinbaseProtrans);echo "</pre>";
Here is the error I am getting,
Fatal error: Uncaught ccxt\ExchangeError: coinbasepro after cursor value is not valid in coinbasepro.php:813
Here is the link of the library:
https://github.com/ccxt/ccxt/blob/master/php/coinbasepro.php
This question was answered here: https://github.com/ccxt/ccxt/issues/6105#issuecomment-552405563
<?php
include_once ('ccxt.php');
date_default_timezone_set ('UTC');
$exchange = new \ccxt\coinbasepro(array(
'apiKey' => 'YOUR_API_KEY',
'secret' => 'YOUR_SECRET',
// 'verbose' => true, // uncomment for debugging
// https://github.com/ccxt/ccxt/wiki/Manual#rate-limit
'enableRateLimit' => true, // rate-limiting is required by the Manual
));
$exchange->load_markets ();
// $exchange->verbose = true; // uncomment for debugging
$all_results = array();
$symbol = 'ETH/USD';
$since = null;
$limit = 100;
$params = array();
do {
// any of the following methods should work:
// $results = $exchange->fetch_orders($symbol, $since, $limit, $params);
// $results = $exchange->fetch_my_trades($symbol, $since, $limit, $params);
$results = $exchange->fetch_trades($symbol, $since, $limit, $params);
echo $exchange->iso8601($exchange->milliseconds());
echo ' fetched ' . count($results) . " results\n";
$all_results = array_merge ($all_results, $results);
if (count($results) > 0) {
$last = count($results) - 1;
echo ' last result ' . $results[$last]['id'] . ' ' . $results[$last]['datetime'] . "\n";
echo ' first result ' . $results[0]['id'] . ' ' . $results[0]['datetime'] . "\n";
} else {
break;
}
#$params['after'] = $exchange->last_response_headers['cb-after'][0];
// uncomment one of the following:
// } while (true); // fetch all results forever
} while (count($all_results) < 1000); // fetch up to 1000 results
echo "fetched " . count($all_results) . " results in total\n";
?>

JoomGallery.net | image ordering asc

i would like to use this simple image slider for the joomgallery for my art students:
https://github.com/danielhpavey/joomgallery-slider
the only problem is the ordering. how do i get an ascending image ordering by id and not by filename ?
thanks peter
<?php
class images
{
public function __construct()
{
$file = JPATH_ROOT. '/components/com_joomgallery/interface.php';
if(!file_exists($file)){
JError::raiseError(500, 'JoomGallery seems not to be installed');
} else {
require_once $file;
$this ->interface = new JoomInterface();
}
}
public function getFirstImage()
{
$images = $this ->talkToJoomgallery();
return $images[0];
}
public function getImages()
{
$images = $this ->talkToJoomgallery();
return $images;
}
public function talkToJoomgallery()
{
$images = $this ->interface ->getPicsByCategory( $this ->categoryid );
$imagepath = $this ->joomgalleryImagePath();
$theimages = array();
$c = 0;
foreach ($images as $i){
$theimages[$c]= array(
'imgpath' => JURI::base() . $imagepath . $i->catpath . '/' . $i->imgfilename
,'imgtitle' => $i->imgtitle
,'imgtext' => $i->imgtext
);
$c ++;
}
shuffle($theimages);
return $theimages;
}
private function joomgalleryImagePath()
{
return $this ->interface ->getJConfig( 'jg_pathoriginalimages' );
}
public function __set($property, $value){
$this->$property = $value;
}
}
Your images are loaded according to image id only but this command is reindexing the array i.e shuffle($theimages);
You can comment out that line by
//shuffle($theimages)
Also for ordering images you can change this line in helper.php file
$images = $this->interface->getPicsByCategory($this->categoryid);
to
$images = $this->interface->getPicsByCategory($this->categoryid,null,'ordering' );
This will do the ordering of images the way you did drag and drop of images at the joomla administrator backend.
UPDATE AS PER YOUR LATEST QUERY
Suppose you want to add a param value (sorting) that can be controlled through admin. You ned to change the xml file mod_joomgallery_slider.xml
Just add a new field like this
<field
name = "sorting"
type = "radio"
label = "Sorting"
description = "Sort by Ordering or random"
default = "ordering"
>
<option value = "ordering">Ordering</option>
<option value = "rand()">Random</option>
</field>
Next to get the param in helper.php file then change the function talkToJoomgallery() like this
public function talkToJoomgallery()
{
//Externally calling a module param
jimport( 'joomla.html.parameter' );
jimport( 'joomla.application.module.helper' );
$module = JModuleHelper::getModule('mod_joomgallery_slider');
$moduleParams = new JRegistry();
$moduleParams->loadString($module->params);
$sorting = $moduleParams->get( 'sorting' );
$images = $this ->interface ->getPicsByCategory( $this ->categoryid,null,$sorting );
$imagepath = $this ->joomgalleryImagePath();
$theimages = array();
$c = 0;
foreach ($images as $i){
$theimages[$c]= array(
'imgpath' => JURI::base() . $imagepath . $i->catpath . '/' . $i->imgfilename
,'imgtitle' => $i->imgtitle
,'imgtext' => $i->imgtext
);
$c ++;
}
//var_dump($theimages); exit;
//shuffle($theimages);
return $theimages;
}
UPDATE: To display 2 slider modules on a single page.
Some files needs to changed:
In mod_joomgallery_slider.php file change this line at top
include('helper.php');
To
include_once('helper.php');
This ensures that the file is included once.
Another change will be to remove the function imageText in default.php and including it in helper.php class else a function redeclaration error will be thrown. But now the default.php file still give error, as function imageText will be not defined, but you already added that function to helper.php. So default.php will only work if you change
echo imageText( $i, $params );
To
echo $image->imageText( $i, $params );// You are calling helper object
Remember to change in both if and else conditions.

JRequest::getVar is keeping previous values even after refreshing

I am writing a mail function as a module in joomla 3. e mail works fine, but when i reload the page and insert a different email and send, but it seemed to return the previous email by JRequest::getVar function. Is there a way to solve this issue? thanks in advance..
this is the code i used:
<?php
defined('_JEXEC') or die('Direct Access to this location is not allowed.');
require_once(dirname(__FILE__) . DS . 'helper.php');
//declaration
$input = JFactory::getApplication()->input;
$form_send = $input->get('form_send', 'notsend');
$fanme = $input->get('firstName');
$lname = $input->get('lastinput');
$email = $input->get('email', 0 , 'STRING');
$mail=false;
$emailexist=false;
echo '<script>
var php_var = "chk is first:'.$email.'";
alert(php_var);
</script>';
switch ($form_send) {
case 'send':
if ((is_null($fanme) || is_null($lname) || is_null($email)) || (!filter_var($email, FILTER_VALIDATE_EMAIL))) {
echo '<div> Fields are empty or not valid. <br></div>';
} else {
$mail = ModLittleContactHelper::SendMail($email, $fanme, $lname);
echo '<script>
var php_var = "chk when mail sending:'.$email.'";
alert(php_var);
</script>';
$input = JFactory::getApplication();//i have tried $app also
$input ->setUserState('mod_mycontact.email', null);
}
//echo $respond
if (!$mail) {
echo 'Error sending email:';
require(JModuleHelper::getLayoutPath('mod_myecontact', 'default_tmpl'));
}else{
require(JModuleHelper::getLayoutPath('mod_mycontact', 'sendok_tmpl'));
break;
}
default:
require(JModuleHelper::getLayoutPath('mod_littlecontact', 'default_tmpl'));
unset($var);
}
?>
#Mario this is the helper code:
class ModLittleContactHelper{
public function SendMail($email, $fname, $lname) {
$body = "<p style='font-family:arial;font-size:20px;'>Hi " . $fname . " " . $lname . ",</p>";
$body.="<p style='font-family:arial;font-size:20px;'>Welcome to Crowd Logistics! Please verify your email address below.</p><br/><br/>";
$body.= "<hr><br/>";
$body.= "<p style='align:center;background-color:#40B3DF;font-family:arial;color:#FFFFFF;font-size:20px;'><a href='http://suriyaarachchi.com/crowdlogistics/index.php?option=com_content&view=article&id=192' target='_blank'>Verify " . $email . "</a></p>";
$body.= "<br/><hr><br/>";
$body.="<p style='text-align:right;font-family:arial;font-size:20px;'>Or, paste this link into your browser:<br/>";
$body.= "http://crowdlogistics/index.php?option=com_content&view=article&id=192<br/><br/>";
$body.= "Thanks.<br/>";
$body.= "CrowdLogistics</p><br/>";
$mailer = & JFactory::getMailer();
$mailer->setSender('info#crowdlogistics.com');
$mailer->addRecipient($email);
$mailer->setSubject('Mail from CrowdLogistics - Confirm your email');
$mailer->setBody($body);
$mailer->IsHTML(true);
$send = & $mailer->Send();
return $send;
}
Since you're trying to run your code on Joomla 3, there are a few things that are wrong. Below os your code, corrected where I was able to correct it. Now you have to test it in your module environment with the class being instantiated (in other words, test the below code in your module).
<?php
defined('_JEXEC') or die('Direct Access to this location is not allowed.');
require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'helper.php');
//declaration
$doc = JFactory::getDocument();
$app = JFactory::getApplication();
$input = $app->input;
$form_send = $input->get('form_send', 'notsend');
$fanme = $input->get('firstName');
$lname = $input->get('lastinput');
$email = $input->get('email', 0 , 'STRING');
$mail=false;
$emailexist=false;
$doc->addScriptDeclaration('
var php_var = "chk is first:'.$email.'";
alert(php_var);
');
switch ($form_send) {
case 'send':
if ((is_null($fanme) || is_null($lname) || is_null($email)) || (!filter_var($email, FILTER_VALIDATE_EMAIL))) {
echo '<div> Fields are empty or not valid. <br></div>';
} else {
$mail = ModLittleContactHelper::SendMail($email, $fanme, $lname);
$doc->addScriptDeclaration('
var php_var = "chk when mail sending:'.$email.'";
alert(php_var);');
$app->setUserState('mod_littlecontact.email', null);
}
//echo $respond
if (!$mail) {
echo 'Error sending email:';
require(JModuleHelper::getLayoutPath('mod_littlecontact', 'default_tmpl'));
break;
}else{
require(JModuleHelper::getLayoutPath('mod_littlecontact', 'sendok_tmpl'));
break;
}
default:
require(JModuleHelper::getLayoutPath('mod_littlecontact', 'default_tmpl'));
unset($var);
}
?>
First, JRequest class is deprecated in J3. You should use JInput:
$input = JFactory::getApplication()->input;
$your_var = $input->get('your_var');
Then, regarding the email, you probably need to unset the session variables when the success is achieved (mail sent), or in other words, when you don't need them any longer.
$app = JFactory::getApplication();
// your_var is the variable you want to unset
$app->setUserState('mod_your_module.your_var', null);
Hope it helps
you can use this code
$email = $input->get('email', 0 , 'STRING','');
4th argument for the default value,

How can I convert validation error field names to input names in CakePHP?

I have a CakePHP (latest version) web app with forms and validation all working properly using traditional postback, but now I'm switching some of the forms to submit via ajax. When there are validation errors, I would like to get them back on the client as JSON formatted like so:
{
"success":false,
"errors":{
"data[User][username]":["This is not a valid e-mail address"],
"data[User][password]":["You must choose a password"]
}}
The keys for the errors array need to correspond to the name attribute on the form fields. We have some prebuilt client script that is expecting JSON formatted in this way. The good news is that this is very close to what the validationErrors object looks like in CakePHP. So I'm currently doing this in my controller:
if ($this->User->save($this->request->data)) {
} else {
if ($this->request->is('ajax')) {
$this->autoRender = $this->layout = false;
$response['success'] = false;
$response['errors'] = $this->User->validationErrors;
echo json_encode($response);
exit(0);
}
}
However, this is what the JSON response looks like:
{
"success":false,
"errors":{
"username":["This is not a valid e-mail address"],
"password":["You must choose a password"]
}}
Note that the errors keys have just the basic database table field names in them. They are not converted into data[User][username] format, which the FormHelper usually takes care of.
Is there some easy way to adjust the array before I return it? I don't want to simply loop through and prepend "data[User]" because that is not robust enough. I'd like some code I can put in one place and call from various controllers for various models. What does FormHelper use to come up with the input name attributes? Can I tap into that? Should I somehow use a JSON view?
That's because that's the way the $validationErrors array is formatted. To obtain the output you want you will have to loop through, there's no way around it.
foreach ($this->User->validationErrors as $field => $error) {
$this->User->validationErrors["data[User][$field]"] = $error;
unset($this->User->validationErrors[$field]);
}
I would suggest instead passing all errors to json_encode(). $this->validationErrors is a combined list of all model validation errors for that request available on the view (compiled after render). You should move your display logic (echoing json) into your view, and loop through it there.
in the view
$errors = array();
foreach ($this->validationErrors as $model => $modelErrors) {
foreach ($modelErrors as $field => $error) {
$errors["data[$model][$field]"] = $error;
}
}
$response['errors'] = $errors;
echo json_encode($response);
This would output something like this:
{
"success":false,
"errors": [
"data[User][username]": "This is not a valid e-mail address",
"data[User][password]": "This is not a valid password",
"data[Profile][name]": "Please fill in the field"
]
}
I have created a small recursive function to create validation error as a string with column name so that can be passed as json object.
/**
* prepare erorr message to be displayed from js
*
* #param array $errors validation error array
* #param stringn $message refernce variable
*
* #return void
*/
public function parseValidationErrors($errors, &$message)
{
foreach ($errors as $columnName => $error) {
$message .= "<strong>$columnName:</strong> ";
foreach ($error as $i => $msg) {
if (is_array($msg)) {
$this->_parseValidationErrors($msg, $message);
} else {
$message .= str_replace("This field", "", $msg . " ");
isset($error[$i + 1]) ? $message .= " and " : $message;
}
}
}
}
and controller code goes like this.
if (!$this->YourModel->saveAll($modelObject)) {
$errors = $this->YourModel->validationErrors;
$message = '';
$this->parseValidationErrors($errors, $message);
$response = array('status' => 'error', 'message' => $message);
}
$response['errors']['User'] = $this->User->validationErrors;

Why I can't get values from this web service Array?

Can't figure out why this web service don't work. Just gives me blank. I tested the url and the data it's all there.
http://onleague.stormrise.pt:8031/OnLeagueRest/resources/onleague/News/News?id_user=a7664093-502e-4d2b-bf30-25a2b26d6021&page=1&new_filter=0
my code:
session_start();
function getNews() {
$json = file_get_contents('http://onleague.stormrise.pt:8031/OnLeagueRest/resources/onleague/News/News?id_user=a7664093-502e-4d2b-bf30-25a2b26d6021&page=1&new_filter=0');
$data = json_decode($json, TRUE);
$newst = array();
foreach($data['data']['item'] as $item) {
$newst[] = $item;
}
foreach($newst as $v)
{
$_SESSION['newsid'][] = $v['id'];
$_SESSION['newstitle'][] = $v['title'];
$_SESSION['newstext'][] = $v['news'];
$_SESSION['newslink'][] = $v['link'];
$_SESSION['newsdate'][] = $v['date'];
$_SESSION['newsentityName'][] = $v['entityName'];
$_SESSION['aclikes'][] = $v['account']['likes'] . ")";
$_SESSION['acdislikes'][] = $v['account']['dislikes'] . ")";
$_SESSION['accomentes'][] = $v['account']['commentes'] . ")";
$_SESSION['acshares'][] = $v['account']['shares'] . ")";
$_SESSION['acclicks'][] = $v['account']['clicks'] . ")";
}
}
getNews();
$key = count($_SESSION['newsid']);
for ($i = 0; $i <= $key; $i++) {
echo $_SESSION['newsid'][$i] . "<br />";
}
Are you sure that this line is correct:
foreach($data['data']['item'] as $item) {
$newst[] = $item;
}
Reading this makes me think that you are overwriting the entire $newst array with a single item... for each item. Thus the array will end up being the value of the last $item (which might be empty).
I'd expect something like:
foreach($data['data']['item'] as $item) {
$newst.push( $item );
}
(note, not tested and my syntax may be dodgy... but you get the drift).

Resources