JRequest::getVar is keeping previous values even after refreshing - joomla3.0

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,

Related

Cant fix my if-else condition in login.php

I have created a condition to check if name and password are correct the only issue here is when i test it it goes complete the opposite of what i want. It doesnt matter if i put it right or wrong the message will always be "You have successfuly logged in". Im using PDO just to know
<?php
include('connection.php');
$name = $_POST['name'];
$password = $_POST['password'];
$data = $_POST;
$statment = $connection->prepare('SELECT * FROM registration WHERE name = :name AND password = :password');
if($statment){
$result = $statment->execute([
':name' => $data['name'],
':password' => $data['password']
]);
}
if($data['name'] == $name && $data['password'] == $password){
echo 'You have successfuly logged in';
}else {
die('Incorrect username or password');
}
?>
You have made your script overly complicated .. The easiest way is to bind and execute .. Then you can simply check if there are any rows, and THEN compare with your data array created from the executed statement.
<?php
include('connection.php');
$name = $_POST['name'];
$password = $_POST['password'];
$statment = $connection->prepare("SELECT name, password FROM registration
WHERE name = ? AND password = ?");
$statment ->bind_param("ss", $name, $password);
$statment ->execute();
$result = $stmt->get_result();
if ($result ->num_rows > 0) {
$data = $result->fetch_array();
}else{
echo "No results found";
}
if($data['name'] == $name && $data['password'] == $password){
echo 'You have successfuly logged in';
}else {
die('Incorrect username or password');
}
?>
(bear in mind I wrote that freehand, and it has not been tested or debugged, but the principals are there)
ON A SIDE NOTE
That being said .. You should never be storing passwords in a open "text" field. You should be encrypting them. The easiest way is to use bcrypt to build out a hash:
$options = [
'cost' => 12,
];
$newPass = password_hash($pass, PASSWORD_BCRYPT, $options);
And store that in your database .. Then you can compare it like so ..
if (password_verify($pss, $pwdCheck)
$pss being what was sent in from the form .. and $pwdCheck being the hash you SELECTED from the database -- Brought into your current code set, would look something like:
if($data['name'] == $name && password_verify($password, $data['password']){

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";
?>

How to pass data into a Listener when using Guzzle?

I am using Guzzle 3.8.1 with CakePHP 2.5.6 and I am making a call to the Box API. I would like to be able to refresh my access token when it expires. The issue I am encountering is that I may be using any one of N possible access tokens and I want to be able to use the $account_id that is in scope for the function I am defining this in. I don't see how I can pass it into the Listener defined function, since I am not calling that myself. I do see that the expired access_token exists in the $event variable, but I would have to locate it and then parse it from the header that I am passing to Box. I think I could add a custom header containing the account_id, but that seems like a bad way to approach the problem. Can I somehow specify a variable in the request that wouldn't be added as part of the call to Box? Any suggestions are much appreciated, thanks!
`
public function get_folder_list ($account_id = null, $parent_folder_id = null) {
// Get account
$this->Account = ClassRegistry::init('Account');
$account = $this->Account->findById($account_id);
$this->Account->log($account);
// If account doesn't exist, throw error
if(empty($account)) {
throw new NotFoundException(__('Account id not found: ' . $account_id));
}
// Call Box for folder list
$box_url = "https://api.box.com/2.0/folders/";
if (empty($parent_folder_id)) {
$box_url .= "0";
} else {
$box_url .= $parent_folder_id;
}
$this->Account->log($box_url);
$bearer = 'Bearer ' . $account['Account']['access_token'];
$client = new Guzzle\Http\Client();
$client->getEventDispatcher()->addListener('request.error', function(Event $event) {
if ($event['response']->getStatusCode() == 401) {
$Account = new Account;
$Account->log($event);
$Box = new BoxLib;
$account = $Box->refresh_token($account_id);
$bearer = 'Bearer ' . $account['Account']['access_token'];
$request = $client->get($box_url, array('Authorization' => $bearer));
$event['response'] = $newResponse;
$event->stopPropagation();
}
});
$request = $client->get($box_url, array('Authorization' => $bearer));
try {
$response = $request->send();
} catch (Guzzle\Http\Exception\BadResponseException $e) {
// HTTP codes 4xx and 5xx throw BadResponseException
$this->Account->log('Service exception!');
$this->Account->log('Uh oh! ' . $e->getMessage());
$this->Account->log('HTTP request URL: ' . $e->getRequest()->getUrl() . "\n");
$this->Account->log('HTTP request: ' . $e->getRequest() . "\n");
$this->Account->log('HTTP response status: ' . $e->getResponse()->getStatusCode() . "\n");
$this->Account->log('HTTP response: ' . $e->getResponse() . "\n");
}
$this->Account->log($response->json());
$json = $response->json();
$folder_list = array();
foreach ($json['item_collection']['entries'] as $folder) {
$folder_list[$folder['id']] = $folder['name'];
}
//$this->Account->log($folder_list);
return $folder_list;
}
`

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

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

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