I am using Moodle version 3.8.4+ and PHP version 7.2.33 . Today I noticed a strange issue when I was trying to send a message to students, the message was:
Coding error detected, it must be fixed by a programmer: Url parameters values can not be arrays! More information about this error
I purge all caches as the suggestion was on "more information" section but it did not work.
I run the same Moodle version and PHP version on non production environment with the debugging mode and then I got this error message:
Coding error detected, it must be fixed by a programmer: Url parameters values can not be arrays!
More information about this error
Debug info:
Error code: codingerror
Stack trace:
line 405 of /lib/weblib.php: coding_exception thrown
line 460 of /lib/weblib.php: call to moodle_url->params()
line 49 of /mod/reservation/messageselect.php: call to moodle_url->param()
Output buffer: Invalid array parameter detected in required_param(): messagebody
line 655 of /lib/moodlelib.php: call to debugging()
line 30 of /mod/reservation/messageselect.php: call to optional_param()
The messageselect.php file is this but I am not able to see any issues here:
require_once('../../config.php');
require_once($CFG->dirroot.'/message/lib.php');
$id = required_param('id', PARAM_INT);
$messagebody = optional_param('messagebody', '', PARAM_CLEANHTML);
$send = optional_param('send', '', PARAM_BOOL);
$preview = optional_param('preview', '', PARAM_BOOL);
$edit = optional_param('edit', '', PARAM_BOOL);
$returnto = optional_param('returnto', new moodle_url('/mod/reservation/view.php', array('id' => $id)), PARAM_LOCALURL);
$format = optional_param('format', FORMAT_MOODLE, PARAM_INT);
$deluser = optional_param('deluser', 0, PARAM_INT);
if (isset($id)) {
if (! $cm = get_coursemodule_from_id('reservation', $id)) {
error('Course Module ID was incorrect');
}
if (! $course = $DB->get_record('course', array('id' => $cm->course))) {
error('Course is misconfigured');
}
}
$url = new moodle_url('/mod/reservation/messageselect.php', array('id' => $id));
if ($messagebody !== '') {
$url->param('messagebody', $messagebody);
}
if ($send !== '') {
$url->param('send', $send);
}
if ($preview !== '') {
$url->param('preview', $preview);
}
if ($edit !== '') {
$url->param('edit', $edit);
}
if ($returnto !== '') {
$url->param('returnto', $returnto);
}
if ($format !== FORMAT_MOODLE) {
$url->param('format', $format);
}
if ($deluser !== 0) {
$url->param('deluser', $deluser);
}
$modulecontext = context_module::instance($cm->id);
$PAGE->set_url($url);
$PAGE->set_context($modulecontext);
require_login($course->id, false, $cm);
$coursecontext = context_course::instance($course->id);
$systemcontext = context_system::instance();
require_capability('moodle/course:bulkmessaging', $coursecontext);
if (empty($SESSION->reservation_messageto)) {
$SESSION->reservation_messageto = array();
}
if (!array_key_exists($id, $SESSION->reservation_messageto)) {
$SESSION->reservation_messageto[$id] = array();
}
if ($deluser) {
$idinmessageto = array_key_exists($id, $SESSION->reservation_messageto);
if ($idinmessageto && array_key_exists($deluser, $SESSION->reservation_messageto[$id])) {
unset($SESSION->reservation_messageto[$id][$deluser]);
}
}
if (empty($SESSION->reservation_messageselect[$id]) || $messagebody) {
$SESSION->reservation_messageselect[$id] = array('messagebody' => $messagebody);
}
$messagebody = $SESSION->reservation_messageselect[$id]['messagebody'];
$count = 0;
if ($data = data_submitted()) {
require_sesskey();
foreach ($data as $k => $v) {
if (preg_match('/^(user|teacher)(\d+)$/', $k, $m)) {
if (!array_key_exists($m[2], $SESSION->reservation_messageto[$id])) {
$returnfields = 'id,firstname,lastname,idnumber,email,mailformat,lastaccess, lang, maildisplay';
if ($user = $DB->get_record_select('user', "id = ?", array($m[2]), $returnfields)) {
$SESSION->reservation_messageto[$id][$m[2]] = $user;
$count++;
}
}
}
}
}
$strtitle = get_string('message', 'reservation');
$PAGE->navbar->add($strtitle);
$PAGE->set_title($strtitle);
$PAGE->set_heading($strtitle);
echo $OUTPUT->header();
// If messaging is disabled on site, we can still allow users with capabilities to send emails instead.
if (empty($CFG->messaging)) {
echo $OUTPUT->notification(get_string('messagingdisabled', 'message'));
}
if ($count) {
if ($count == 1) {
$heading = get_string('addedrecip', 'moodle', $count);
} else {
$heading = get_string('addedrecips', 'moodle', $count);
}
echo $OUTPUT->heading($heading);
}
if (!empty($messagebody) && !$edit && !$deluser && ($preview || $send)) {
require_sesskey();
if (count($SESSION->reservation_messageto[$id])) {
if (!empty($preview)) {
echo '<form method="post" action="messageselect.php" style="margin: 0 20px;">
<input type="hidden" name="returnto" value="'.s($returnto).'" />
<input type="hidden" name="id" value="'.$id.'" />
<input type="hidden" name="format" value="'.$format.'" />
<input type="hidden" name="sesskey" value="' . sesskey() . '" />
';
echo "<h3>".get_string('previewhtml')."</h3>";
echo "<div class=\"messagepreview\">\n".format_text($messagebody, $format)."\n</div>\n";
echo '<p align="center"><input type="submit" name="send" value="'.get_string('sendmessage', 'message').'" />'."\n";
echo '<input type="submit" name="edit" value="'.get_string('update').'" /></p>';
echo "\n</form>";
} else if (!empty($send)) {
$fails = array();
foreach ($SESSION->reservation_messageto[$id] as $user) {
if (!message_post_message($USER, $user, $messagebody, $format)) {
$user->fullname = fullname($user);
$fails[] = get_string('messagedselecteduserfailed', 'moodle', $user);
};
}
if (empty($fails)) {
echo $OUTPUT->heading(get_string('messagedselectedusers'));
unset($SESSION->reservation_messageto[$id]);
unset($SESSION->reservation_messageselect[$id]);
} else {
echo $OUTPUT->heading(get_string('messagedselectedcountusersfailed', 'moodle', count($fails)));
echo '<ul>';
foreach ($fails as $f) {
echo '<li>', $f, '</li>';
}
echo '</ul>';
}
echo '<p align="center">'.get_string('backtoparticipants').'</p>';
}
echo $OUTPUT->footer();
exit;
} else {
echo $OUTPUT->notification(get_string('nousersyet'));
}
}
echo '<p align="center">'.get_string("keepsearching").''.
((count($SESSION->reservation_messageto[$id])) ? ', '.get_string('usemessageform') : '').'</p>';
if ((!empty($send) || !empty($preview) || !empty($edit)) && (empty($messagebody))) {
echo $OUTPUT->notification(get_string('allfieldsrequired'));
}
if (count($SESSION->reservation_messageto[$id])) {
require_sesskey();
require("message.html");
}
$PAGE->requires->yui_module('moodle-core-formchangechecker',
'M.core_formchangechecker.init',
array(array(
'formid' => 'theform'
))
);
$PAGE->requires->string_for_js('changesmadereallygoaway', 'moodle');
echo $OUTPUT->footer();
```php
It looks like the massagebody param in the request that initiates this process is using array syntax, like ?messagebody[]=foo instead of ?messagebody=foo, so the error is in whatever page the request originated from. You can either try to figure out why that is and change it, or make a change to this messageselect.php file to flatten the parameter. To do that you would change this:
<?php
if ($messagebody !== '') {
$url->param('messagebody', $messagebody);
}
to this:
<?php
if ($messagebody !== '') {
if(is_array($messagebody))
{
$messagebody = array_shift($messagebody);
}
$url->param('messagebody', $messagebody);
}
However be aware that if the page is sending this parameter as an array, it is quite likely that others will be sent that way as well. Usually you would send parameters using array syntax so that multiple records can be processed in one request, so that messagebody[1] would correlate to format[1], messagebody[2] would correlate to format[2], and so on. The code in messageselect.php is clearly not expecting this. I would be interested to find out what the story is for the page that sends requests here.
Related
The environment is MAMP, PHP version is 7.1.19.
We are assuming a contact form on the landing page that we do not use framework etc.
Because the code is long, the part which does not correspond to the question content is deleted
Below, select an image in form.html, push "submit" to "Confirmation screen", then display the image data in $ _FILES in the log to add the code of the image upload processing in confirm.php I want to.
However, even if you try to display the contents of $ _FILES in the log file with error_log ('confirm-files:'. Print_r ($ _ FILES, true), '0'); Array () I can not see the contents. By the way, file name is displayed in $ _POST.
Please tell us why the contents of $ _ FILES can not be seen.
After that, save the database as a tmp file on the server without using the database, after the transition to thanks.php, we will add the process to register to the customer management system.
Thank you.
・contact form
<form method="post" action="<?=$sfm_script?>" class="form" enctype="multipart/form-data">
<div class="file">
<label for="file1">Select files
<input type="file" id="file1" name="file1" onchange="$('.file_name1').text($(this).val())" class="file_name1"></label><span class="file_name1">
</div>
<button type="submit">To confirmation screen</button>
<input type="hidden" name="mailToNum" id="mailToNum" value="3">
<input type="hidden" name="autoReply" id="autoReply" value="1">
<input type="hidden" name="mode" id="mode" value="CONFIRM">
<?php if (array_key_exists('pram', $formvalue)):?>
<input type="hidden" name="pram" id="pram" value="<?=$formvalue['pram']?>">
<?php else:?>
<input type="hidden" name="pram" id="pram" value="">
<?php endif; ?>
</form>
・confirm.php
<?php header("Content-type: text/html; charset=utf-8") ?>
<?php
include_once('config.php');
if (!extension_loaded('mbstring')) {
Err('mbstring');
}
$internalEnc = 'UTF-8';
mb_language('ja');
mb_internal_encoding($internalEnc);
// main
if (!isset($mailTo[0])) {
Err('mailaddress');
}
$mode = (isset($_POST['mode'])) ? $_POST['mode'] : '';
error_log ('confirm-files:' . print_r($_FILES,true), '0');
switch ($mode) {
case 'SEND':
session_cache_limiter('nocache');
session_start();
//Om
include_once('thanks.html');
break;
case 'CONFIRM':
if ($_SERVER['HTTP_REFERER'] != 'http://'.$_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] && $refCheck) {
Err('It can not be used from outside');
}
session_cache_limiter('nocache');
session_start();
unset($_SESSION['SFM']);
$error = $email = '';
foreach ($_POST as $key => $value) {
if (is_array($value)) {
$value = implode("\t", $value);
}
if (!$ill_slash) {
$value = (!get_magic_quotes_gpc()) ? addslashes($value) : $value;
}
if (!$ill_char) {
$value = mb_convert_encoding($value, $internalEnc, $baseEnc);
}
$value = mb_convert_kana($value, 'KV', $internalEnc);
$name = preg_replace('/(.+)_i$/', "$1", $key);
if (preg_match('/_i$/', $key) && $value == '') {
$_SESSION['SFM'][$name] = '::INPUT ERROR::';
$error = 1;
} elseif ($name == 'email' && $value) {
if (!preg_match("/^[\w\-\.\+]+\#[\w\-\.]+\.([a-z]+)$/", $value)) {
$_SESSION['SFM']['email'] = '::EMAIL ERROR::';
$error = $email = 1;
} else {
$_SESSION['SFM']['email'] = $email = $value;
}
} elseif ($name == 'emailcheck') {
if ($email != 1 && $email != $value) {
$_SESSION['SFM']['email'] = '::EMAIL CHECK ERROR::';
$error = 1;
}
} elseif ($maxText && strlen($value) > $maxText) {
$_SESSION['SFM'][$name] = '::MAXTEXT ERROR::';
$error = 1;
} else {
$_SESSION['SFM'][$name] = $value;
}
}
$_SESSION['SFM']['InputErr'] = $error;
//$sfm_script = $script_name . ((SID) ? '?'.strip_tags(SID) : '');
$sfm_script = "thanks.php";
include_once('confirm.html');
break;
default:
session_cache_limiter('private_no_expire');
session_start();
unset($_SESSION['SFM']);
//$sfm_script = $script_name;
$sfm_script = "confirm.php";
include_once('form.html');
}
exit;
function FORM_DATA_H($name) {
$errArray = array(
'::INPUT ERROR::' => '<span class="req">Required</span>',
'::EMAIL ERROR::' => 'E-mail address is invalid',
'::EMAIL CHECK ERROR::' => 'Mail address does not match',
'::MAXTEXT ERROR::' => 'Too many characters (upper limit ' . number_format($GLOBALS['maxText']) . ')'
);
$value = (isset($_SESSION['SFM'][$name])) ? $_SESSION['SFM'][$name] : '';
$value = (get_magic_quotes_gpc()) ? stripslashes($value) : $value;
$value = str_replace("\t", "\n", $value);
$value = nl2br(htmlspecialchars($value, ENT_QUOTES, 'UTF-8'));
$value = (preg_match('/::.+::/', $value)) ? '<span class="ERR">' . $errArray[$value] . '</span>' : $value;
$value = ($value != '') ? $value : ' ';
return mb_convert_encoding($value, $GLOBALS['baseEnc'], $GLOBALS['internalEnc']);
}
?>
・$_FILES log
[10-Mar-2019 09:15:55 Asia/Tokyo] files:Array
(
)
・Upload process I want to add in the future
foreach ($_FILES as $key => $file) {
if ($file['size'] > 0) {
$time = strtotime('today');
if (!file_exists('./files/' . $time)) {
mkdir('./files/' . $time);
chmod('./files/' . $time, 0777);
}
$tmp_name = str_replace('/Applications/MAMP/tmp/php', '', $file['tmp_name']);
move_uploaded_file($file['tmp_name'], './files/' . $time . $tmp_name);
$_FILES[$key]['tmp_name'] = './files/' . $time . $tmp_name;
}
}
Your issue is very well documented and, if I bothered to look for an instance your question should be closed as a duplicate of the many times this has been asked and answered here. You haven't set the form encoding so it is defaulting to URL encoding.
It should be enctype="multipart/form-data"
Here is my code which works well:
<?php
if(isset($_POST['btn'])){
$search=$_POST['search'];
require_once('Apache/Solr/Service.php');
$solr=new Apache_Solr_Service( 'localhost', '8983', '/solr' );
$offset = 0;
$limit = 10;
$queries = array(
'title:*'.$search.'*'
);
foreach ($queries as $query) {
$response = $solr->search($query, $offset, $limit);
if ($response->getHttpStatus() == 200) {
// print_r( $response->getRawResponse() );
if ($response->response->numFound > 0) {
foreach ($response->response->docs as $doc) {
echo '<pre>';
echo 'title ='.$doc->title;
echo '<br>';
echo 'image='.$doc->image;
echo '</pre>';
}
echo '<br />';
}
} else {
echo $response->getHttpStatusMessage();
}
}
}
?>
It searches for what $_POST['search'] is. But I want to use something named Solr Client. Because it has a method named $solrQuery->set('spellcheck','true'); that gives you the "did you mean x ?" feature.
I've followed this from the doc with no success. It throws SolrClient class not found.
Any clue how can I use SolrClient and what's its different with Apache_Solr_Service ?
I'm a complete newb in PHP, and the only reason I got this far was because I was trying to guess what everything does. I guess I was lucky that it worked this far.
So basically, I'm using the PHP Wake On LAN code that I found here to make a simple page that I log into, to remotely turn on my computer. I decided to add a username, rather than just a password, so maybe I could have multiple users. I've done everything successfully so far except one thing. When I log in, check my computer, and hit "Wake all selected", it logs me out immediately and doesn't send the magic packet. Any tips on what I could change to fix this? As soon as I remove the 'and' and the username bit in the if statement that checks for both user and pass to be correct, it works. But then there's no user and pass verifying going on. The if statement I'm talking about is the second if under the === Test for password protection === part.
You can demo the code on my site to see the issue in action here: http://trivisionzero.com/wol/
Just use 'user', 'pass'. (to recreate it, select any computer and press wake button)
Full code so far:
<center>
<br><br><br><br><br>
<?php
/* ============================== Configuration settings ====================================== */
/* List of PCs that may be woken */
$config_network_data_array[] = array("name" => "Shane-EPC", "MAC" => "changed for security", "IP" => "changed for security", "WakeIP" =>
"changed for security");
$config_network_data_array[] = array("name" => "Demo", "MAC" => "changed for security", "IP" => "changed for security", "WakeIP" =>
"changed for security");
$config_network_data_array[] = array("name" => "Demo", "MAC" => "changed for security", "IP" => "changed for security", "WakeIP" =>
"changed for security");
// Port number where the computer is listening. Usually, any number between 1-50000 will do. Normally people choose 7 or 9.
$socket_number = "7";
$my_password = 'pass';
$my_username = 'user';
$html_title = '<H2>TrivisionZero PC Waker</H2>';
$config_table_columns = array('name', 'IP', 'MAC', 'links');
# The following function is copied (with some edits, to suppress output and return TRUE or an error message) from:
# http://www.hackernotcracker.com/2006-04/wol-wake-on-lan-tutorial-with-bonus-php-script.html
# Wake on LAN - (c) HotKey#spr.at, upgraded by Murzik
# Modified by Allan Barizo http://www.hackernotcracker.com
flush();
function WakeOnLan($addr, $mac,$socket_number) {
$separator = ':';
if (strstr ( $mac, '-' ) ) {
$separator = '-';
}
$addr_byte = explode($separator, $mac);
$hw_addr = '';
for ($a=0; $a <6; $a++) $hw_addr .= chr(hexdec($addr_byte[$a]));
$msg = chr(255).chr(255).chr(255).chr(255).chr(255).chr(255);
for ($a = 1; $a <= 16; $a++) $msg .= $hw_addr;
// send it to the broadcast address using UDP
// SQL_BROADCAST option isn't help!!
$s = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
if ($s == false) {
// echo "Error creating socket!\n";
// echo "Error code is '".socket_last_error($s)."' - " . socket_strerror(socket_last_error($s));
return "Error creating socket!\nError code is '".socket_last_error($s)."' - " . socket_strerror(socket_last_erro
($s));
// return FALSE;
}
else {
// setting a broadcast option to socket:
$opt_ret = socket_set_option($s, 1, 6, TRUE);
if($opt_ret <0) {
// echo "setsockopt() failed, error: " . strerror($opt_ret) . "\n";
return "setsockopt() failed, error: " . strerror($opt_ret) . "\n";
// return FALSE;
}
if(socket_sendto($s, $msg, strlen($msg), 0, $addr, $socket_number)) {
// echo "Magic Packet sent successfully!";
socket_close($s);
return TRUE;
}
else {
// echo "Magic packet failed!";
return "Magic packet failed!";
// return FALSE;
}
}
}
/* ============================== some predefined texts ====================================== */
$display_sent = 'Magic Packet sent successfully!';
$button_text = 'Wake!';
$button_text2 = 'Wake all selected';
//this is where I added my username part
$username_element = "<P>Username: <input type=\"text\" name=\"username\" />";
$password_element = "<P>Password: <input type=\"password\" name=\"password\" /><input type=\"submit\" name=\"submit\" value = \"Login\" />";
$table_html = "<TABLE border=\"2\">\n";
$logout_html = '';
/* ========================= Test for password protection ==================================== */
$wake_MAC_array = array();
if (!isset ($_POST['logout'])) {
$input_password = $_POST['password'];
$input_username = $_POST['username'];
}
//($my_password === '') is if you want no password
if (($input_password === $my_password) and ($input_username === $my_username)) {
$logged_in = TRUE;
$hidden_login = "<input type=\"hidden\" name=\"password\" value=\"$my_password\"/>";
if ($my_password !== '') {
$logout_html = "\n<P><input type=\"submit\" name=\"logout\" value=\"Log Out\"/>\n";
}
if ( (isset ($_POST['tickbox'])) and (is_array($_POST['tickbox']) ) ) {
$checkbox_array = $_POST['tickbox'];
foreach ($checkbox_array as $mac_address => $tickbox_setting) {
$wake_MAC_array[$mac_address] = $tickbox_setting;
}
}
} else {
$logged_in = FALSE;
$hidden_login = '';
$table_html_user = $username_element;
$table_html = $password_element;
}
/* ================================ LOGGED-IN users only ===================================== */
/* ======================= construct table for listing of devices ============================ */
if ($logged_in == TRUE) {
$table_row = "\n<TR>";
foreach ($config_table_columns as $key => $column_heading) {
$table_row .= '<TD>' . $column_heading . '</TD>';
}
$table_row .= '<TD>Wake Up!</TD>';
$table_row .= '<TD>status</TD>';
$table_html .= $table_row . "</TR>\n";
foreach ($config_network_data_array as $device_key => $device_values) {
$table_row = "\n<TR>";
$mac = $device_values['MAC'];
$device_name = $device_values['name'];
$status_cell = '<TD> </TD>';
foreach ($config_table_columns as $key => $column_heading) {
if (isset ( $device_values[$column_heading])) {
$value = $device_values[$column_heading];
if ($column_heading == 'MAC') {
/* special coding for MAC address column; prepare clickable button */
$this_MAC = $value;
$value = "<input type=\"submit\" name=\"wake_MAC\" value = \"$value\" />";
if (( $_POST['wake_MAC'] === $this_MAC ) or (array_key_exists ($this_MAC,
$wake_MAC_array))) {
$status = WakeOnLan ($device_values['WakeIP'], $this_MAC, $socket_number) ;
if ( $status === TRUE ) {
$status = $display_sent;
}
$status_cell = "<TD>$status</TD>";
}
}
} elseif ($column_heading == 'links') {
/* special coding for links column; prepare clickable links from $config_network_links_array */
$value = '';
if (isset ( $config_network_links_array[$device_name])) {
foreach ($config_network_links_array[$device_name] as $link_title => $link_URL) {
if ( $value !== '') {
$value .= '<BR />';
}
$value .= '' . $link_title . '';
}
}
} else {
$value = '';
}
if ($value === '') {
$value = ' ';
}
$table_row .= '<TD>' . $value . '</TD>';
}
/* now add a checkbox to wake up this device */
$table_row .= '<TD>' . "<input type=\"checkbox\" name=\"tickbox[$this_MAC]\" />" . '</TD>';
/* now add the status message (if applicable) for the attempt to send a packet to this device */
$table_row .= $status_cell;
$table_html .= $table_row . "</TR>\n";
}
$table_html .= "</TABLE>\n";
$table_html .= "<P><input type=\"submit\" name=\"wake all\" value = \"$button_text2\" />\n";
}
/* =========================================================================================== */
/* ======================= Now output the html that we've built ============================== */
echo $html_title;
echo "<FORM name=\"input\" action=\"" .$_SERVER['PHP_SELF'] . "\" method=\"post\">";
echo '<P>';
echo $table_html_user;
echo $table_html;
echo $hidden_login;
echo $logout_html;
echo "</FORM>\n";
?>
</center>
When you are logged in and then submit the form to wake a machine, you are passing the password in a hidden field, but not the username.
As you are not passing the username, $input_username = null and thus the check if (($input_password === $my_password) and ($input_username === $my_username)) becomes if (('pass' === 'pass') and (null === 'user')) which is false and this is why you get logged out.
Function fn_redirect($url,true,true) not working when iam adding it in new addon in cscart that i have created. I have added use Tygh\Registry;. But why its not working?
In my buy now addon, im calling fn_redirect in the buy_now.php (controller). It is doing the same functionality as addtocart. But it has to redirected to checkout page after the item is added to cart.
if ($mode == 'add') {
if (empty($auth['user_id']) && Registry::get('settings.General.allow_anonymous_shopping') != 'allow_shopping') {
return array(CONTROLLER_STATUS_REDIRECT, "auth.login_form?return_url=" . urlencode($_REQUEST['return_url']));
}
// Add to cart button was pressed for single product on advanced list
if (!empty($dispatch_extra)) {
if (empty($_REQUEST['product_data'][$dispatch_extra]['amount'])) {
$_REQUEST['product_data'][$dispatch_extra]['amount'] = 1;
}
foreach ($_REQUEST['product_data'] as $key => $data) {
if ($key != $dispatch_extra && $key != 'custom_files') {
unset($_REQUEST['product_data'][$key]);
}
}
}
$prev_cart_products = empty($cart['products']) ? array() : $cart['products'];
fn_add_product_to_cart($_REQUEST['product_data'], $cart, $auth);
fn_save_cart_content($cart, $auth['user_id']);
//header("Location: ". Registry::get('config.https_location') . "/checkout");
fn_redirect(Registry::get('config.https_location') . "/checkout",true);
$previous_state = md5(serialize($cart['products']));
$cart['change_cart_products'] = true;
fn_calculate_cart_content($cart, $auth, 'S', true, 'F', true);
if (md5(serialize($cart['products'])) != $previous_state && empty($cart['skip_notification'])) {
$product_cnt = 0;
$added_products = array();
foreach ($cart['products'] as $key => $data) {
if (empty($prev_cart_products[$key]) || !empty($prev_cart_products[$key]) && $prev_cart_products[$key]['amount'] != $data['amount']) {
$added_products[$key] = $data;
$added_products[$key]['product_option_data'] = fn_get_selected_product_options_info($data['product_options']);
if (!empty($prev_cart_products[$key])) {
$added_products[$key]['amount'] = $data['amount'] - $prev_cart_products[$key]['amount'];
}
$product_cnt += $added_products[$key]['amount'];
}
}
if (!empty($added_products)) {
Registry::get('view')->assign('added_products', $added_products);
if (Registry::get('config.tweaks.disable_dhtml') && Registry::get('config.tweaks.redirect_to_cart')) {
Registry::get('view')->assign('continue_url', (!empty($_REQUEST['redirect_url']) && empty($_REQUEST['appearance']['details_page'])) ? $_REQUEST['redirect_url'] : $_SESSION['continue_url']);
}
// $msg = Registry::get('view')->fetch('views/checkout/checkout.tpl');
// fn_set_notification('I', __($product_cnt > 1 ? 'products_added_to_cart' : 'product_added_to_cart'), $msg, 'I');
$cart['recalculate'] = true;
} else {
fn_set_notification('N', __('notice'), __('product_in_cart'));
}
}
unset($cart['skip_notification']);
$_suffix = '.checkout';
if (Registry::get('config.tweaks.disable_dhtml') && Registry::get('config.tweaks.redirect_to_cart') && !defined('AJAX_REQUEST')) {
if (!empty($_REQUEST['redirect_url']) && empty($_REQUEST['appearance']['details_page'])) {
$_SESSION['continue_url'] = fn_url_remove_service_params($_REQUEST['redirect_url']);
}
unset($_REQUEST['redirect_url']);
}
}
return array(CONTROLLER_STATUS_REDIRECT, 'checkout.cart');
}
in add_to_cart.post.tpl
{$id = "buy_now_{$product.product_id}"}
<button id="opener_{$id}" name="dispatch[buy_now.add..{$product.product_id}]" onclick="goto_checkout()" data-ca-target-id="content_{$id}" class=" buynow_btn">BUY NOW</button>
If you are using it into a controller php file, something like
app/addons/MY_ADDON/controllers/frontend/MY_ADDON.php
you can use
return array(CONTROLLER_STATUS_REDIRECT, $url);
I need help with a PHP ToDo List. I have most of it working except for the check box to move it from a completed list to a still need to do list. here is the code I have so far:
For the edit screen:
%% views/header.html %%
<h1>{{$title}}</h1>
<div class='inputs'>
<form action="##todo/update##" method="post">
<input type="hidden" id="id" name="id" value="{{$todo['id']}}" />
<label for="description">Description:</label>
<input type="text" id="description" name="description" value="{{$todo ['description']}}" />
<label for="done">Done?:</label>
<input type="checkbox" id="done" name="done" value="1" />
<input type="submit" value="Update" />
<form>
</div>
<p><< Back</p>
%% views/footer.html %%
For the todo.inc file:
<?php
include_once "include/util.inc";
include_once "models/todo.inc";
function safeParam($arr, $index, $default) {
if ($arr && isset($arr[$index])) {
return $arr[$index];
}
return $default;
}
function get_view($params) {
$id = safeParam($params, 0, false);
if ($id === false) {
die("No todo id specified");
}
$todo = findToDoById($id);
if (!$todo) {
die("No todo with id $id found.");
}
// #formatter:off
renderTemplate(
"views/todo_view.inc",
array(
'title' => 'Viewing To Do',
'todo' => $todo
)
);
// #formatter:on
}
function get_list($params) {
$todos = findAllCurrentToDos();
$dones = findAllDoneToDos();
// #formatter:off
renderTemplate(
"views/index.inc",
array(
'title' => 'To Do List',
'todos' => $todos,
'dones' => $dones
)
);
// #formatter:on
}
function get_edit($params) {
$id = safeParam($params, 0, false);
if (!$id) {
die("No todo specified");
}
$todo = findToDoById($id);
if (!$todo) {
die("No todo found.");
}
// #formatter:off
renderTemplate(
"views/todo_edit.inc",
array(
'title' => 'Editing To Do',
'todo' => $todo
)
);
// #formatter:on
}
function post_add($params) {
if (!isset($_POST['description'])) {
die("no description given");
}
$description = htmlentities($_POST['description']);
addToDo($description);
redirectRelative("index");
}
function validate_present($elements) {
$errors = '';
foreach ($elements as $element) {
if (!isset($_POST[$element])) {
$errors .= "Missing $element\n";
}
}
return $errors;
}
function post_update($params) {
$errors = validate_present(array('id', 'description', 'done'));
if ($errors) {
die($errors);
}
$id = $_POST['id'];
$description = $_POST['description'];
$done = $_POST['done'];
updateToDo($id, $description, $done);
redirectRelative("todo/view/$id");
}
function get_delete($params) {
$id = safeParam($params, 0, false);
if (!$id) {
die("No todo specified");
}
$todo = findToDoById($id);
if (!$todo) {
die("No todo found.");
}
deleteToDo($id);
redirectRelative("index");
}
?>
Your error is in these two functions.
function validate_present($elements) {
$errors = '';
foreach ($elements as $element) {
if (!isset($_POST[$element])) {
$errors .= "Missing $element\n";
}
}
return $errors;
}
function post_update($params) {
$errors = validate_present(array('id', 'description', 'done'));
if ($errors) {
die($errors);
}
$id = $_POST['id'];
$description = $_POST['description'];
$done = $_POST['done'];
updateToDo($id, $description, $done);
redirectRelative("todo/view/$id");
}
You are attempting to validate that done exists in validate_present when called by post_update. done obviously cannot exists since it is not sent to the server when the checkbox is not checked. The $_POST does not even contain that variable, so it returns that element is missing (since it technically is). I would leave validate_present alone and change post_update as follows:
function post_update($params) {
$errors = validate_present(array('id', 'description'));
if ($errors) {
die($errors);
}
$id = $_POST['id'];
$description = $_POST['description'];
$done = (isset($_POST['done'])? 1 : 0);
updateToDo($id, $description, $done);
redirectRelative("todo/view/$id");
}