Related
I have a controller method that checks for post data and parses this through form_validation run method. There is also an image upload field in my view where an image can be uploaded.
The problem is that when a file gets uploaded which is way too big, let's say over 10MB, the form validation will return every single error defined in my validation rules.
If i upload a file which is still too big, but not too much, i will get the correct error message back.
My code looks like this:
public function addVacancy()
{
$this->is_logged_in();
//Check if user has correct permission to access this page
$aclConfig = array('userID' => $this->auth_user_id);
$this->load->library('acl', $aclConfig);
$redirect_protocol = USE_SSL ? 'https' : NULL;
if (!empty($this->auth_user_id)) {
if ( $this->acl->hasPermission("create_vacancy") ) {
//If the value is filled in we know it is an admin creating a vacancy for an organisation, we also set a boolean so we show a bit different message in confirmation.php
$orgId = $this->input->post('orgid');
if (empty($orgId)) {
$orgId = $this->userRoles_model->getOrgUserId($this->auth_user_id);
} else {
$adminEditing = TRUE;
}
$vacancyId = null;
$data = null;
if (strlen($this->input->post('occupancy')) != 1) {
$occupancy = 3;
} else {
$occupancy = $this->input->post('occupancy');
}
$vacancy_data = [
'org_id' => $orgId,
'offer' => $this->input->post('offer'),
'name' => $this->input->post('title'),
'website' => $this->input->post('website'),
'description' => $this->input->post('vacdescription'),
'address_line_1' => $this->input->post('route'),
'address_line_2' => $this->input->post('street_number'),
'address_postal_code' => $this->input->post('postalcode'),
'address_city' => $this->input->post('city'),
'address_country' => $this->input->post('country'),
'number_required' => $this->input->post('count'),
'engagement' => $this->input->post('time'),
'occupancy_kind' => $occupancy,
'create_time' => date('Y-m-d H:i:s'),
'accessibility' => $this->input->post('vacaccessibility'),
'status' => 0
];
$dates_data = [
'fullvacancydate' => $this->input->post('daterange-vacancy')
];
if (!empty($dates_data['fullvacancydate'])) {
$splitfromandto = explode(" - ", $dates_data['fullvacancydate']);
$vacancy_data['vacancy_start_date'] = date( 'Y-m-d', strtotime($splitfromandto[0]));
$vacancy_data['vacancy_end_date'] = date( 'Y-m-d', strtotime($splitfromandto[1]));
} else {
$today = date('Y-m-d');
$todayPlus6Months = date('Y-m-d', strtotime("+6 months", strtotime($today)));
$vacancy_data['vacancy_start_date'] = $today;
$vacancy_data['vacancy_end_date'] = $todayPlus6Months;
}
$contactId = $this->input->post('contactpersons');
if ($contactId == 0) {
$contact_data = [
'org_id' => $orgId,
'family_name' => $this->input->post('family_name'),
'first_name' => $this->input->post('first_name'),
'email' => $this->input->post('email'),
'phone' => $this->input->post('phone'),
'function' => $this->input->post('function')
];
}else{
$contact_data = (array) $this->orgContacts_model->get($contactId);
}
$this->load->library('form_validation');
$validation_data = array_merge($vacancy_data, $contact_data);
$this->form_validation->set_data($validation_data);
$validation_rules = [
[
'field' => 'offer',
'label' => 'offer',
'rules' => 'trim|required',
'errors' => ['required' => 'Wat heb je te bieden is verplicht.']
],
[
'field' => 'name',
'label' => 'name',
'rules' => 'trim|required',
'errors' => ['required' => 'Naam is verplicht.']
],
[
'field' => 'description',
'label' => 'description',
'rules' => 'trim|required',
'errors' => ['required' => 'Beschrijving is verplicht.']
],
[
'field' => 'address_postal_code',
'label' => 'address_postal_code',
'rules' => 'trim|required',
'errors' => ['required' => 'Postcode is verplicht.']
],
[
'field' => 'address_city',
'label' => 'address_city',
'rules' => 'trim|required',
'errors' => ['required' => 'Stad of gemeente is verplicht.']
],
[
'field' => 'address_country',
'label' => 'address_country',
'rules' => 'trim|required',
'errors' => ['required' => 'Land is verplicht.']
],
[
'field' => 'number_required',
'label' => 'number_required',
'rules' => 'trim|required',
'errors' => ['required' => 'Aantal vrijwilligers is verplicht.']
],
[
'field' => 'occupancy_kind',
'label' => 'occupancy_kind',
'rules' => 'trim|required',
'errors' => ['required' => 'Bezetting is verplicht.']
],
[
'field' => 'family_name',
'label' => 'family_name',
'rules' => 'trim|required',
'errors' => ['required' => 'Familie naam van de contactpersoon is verplicht.']
],
[
'field' => 'first_name',
'label' => 'first_name',
'rules' => 'trim|required',
'errors' => ['required' => 'Voornaam van de contactpersoon is verplicht.']
],
[
'field' => 'email',
'label' => 'email',
'rules' => 'trim|required',
'errors' => ['required' => 'Email van de contactpersoon is verplicht.']
],
[
'field' => 'phone',
'label' => 'phone',
'rules' => 'trim|required',
'errors' => ['required' => 'Telefoonnummer van de contactpersoon is verplicht.']
],
[
'field' => 'function',
'label' => 'function',
'rules' => 'trim|required',
'errors' => ['required' => 'Functie van de contactpersoon is verplicht.']
],
];
$this->form_validation->set_rules($validation_rules);
if ($this->form_validation->run()) {
// Create new contact
if ($contactId == 0) {
$contactId = $this->orgContacts_model->add($contact_data);
}
// Create vacancy
$this->load->model('vacancy/vacancy_model');
// Var to check
$check = false;
$isNoImageChosen = false;
if(isset($_FILES['userfile']['name']) && is_uploaded_file($_FILES['userfile']['tmp_name'])) {
// Banner Upload
$config['upload_path'] = VACANCY_IMAGES;
$config['allowed_types'] = 'jpg|png|PNG|JPG|jpeg|bmp';
$config['min_width'] = 1024;
$config['min_height'] = 768;
$config['max_size'] = 3072;
$config['quality'] = 60;
$this->load->library('upload', $config);
if ($this->upload->do_upload('userfile')) {
$uploadData = $this->upload->data();
if (isset($uploadData)) {
$vacancy_data['banner'] = $uploadData['file_name'];
$check = true;
}
} else {
$imageOk = array('error' => $this->upload->display_errors());
// Passing Variables
$data['title'] = 'Give a Day - Error';
$data['class'] = 'vacancy';
$data['validationErrors'] = validation_errors();
$data['imgErrors'] = $imageOk['error'];
$data['feedback'] = array(
'type' => 'alert-danger',
'icon' => 'fa-times',
'title' => 'Oops!',
'text' => 'Uploaden van de foto is niet gelukt'
);
$content = 'dashboard/vacancy/error';
}
} else {
//check on true cause there is no image selected
$check = true;
$isNoImageChosen = true;
}
//Check if image upload went without errors
if($check) {
//Serialize the accessibility (because more than 1 value can be entered)
$vacancy_data['accessibility'] = serialize($vacancy_data['accessibility']);
$vacancyId = $this->vacancy_model->add($vacancy_data);
// Create Vacancy Contact
$vacancyContact['contact_id'] = $contactId;
$vacancyContact['vacancy_id'] = $vacancyId;
$this->vacancyContacts_model->add($vacancyContact);
// Set Interests
$this->load->model('vacancy/vacancyInterests_model');
$interests = $this->input->post('interests');
if ($interests != '') {
$interests = explode(",", $interests);
foreach ($interests as $id) {
$this->vacancyInterests_model->add($vacancyId, $id);
}
}
if ($isNoImageChosen) {
$k = array_rand($interests);
$randomInterestId = $interests[$k];
$randomBannerImageLocation = return_random_interest_banner($randomInterestId);
//Because the vacancy has already been created we need to do an update for setting the banner image
$bannerData = array (
'banner' => $randomBannerImageLocation
);
$this->vacancies_model->update($vacancyId, $bannerData);
}
// Set Skills
$this->load->model('vacancy/vacancySkills_model');
$skills = $this->input->post('skills');
if ($skills != '') {
$skills = explode(",", $skills);
foreach ($skills as $id) {
$this->vacancySkills_model->add($vacancyId, $id);
}
}
//Get organisation information for the name
$orgdata = $this->organization_model->get($orgId);
$orgname = $orgdata->name;
$orguserid = $this->userRoles_model->getAdminUserId($orgId);
$orguserdata = $this->users_model->get($orguserid[0]->user_id);
$orgemail = $orguserdata->email;
$mail_data['vacid'] = $vacancyId;
$mail_data['vacname'] = $vacancy_data['name'];
$mail_data['org_id'] = $orgId;
$mail_data['orgname'] = $orgname;
$mail_data['contactpersonfirstname'] = $contact_data['first_name'];
$this->email->from(GENERAL_MAIL, 'Give a Day');
$this->email->to($contact_data['email']);
$this->email->cc($orgemail);
$this->email->bcc(GENERAL_MAIL);
$this->email->subject('Je vrijwilligersactiviteit is aangemaakt');
$message = $this->load->view('mail/vacancy/creation_confirmation', $mail_data, TRUE);
$this->email->message($message);
$this->email->send();
// Passing Variables
$data['title'] = 'Give a Day - Succes!';
$data['class'] = 'vacancy';
$data['vacancyId'] = $vacancyId;
$data['vacancyName'] = $vacancy_data['name'];
if ($adminEditing) {
$data['adminedit'] = TRUE;
$data['orgid'] = $orgId;
}
$content = 'dashboard/vacancy/confirmation';
} else {
// Passing Variables
$data['title'] = 'Give a Day - Error';
$data['class'] = 'vacancy';
$data['validationErrors'] = validation_errors();
$imageOk = array('error' => $this->upload->display_errors());
$data['imgErrors'] = $imageOk['error'];
$content = 'dashboard/vacancy/error';
}
} else {
// Passing Variables
$data['title'] = 'Give a Day - Error';
$data['class'] = 'vacancy';
$data['validationErrors'] = validation_errors();
//$imageOk = array('error' => $this->upload->display_errors());
//$data['imgErrors'] = $imageOk['error'];
$content = 'dashboard/vacancy/error';
}
// Template declaration
$partials = array('head' => '_master/header/head', 'navigation' => '_master/header/navigation_dashboard', 'content' => $content, 'footer' => '_master/footer/footer');
$this->template->load('_master/master', $partials, $data);
} else {
//User does not have correct permissions --> Go to 404
redirect(site_url( 'error/my404', $redirect_protocol));
}
} else {
//User is anonymous -> go to login page (and remember the current URL for redirecting again after log in)
$this->session->set_flashdata('referred_from', uri_string());
redirect(site_url( 'login?redirect=user', $redirect_protocol));
}
}
Note that when I upload an image of 19 MB, for some reason I end up in the else clause all the way at the bottom and I get a page showing all the validation errors saying "Wat heb je te bieden is verplicht.", "naam is verplicht", ... and all of them literally.
All data is filled in correctly, and when i perform the exact same steps, but take an image which is less than 3MB, it works perfect.
So 0-3MB - works perfect.
3-10MB - gives perfect error
and >10 MB - gives all validation errors.
You may find this useful, this is a helper I've created for form uploads to determine the maximum size for uploads based on post_max_size and upload_max_size
Usage:
$config['max_size'] = convert_bytes_to_type(file_upload_max_size(), 'KB');
Helper:
/**
* Gets max upload size from post_max_size and upload_max_filesize
* Returns whichever is smaller
*
* #return int
*/
function file_upload_max_size() {
$max_size = convert_to_bytes(ini_get('post_max_size'));
$upload_max = convert_to_bytes(ini_get('upload_max_filesize'));
if ($upload_max > 0 && $upload_max < $max_size) {
$max_size = $upload_max;
}
return $max_size;
}
/**
* Converts KB (K) through GB (G) to bytes
*
* #param string $from
* #return int bytes
*/
function convert_to_bytes($from) {
$number = filter_var($from, FILTER_SANITIZE_NUMBER_INT);
if (empty($number)) {
return 0;
}
$type = strtoupper(str_replace($number, '', $from));
switch ($type) {
case "KB":
case "K":
$number = $number * 1024;
break;
case "MB":
case "M":
$number = $number * pow(1024, 2);
break;
case "GB":
case "G":
$number = $number * pow(1024, 3);
break;
default:
return 0;
}
return fix_integer_overflow($number);
}
/**
* Converts bytes to KB (K) through GB (G)
*
* #param int $bytes
* #param string $type Type to convert to
* KB (K) through GB (G)
* #return int bytes
*/
function convert_bytes_to_type($bytes, $type = 'MB') {
$number = filter_var($bytes, FILTER_SANITIZE_NUMBER_INT);
if (empty($number)) {
return 0;
}
$type = strtoupper($type);
switch ($type) {
case "KB":
case "K":
$divisor = 1024;
break;
case "MB":
case "M":
$divisor = pow(1024, 2);
break;
case "GB":
case "G":
$divisor = pow(1024, 3);
break;
default:
return 0;
}
return $bytes / $divisor;
}
/**
* Converts bytes into human readable form
*
* #param string || File
* #param int precision round precision
* #return int rounded bytes in units
*/
function human_readable_bytes($bytes, $precision = 2) {
$CI = & get_instance();
$CI->lang->load('number');
if (is_file($bytes)) {
$bytes = fix_integer_overflow(filesize($bytes));
}
$units = array(
$CI->lang->line('bytes'),
$CI->lang->line('kilobyte_abbr'),
$CI->lang->line('megabyte_abbr'),
$CI->lang->line('gigabyte_abbr'),
$CI->lang->line('terabyte_abbr')
);
$bytes = max($bytes, 0);
$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
$pow = min($pow, count($units) - 1);
$bytes /= pow(1024, $pow);
return round($bytes, $precision) . ' ' . $units[$pow];
}
/**
* Fixes integer overflow
*
* #param int $size
* #return int
*/
function fix_integer_overflow($size) {
if ($size < 0) {
$size += 2.0 * (PHP_INT_MAX + 1);
}
return $size;
}
https://pastebin.com/2zDJ90Qr
I figured out that post_max_size in php.ini was set to 8MB, this caused the $_POST variable to become NULL... Setting an if case to check if $_POST is not null solved the issue! Thanks
I copy order_conf.tpl and order_conf.txt file from mail folder and rename it. Now add override to classes/order/OrderHistory.php
I change function sendemail() to:
public function sendEmail($order, $template_vars = false)
{
$result = Db::getInstance()->getRow('
SELECT osl.`template`, c.`lastname`, c.`firstname`, osl.`name` AS osname, c.`email`, os.`module_name`, os.`id_order_state`, os.`pdf_invoice`, os.`pdf_delivery`
FROM `'._DB_PREFIX_.'order_history` oh
LEFT JOIN `'._DB_PREFIX_.'orders` o ON oh.`id_order` = o.`id_order`
LEFT JOIN `'._DB_PREFIX_.'customer` c ON o.`id_customer` = c.`id_customer`
LEFT JOIN `'._DB_PREFIX_.'order_state` os ON oh.`id_order_state` = os.`id_order_state`
LEFT JOIN `'._DB_PREFIX_.'order_state_lang` osl ON (os.`id_order_state` = osl.`id_order_state` AND osl.`id_lang` = o.`id_lang`)
WHERE oh.`id_order_history` = '.(int)$this->id.' AND os.`send_email` = 1');
if (isset($result['template']) && Validate::isEmail($result['email'])) {
ShopUrl::cacheMainDomainForShop($order->id_shop);
$topic = $result['osname'];
/*----------------------
-START OF INSERTED CODE-
----------------------*/
/* GET THE PRODUCTS */
$order_details = $order->getProducts();
$product_var_tpl_list = array();
foreach ($order_details as $id => &$order_detail) {
$product_var_tpl = array(
'reference' => $order_detail['product_reference'],
'name' => $order_detail['product_name'].(isset($order_detail['product_attributes']) ? ' - '.$order_detail['product_attributes'] : ''),
'unit_price' => Tools::displayPrice($order_detail['unit_price_tax_incl'], $this->context->currency, false),
'price' => Tools::displayPrice($order_detail['total_price_tax_incl'], $this->context->currency, false),
'quantity' => $order_detail['product_quantity'],
'customization' => $order_detail['customizedDatas']
);
$product_var_tpl_list[] = $product_var_tpl;
} // end foreach ($order_detail)
$product_list_txt = '';
$product_list_html = '';
if (count($product_var_tpl_list) > 0) {
$product_list_txt = $this->getEmailTemplateContent('order_conf_product_list.txt', Mail::TYPE_TEXT, $product_var_tpl_list);
$product_list_html = $this->getEmailTemplateContent('order_conf_product_list.tpl', Mail::TYPE_HTML, $product_var_tpl_list);
}
/* GET THE DISCOUNTS */
$cart_rules = $order->getCartRules();
foreach ($cart_rules as $id => &$cart_rule) {
$cart_rules_list[] = array(
'voucher_name' => $cart_rule['name'],
'voucher_reduction' => ($cart_rule['value'] != 0.00 ? '-' : '').Tools::displayPrice($cart_rule['value'], $this->context->currency, false)
);
}
$cart_rules_list_txt = '';
$cart_rules_list_html = '';
if (count($cart_rules_list) > 0) {
$cart_rules_list_txt = $this->getEmailTemplateContent('order_conf_cart_rules.txt', Mail::TYPE_TEXT, $cart_rules_list);
$cart_rules_list_html = $this->getEmailTemplateContent('order_conf_cart_rules.tpl', Mail::TYPE_HTML, $cart_rules_list);
}
/* GET ORDER DETAILS, delivery, invoice, amount... etc */
$invoice_address = new Address((int)$order->id_address_invoice);
$invoiceAddressPatternRules = Tools::jsonDecode(Configuration::get('PS_INVCE_INVOICE_ADDR_RULES'), true);
$deliveryAddressPatternRules = Tools::jsonDecode(Configuration::get('PS_INVCE_DELIVERY_ADDR_RULES'), true);
$country = new Country((int)$invoice_address->id_country);
$delivery_address = null;
$formatted_delivery_address = '';
if (isset($order->id_address_delivery) && $order->id_address_delivery) {
$delivery_address = new Address((int)$order->id_address_delivery);
}
$carrier = new Carrier((int)($order->id_carrier), $order->id_lang);
/* ATTACH INFORMATION TO SMARTY VARIABLE*/
$data = array(
'{lastname}' => $result['lastname'],
'{firstname}' => $result['firstname'],
'{id_order}' => (int)$this->id_order,
'{delivery_block_txt}' => AddressFormat::generateAddress($delivery_address, $deliveryAddressPatternRules, ', ', ' '),
'{invoice_block_txt}' => AddressFormat::generateAddress($invoice_address, $invoiceAddressPatternRules, ', ', ' '),
'{delivery_block_html}' => AddressFormat::generateAddress($delivery_address, $deliveryAddressPatternRules, '<br />',' ', array(
'firstname' => '<span style="font-weight:bold;">%s</span>',
'lastname' => '<span style="font-weight:bold;">%s</span>'
)),
'{invoice_block_html}' => AddressFormat::generateAddress($invoice_address, $invoiceAddressPatternRules, '<br />',' ', array(
'firstname' => '<span style="font-weight:bold;">%s</span>',
'lastname' => '<span style="font-weight:bold;">%s</span>'
)),
'{delivery_company}' => $delivery_address->company,
'{delivery_firstname}' => $delivery_address->firstname,
'{delivery_lastname}' => $delivery_address->lastname,
'{delivery_address1}' => $delivery_address->address1,
'{delivery_address2}' => $delivery_address->address2,
'{delivery_city}' => $delivery_address->city,
'{delivery_postal_code}' => $delivery_address->postcode,
'{delivery_country}' => $delivery_address->country,
'{delivery_state}' => $delivery_address->id_state ? $delivery_state->name : '',
'{delivery_phone}' => ($delivery_address->phone) ? $delivery_address->phone : $delivery_address->phone_mobile,
'{delivery_other}' => $delivery_address->other,
'{invoice_company}' => $invoice_address->company,
'{invoice_vat_number}' => $invoice_address->vat_number,
'{invoice_firstname}' => $invoice_address->firstname,
'{invoice_lastname}' => $invoice_address->lastname,
'{invoice_address2}' => $invoice_address->address2,
'{invoice_address1}' => $invoice_address->address1,
'{invoice_city}' => $invoice_address->city,
'{invoice_postal_code}' => $invoice_address->postcode,
'{invoice_country}' => $invoice_address->country,
'{invoice_state}' => $invoice_address->id_state ? $invoice_state->name : '',
'{invoice_phone}' => ($invoice_address->phone) ? $invoice_address->phone : $invoice_address->phone_mobile,
'{invoice_other}' => $invoice_address->other,
'{order_name}' => $order->getUniqReference(),
'{date}' => Tools::displayDate(date('Y-m-d H:i:s'), null, 1),
'{carrier}' => (!isset($carrier->name)) ? Tools::displayError('No carrier') : $carrier->name,
'{payment}' => Tools::substr($order->payment, 0, 32),
'{products}' => $product_list_html,
'{products_txt}' => $product_list_txt,
'{discounts}' => $cart_rules_list_html,
'{discounts_txt}' => $cart_rules_list_txt,
'{total_paid}' => Tools::displayPrice($order->total_paid, $this->context->currency, false),
'{total_products}' => Tools::displayPrice(Product::getTaxCalculationMethod() == PS_TAX_EXC ? $order->total_products : $order->total_products_wt, $this->context->currency, false),
'{total_discounts}' => Tools::displayPrice($order->total_discounts, $this->context->currency, false),
'{total_shipping}' => Tools::displayPrice($order->total_shipping, $this->context->currency, false),
'{total_wrapping}' => Tools::displayPrice($order->total_wrapping, $this->context->currency, false),
'{total_tax_paid}' => Tools::displayPrice(($order->total_products_wt - $order->total_products) + ($order->total_shipping_tax_incl - $order->total_shipping_tax_excl), $this->context->currency, false)
);
/*---------------------
!-END OF INSERTED CODE-
---------------------*/
if ($result['module_name']) {
$module = Module::getInstanceByName($result['module_name']);
if (Validate::isLoadedObject($module) && isset($module->extra_mail_vars) && is_array($module->extra_mail_vars)) {
$data = array_merge($data, $module->extra_mail_vars);
}
}
if ($template_vars) {
$data = array_merge($data, $template_vars);
}
$data['{total_paid}'] = Tools::displayPrice((float)$order->total_paid, new Currency((int)$order->id_currency), false);
if (Validate::isLoadedObject($order)) {
// Attach invoice and / or delivery-slip if they exists and status is set to attach them
if (($result['pdf_invoice'] || $result['pdf_delivery'])) {
$context = Context::getContext();
$invoice = $order->getInvoicesCollection();
$file_attachement = array();
if ($result['pdf_invoice'] && (int)Configuration::get('PS_INVOICE') && $order->invoice_number) {
Hook::exec('actionPDFInvoiceRender', array('order_invoice_list' => $invoice));
$pdf = new PDF($invoice, PDF::TEMPLATE_INVOICE, $context->smarty);
$file_attachement['invoice']['content'] = $pdf->render(false);
$file_attachement['invoice']['name'] = Configuration::get('PS_INVOICE_PREFIX', (int)$order->id_lang, null, $order->id_shop).sprintf('%06d', $order->invoice_number).'.pdf';
$file_attachement['invoice']['mime'] = 'application/pdf';
}
if ($result['pdf_delivery'] && $order->delivery_number) {
$pdf = new PDF($invoice, PDF::TEMPLATE_DELIVERY_SLIP, $context->smarty);
$file_attachement['delivery']['content'] = $pdf->render(false);
$file_attachement['delivery']['name'] = Configuration::get('PS_DELIVERY_PREFIX', Context::getContext()->language->id, null, $order->id_shop).sprintf('%06d', $order->delivery_number).'.pdf';
$file_attachement['delivery']['mime'] = 'application/pdf';
}
} else {
$file_attachement = null;
}
if (!Mail::Send((int)$order->id_lang, $result['template'], $topic, $data, $result['email'], $result['firstname'].' '.$result['lastname'],
null, null, $file_attachement, null, _PS_MAIL_DIR_, false, (int)$order->id_shop)) {
return false;
}
}
ShopUrl::resetMainDomainCache();
}
return true;
}
protected function getEmailTemplateContent($template_name, $mail_type, $var)
{
$email_configuration = Configuration::get('PS_MAIL_TYPE');
if ($email_configuration != $mail_type && $email_configuration != Mail::TYPE_BOTH) {
}
$theme_template_path = _PS_THEME_DIR_.'mails'.DIRECTORY_SEPARATOR.Context::getContext()->language->iso_code.DIRECTORY_SEPARATOR.$template_name;
$default_mail_template_path = _PS_MAIL_DIR_.Context::getContext()->language->iso_code.DIRECTORY_SEPARATOR.$template_name;
if (Tools::file_exists_cache($theme_template_path)) {
$default_mail_template_path = $theme_template_path;
}
if (Tools::file_exists_cache($default_mail_template_path)) {
Context::getContext()->smarty->assign('list', $var);
return Context::getContext()->smarty->fetch($default_mail_template_path);
}
return ' ';
}
In status I create new one status and add option to send my new email to customer, when in order I change status email is send to customer with data but there is missing all product detail from orders.
I don't know how I can correct get this product in my override file.
You don't have the needed templates in your context backoffice language.
Copy files:
/mails/en/order_conf_cart_rules.tpl
/mails/en/order_conf_cart_rules.txt
/mails/en/order_conf_product_list.tpl
/mails/en/order_conf_product_list.txt
To:
/mails/YOUR_BACKOFFICE_USER_LANG_ISO_CODE/order_conf_cart_rules.tpl
/mails/YOUR_BACKOFFICE_USER_LANG_ISO_CODE/order_conf_cart_rules.txt
/mails/YOUR_BACKOFFICE_USER_LANG_ISO_CODE/order_conf_product_list.tpl
/mails/YOUR_BACKOFFICE_USER_LANG_ISO_CODE/order_conf_product_list.txt
I have this function that handle the Fb Callback.
public function handleFbCallback() {
if( !\Input::get('error', NULL) ) {
try {
$fuser = \Socialize::with('facebook')->user();
$token = $fuser->token;
if($fb = \App\UserFacebook::whereEmail($fuser->getEmail())->first()) {
$fb->fb_id = $fuser->getId();
$fb->nickname = $fuser->getNickname();
$fb->name = $fuser->getName();
$fb->avatar = $fuser->getAvatar();
$fb->token = $token;
$fb->save();
$profile = \App\Profile::whereUserId($fb->user_id)->first();
if($profile) {
$profile->name = $fuser->user['first_name'];
$profile->last_name = $fuser->user['last_name'];
$profile->save();
} else {
\App\Profile::create([
'name' => $fuser->user['first_name'],
'last_name' => $fuser->user['last_name'],
'user_id' => $fb->user_id,
]);
}
//load user and increments number login
$user = \App\User::find($fb->user_id);
if($user) {
$user->last_login = date('Y-m-d H:i:s');
$user->number_logins = $user->number_logins + 1;
$user->save();
}
}
else {
$password = str_random(8);
$nuser = \App\User::whereEmail($fuser->getEmail())->first();
if(!$nuser) {
$nuser = \App\User::create([
'email' => $fuser->getEmail(),
'password' => bcrypt($password),
'active' => 1,
]);
if(\Session::get('source', NULL)) {
$nuser->source = \Session::get('source');
\Session::forget('source');
}
if(\Session::get('campaign', NULL)) {
$nuser->source = \Session::get('campaign');
\Session::forget('campaign');
}
$nuser->save();
//profile
\App\Profile::create([
'name' => $fuser->user['first_name'],
'last_name' => $fuser->user['last_name'],
'user_id' => $nuser->id,
]);
}
$nuser->last_login = date('Y-m-d H:i:s');
$nuser->number_logins = 1;
$nuser->save();
$fb = \App\UserFacebook::create([
'fb_id' => $fuser->getId(),
'nickname' => $fuser->getNickname(),
'name' => $fuser->getName(),
'email' => $fuser->getEmail(),
'avatar' => $fuser->getAvatar(),
'token' => $token,
'user_id' => $nuser->id
]);
}
\Auth::loginUsingId($fb->user_id);
if(\Session::get('custom_url', NULL) == 'thanks') {
return redirect()->route('landing.thanks', array('social', $fb->user_id));
} elseif($url = \Session::get('custom_url', NULL)) {
\Session::forget('custom_url');
return redirect($url);
}
return redirect()->intended();
}
catch(Exception $e) {
dd($e->getMessage());
}
}
return redirect('/');
}
Running this function it make an exception:
Client error: GET https://graph.facebook.com/v2.6/me?access_token=&appsecret_proof=cb32db5fac27b922d1a9c3040772a05b9a6e79f8145ee5a9fc21bbefd1f00909&fields=name,first_name,last_name,email,gender,verified resulted in a 400 Bad Request response: {"error":{"message":"An active access token must be used to query information about the current user.","type":"OAuthExce (truncated...)
But it make an exception about the token.
Someone have any idea to solve that?
Thank you!
I am new to codeigniter and trying to add and edit a category with the same method add.
Here is my add method:
public function add($category_id = FALSE)
{
$this->load->helper('form');
$this->load->library('form_validation');
if($category_id === FALSE)
{
$this->data['mode'] = 'insert';
$this->data['hidden_fields'] = array('mode' => $this->data['mode']);
}
else
{
$this->data['mode'] = 'update';
$this->data['category_details'] = $this->category_model->get_category_details($category_id);
$this->data['category_id'] = isset($this->data['category_details'][0]['category_id']) ? $this->data['category_details'][0]['category_id'] : '';
$this->data['hidden_fields'] = array('category_id' => $this->data['category_id'], 'mode' => $this->data['mode']);
}
// Fill the form data for edit.
$this->data['name'] = isset($this->data['category_details'][0]['name']) ? $this->data['category_details'][0]['name'] : set_value('name');
$this->data['description'] = isset($this->data['exam_category_details'][0]['description']) ? $this->data['category_details'][0]['description'] : set_value('description');
$this->data['status_y'] = (isset($this->data['category_details'][0]['status']) && $this->data['category_details'][0]['status'] === 'Y') ? 'checked="checked"' : set_radio('status', 'Y', TRUE);
$this->data['status_n'] = (isset($this->data['category_details'][0]['status']) && $this->data['category_details'][0]['status'] === 'N') ? 'checked="checked"' : set_radio('status', 'Y');
// set the validation rules
$validation_rules = array(
array(
'field' => 'name',
'label' => 'Name',
'rules' => 'trim|required|min_length[5]|max_length[20]|xss_clean'
),
array(
'field' => 'description',
'label' => 'Description',
'rules' => 'trim|min_length[5]|max_length[256]|xss_clean'
)
);
$this->form_validation->set_rules($validation_rules);
// check if validation fails or upload logo fails
if ($this->form_validation->run() === FALSE)
{
$this->data['validation_errors'] = validation_errors();
$this->load->view($this->config->item('templates_path').'header', $this->data);
$this->load->view($this->config->item('templates_path').'sidebar_content', $this->data);
$this->load->view($this->config->item('templates_path').'navigation', $this->data);
$this->load->view('add_category', $this->data);
$this->load->view($this->config->item('templates_path').'footer');
}
else
{
$id = $this->category_model->update_category();
if($id !== FALSE && is_numeric($id))
{
$this->session->set_flashdata('msg_success', 'Operation Successful');
redirect('/exams/exam_category/');
}
else
{
// update exam category failed some where
log_message('error', 'Update exam category failed', TRUE);
show_error("Unable to Update exam category : ".$id);
}
}
}
The above method works fine for add and edit category, but if form validation fails I am loosing my form default values in both add and edit cases. I have used set_value method of codeignitor. How can I retain the form input values in case of validation fails?
I'm currently working on a project where I use Zend Framework with Propel.
I'm looking for something that'll create Zend_Forms for Propel objects, preferably in a similar way to django's modelforms
Is there anything out there that does this already, and if not, what would be the best way to go about creating something like this?
One of my colleagues has provided the following as a "starting place"
<?php
class TestController extends Zend_Controller_Action
{
public function indexAction()
{
$product_table = ProductPeer::getTableMap();
$product_columns = $product_table->getColumns();
$elements = array();
foreach($product_columns as $col_name => $col_data)
{
$col_name = ucwords(str_replace('_', ' ', strtolower($col_name)));
switch($col_data->getType())
{
case 'TINYINT':
$element = new Zend_Form_Element_Text(
$col_name,
array(
'label' => $col_name
)
);
break;
case 'SMALLINT':
$element = new Zend_Form_Element_Text(
$col_name,
array(
'label' => $col_name
)
);
break;
case 'INTEGER':
$element = new Zend_Form_Element_Text(
$col_name,
array(
'label' => $col_name
)
);
break;
case 'FLOAT':
$element = new Zend_Form_Element_Text(
$col_name,
array(
'label' => $col_name
)
);
break;
case 'DOUBLE':
$element = new Zend_Form_Element_Text(
$col_name,
array(
'label' => $col_name
)
);
break;
case 'VARCHAR':
$element = new Zend_Form_Element_Text(
$col_name,
array(
'label' => $col_name
)
);
break;
case 'DECIMAL':
$element = new Zend_Form_Element_Text(
$col_name,
array(
'label' => $col_name
)
);
break;
case 'LONGVARCHAR':
$element = new Zend_Form_Element_Text(
$col_name,
array(
'label' => $col_name
)
);
break;
case 'DATE':
$element = new Zend_Form_Element_Text(
$col_name,
array(
'label' => $col_name
)
);
break;
case 'TIMESTAMP':
$element = new Zend_Form_Element_Text(
$col_name,
array(
'label' => $col_name
)
);
break;
default:
die("Unknown colum type: " . $col_data->getType());
}
$elements[] = $element;
echo $element;
}
die("END");
}
}