newbies should be encouraged. rather discouraging
I am new an having problems in understanding docs of php.
can someone give the exact code steps for my future reference to :
I want to run this query:
$query = $this->db->query("SELECT tracking_code FROM " . DB_PREFIX . "customer WHERE language_id = '" . (int)$this->customer->getId() . "'");
(I know it will return only one value) and 1. if "if tacking named cookie exists, delete it or replace it and set a cookie named "tracking" for one year with the value returned by that query. How can i do it?
I know little about php . but i get the feeling that i have no reference to db in that confirm.php . it doesnot extends model, nor i know would $this work here or not
the file iam working on is.
<?php
class ControllerCheckoutConfirm extends Controller {
public function index() {
$redirect = '';
if ($this->cart->hasShipping()) {
// Validate if shipping address has been set.
$this->load->model('account/address');
if ($this->customer->isLogged() && isset($this->session->data['shipping_address_id'])) {
$shipping_address = $this->model_account_address->getAddress($this->session->data['shipping_address_id']);
} elseif (isset($this->session->data['guest'])) {
$shipping_address = $this->session->data['guest']['shipping'];
}
if (empty($shipping_address)) {
$redirect = $this->url->link('checkout/checkout', '', 'SSL');
}
// Validate if shipping method has been set.
if (!isset($this->session->data['shipping_method'])) {
$redirect = $this->url->link('checkout/checkout', '', 'SSL');
}
} else {
unset($this->session->data['shipping_method']);
unset($this->session->data['shipping_methods']);
}
// Validate if payment address has been set.
$this->load->model('account/address');
if ($this->customer->isLogged() && isset($this->session->data['payment_address_id'])) {
$payment_address = $this->model_account_address->getAddress($this->session->data['payment_address_id']);
} elseif (isset($this->session->data['guest'])) {
$payment_address = $this->session->data['guest']['payment'];
}
if (empty($payment_address)) {
$redirect = $this->url->link('checkout/checkout', '', 'SSL');
}
// Validate if payment method has been set.
if (!isset($this->session->data['payment_method'])) {
$redirect = $this->url->link('checkout/checkout', '', 'SSL');
}
// Validate cart has products and has stock.
if ((!$this->cart->hasProducts() && empty($this->session->data['vouchers'])) || (!$this->cart->hasStock() && !$this->config->get('config_stock_checkout'))) {
$redirect = $this->url->link('checkout/cart');
}
// Validate minimum quantity requirments.
$products = $this->cart->getProducts();
foreach ($products as $product) {
$product_total = 0;
foreach ($products as $product_2) {
if ($product_2['product_id'] == $product['product_id']) {
$product_total += $product_2['quantity'];
}
}
if ($product['minimum'] > $product_total) {
$redirect = $this->url->link('checkout/cart');
break;
}
}
if (!$redirect) {
$total_data = array();
$total = 0;
$taxes = $this->cart->getTaxes();
$this->load->model('setting/extension');
$sort_order = array();
$results = $this->model_setting_extension->getExtensions('total');
foreach ($results as $key => $value) {
$sort_order[$key] = $this->config->get($value['code'] . '_sort_order');
}
array_multisort($sort_order, SORT_ASC, $results);
foreach ($results as $result) {
if ($this->config->get($result['code'] . '_status')) {
$this->load->model('total/' . $result['code']);
$this->{'model_total_' . $result['code']}->getTotal($total_data, $total, $taxes);
}
}
$sort_order = array();
foreach ($total_data as $key => $value) {
$sort_order[$key] = $value['sort_order'];
}
array_multisort($sort_order, SORT_ASC, $total_data);
$this->language->load('checkout/checkout');
$data = array();
$data['invoice_prefix'] = $this->config->get('config_invoice_prefix');
$data['store_id'] = $this->config->get('config_store_id');
$data['store_name'] = $this->config->get('config_name');
if ($data['store_id']) {
$data['store_url'] = $this->config->get('config_url');
} else {
$data['store_url'] = HTTP_SERVER;
}
if ($this->customer->isLogged()) {
$data['customer_id'] = $this->customer->getId();
$data['customer_group_id'] = $this->customer->getCustomerGroupId();
$data['firstname'] = $this->customer->getFirstName();
$data['lastname'] = $this->customer->getLastName();
$data['email'] = $this->customer->getEmail();
$data['telephone'] = $this->customer->getTelephone();
$data['fax'] = $this->customer->getFax();
$this->load->model('account/address');
$payment_address = $this->model_account_address->getAddress($this->session->data['payment_address_id']);
} elseif (isset($this->session->data['guest'])) {
$data['customer_id'] = 0;
$data['customer_group_id'] = $this->session->data['guest']['customer_group_id'];
$data['firstname'] = $this->session->data['guest']['firstname'];
$data['lastname'] = $this->session->data['guest']['lastname'];
$data['email'] = $this->session->data['guest']['email'];
$data['telephone'] = $this->session->data['guest']['telephone'];
$data['fax'] = $this->session->data['guest']['fax'];
$payment_address = $this->session->data['guest']['payment'];
}
$data['payment_firstname'] = $payment_address['firstname'];
$data['payment_lastname'] = $payment_address['lastname'];
$data['payment_company'] = $payment_address['company'];
$data['payment_company_id'] = $payment_address['company_id'];
$data['payment_tax_id'] = $payment_address['tax_id'];
$data['payment_address_1'] = $payment_address['address_1'];
$data['payment_address_2'] = $payment_address['address_2'];
$data['payment_city'] = $payment_address['city'];
$data['payment_postcode'] = $payment_address['postcode'];
$data['payment_zone'] = $payment_address['zone'];
$data['payment_zone_id'] = $payment_address['zone_id'];
$data['payment_country'] = $payment_address['country'];
$data['payment_country_id'] = $payment_address['country_id'];
$data['payment_address_format'] = $payment_address['address_format'];
if (isset($this->session->data['payment_method']['title'])) {
$data['payment_method'] = $this->session->data['payment_method']['title'];
} else {
$data['payment_method'] = '';
}
if (isset($this->session->data['payment_method']['code'])) {
$data['payment_code'] = $this->session->data['payment_method']['code'];
} else {
$data['payment_code'] = '';
}
if ($this->cart->hasShipping()) {
if ($this->customer->isLogged()) {
$this->load->model('account/address');
$shipping_address = $this->model_account_address->getAddress($this->session->data['shipping_address_id']);
} elseif (isset($this->session->data['guest'])) {
$shipping_address = $this->session->data['guest']['shipping'];
}
$data['shipping_firstname'] = $shipping_address['firstname'];
$data['shipping_lastname'] = $shipping_address['lastname'];
$data['shipping_company'] = $shipping_address['company'];
$data['shipping_address_1'] = $shipping_address['address_1'];
$data['shipping_address_2'] = $shipping_address['address_2'];
$data['shipping_city'] = $shipping_address['city'];
$data['shipping_postcode'] = $shipping_address['postcode'];
$data['shipping_zone'] = $shipping_address['zone'];
$data['shipping_zone_id'] = $shipping_address['zone_id'];
$data['shipping_country'] = $shipping_address['country'];
$data['shipping_country_id'] = $shipping_address['country_id'];
$data['shipping_address_format'] = $shipping_address['address_format'];
if (isset($this->session->data['shipping_method']['title'])) {
$data['shipping_method'] = $this->session->data['shipping_method']['title'];
} else {
$data['shipping_method'] = '';
}
if (isset($this->session->data['shipping_method']['code'])) {
$data['shipping_code'] = $this->session->data['shipping_method']['code'];
} else {
$data['shipping_code'] = '';
}
} else {
$data['shipping_firstname'] = '';
$data['shipping_lastname'] = '';
$data['shipping_company'] = '';
$data['shipping_address_1'] = '';
$data['shipping_address_2'] = '';
$data['shipping_city'] = '';
$data['shipping_postcode'] = '';
$data['shipping_zone'] = '';
$data['shipping_zone_id'] = '';
$data['shipping_country'] = '';
$data['shipping_country_id'] = '';
$data['shipping_address_format'] = '';
$data['shipping_method'] = '';
$data['shipping_code'] = '';
}
$product_data = array();
foreach ($this->cart->getProducts() as $product) {
$option_data = array();
foreach ($product['option'] as $option) {
if ($option['type'] != 'file') {
$value = $option['option_value'];
} else {
$value = $this->encryption->decrypt($option['option_value']);
}
$option_data[] = array(
'product_option_id' => $option['product_option_id'],
'product_option_value_id' => $option['product_option_value_id'],
'option_id' => $option['option_id'],
'option_value_id' => $option['option_value_id'],
'name' => $option['name'],
'value' => $value,
'type' => $option['type']
);
}
$product_data[] = array(
'product_id' => $product['product_id'],
'name' => $product['name'],
'model' => $product['model'],
'option' => $option_data,
'download' => $product['download'],
'quantity' => $product['quantity'],
'subtract' => $product['subtract'],
'price' => $product['price'],
'total' => $product['total'],
'tax' => $this->tax->getTax($product['price'], $product['tax_class_id']),
'reward' => $product['reward']
);
}
// Gift Voucher
$voucher_data = array();
if (!empty($this->session->data['vouchers'])) {
foreach ($this->session->data['vouchers'] as $voucher) {
$voucher_data[] = array(
'description' => $voucher['description'],
'code' => substr(md5(mt_rand()), 0, 10),
'to_name' => $voucher['to_name'],
'to_email' => $voucher['to_email'],
'from_name' => $voucher['from_name'],
'from_email' => $voucher['from_email'],
'voucher_theme_id' => $voucher['voucher_theme_id'],
'message' => $voucher['message'],
'amount' => $voucher['amount']
);
}
}
$data['products'] = $product_data;
$data['vouchers'] = $voucher_data;
$data['totals'] = $total_data;
$data['comment'] = $this->session->data['comment'];
$data['total'] = $total;
$query = $this->db->query("SELECT affiliate_code FROM " . DB_PREFIX . "customer WHERE language_id = '" . (int)$this->customer->getId() . "'");
//set cookie $query->rows;
if (isset($this->request->cookie['tracking'])) {
$this->load->model('affiliate/affiliate');
$affiliate_info = $this->model_affiliate_affiliate->getAffiliateByCode($this->request->cookie['tracking']);
$subtotal = $this->cart->getSubTotal();
if ($affiliate_info) {
$data['affiliate_id'] = $affiliate_info['affiliate_id'];
$data['commission'] = ($subtotal / 100) * $affiliate_info['commission'];
} else {
$data['affiliate_id'] = 0;
$data['commission'] = 0;
}
} else {
$data['affiliate_id'] = 0;
$data['commission'] = 0;
}
$data['language_id'] = $this->config->get('config_language_id');
$data['currency_id'] = $this->currency->getId();
$data['currency_code'] = $this->currency->getCode();
$data['currency_value'] = $this->currency->getValue($this->currency->getCode());
$data['ip'] = $this->request->server['REMOTE_ADDR'];
if (!empty($this->request->server['HTTP_X_FORWARDED_FOR'])) {
$data['forwarded_ip'] = $this->request->server['HTTP_X_FORWARDED_FOR'];
} elseif(!empty($this->request->server['HTTP_CLIENT_IP'])) {
$data['forwarded_ip'] = $this->request->server['HTTP_CLIENT_IP'];
} else {
$data['forwarded_ip'] = '';
}
if (isset($this->request->server['HTTP_USER_AGENT'])) {
$data['user_agent'] = $this->request->server['HTTP_USER_AGENT'];
} else {
$data['user_agent'] = '';
}
if (isset($this->request->server['HTTP_ACCEPT_LANGUAGE'])) {
$data['accept_language'] = $this->request->server['HTTP_ACCEPT_LANGUAGE'];
} else {
$data['accept_language'] = '';
}
$this->load->model('checkout/order');
$this->session->data['order_id'] = $this->model_checkout_order->addOrder($data);
$this->data['column_name'] = $this->language->get('column_name');
$this->data['column_model'] = $this->language->get('column_model');
$this->data['column_quantity'] = $this->language->get('column_quantity');
$this->data['column_price'] = $this->language->get('column_price');
$this->data['column_total'] = $this->language->get('column_total');
$this->data['products'] = array();
foreach ($this->cart->getProducts() as $product) {
$option_data = array();
foreach ($product['option'] as $option) {
if ($option['type'] != 'file') {
$value = $option['option_value'];
} else {
$filename = $this->encryption->decrypt($option['option_value']);
$value = utf8_substr($filename, 0, utf8_strrpos($filename, '.'));
}
$option_data[] = array(
'name' => $option['name'],
'value' => (utf8_strlen($value) > 20 ? utf8_substr($value, 0, 20) . '..' : $value)
);
}
$this->data['products'][] = array(
'product_id' => $product['product_id'],
'name' => $product['name'],
'model' => $product['model'],
'option' => $option_data,
'quantity' => $product['quantity'],
'subtract' => $product['subtract'],
'price' => $this->currency->format($this->tax->calculate($product['price'], $product['tax_class_id'], $this->config->get('config_tax'))),
'total' => $this->currency->format($this->tax->calculate($product['price'], $product['tax_class_id'], $this->config->get('config_tax')) * $product['quantity']),
'href' => $this->url->link('product/product', 'product_id=' . $product['product_id'])
);
}
// Gift Voucher
$this->data['vouchers'] = array();
if (!empty($this->session->data['vouchers'])) {
foreach ($this->session->data['vouchers'] as $voucher) {
$this->data['vouchers'][] = array(
'description' => $voucher['description'],
'amount' => $this->currency->format($voucher['amount'])
);
}
}
$this->data['totals'] = $total_data;
$this->data['payment'] = $this->getChild('payment/' . $this->session->data['payment_method']['code']);
} else {
$this->data['redirect'] = $redirect;
}
if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/checkout/confirm.tpl')) {
$this->template = $this->config->get('config_template') . '/template/checkout/confirm.tpl';
} else {
$this->template = 'default/template/checkout/confirm.tpl';
}
$this->response->setOutput($this->render());
}
}
?>
It can be done this way .
<?php
$query = $this->db->query("SELECT tracking_code FROM " . DB_PREFIX . "customer WHERE language_id = '" . (int)$this->customer->getId() . "'");
if(isset($_COOKIE['tracking'])){
setcookie('tracking', '', time()-1);
sleep(1); // sleep for 1 sec
setcookie('tracking', '$query->row["tracking_code"]', time()+60*60*24*30*12);
}else{
setcookie('tracking', '$query->row["tracking_code"]', time()+60*60*24*30*12);
}
?>
So in the if condition ,if your cookie named tracking is set than it will delete it with 1 sec and and apply you new value from $query . I hope this will work .
Related
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class index extends BaseController
{
public function __construct()
{
parent::__construct();
$this->load->model('P_pmb', 'p_pmb');
}
public function index()
{
$data['title'] = 'Dashboard';
$this->render('index/index', $data);
}
public function pendaftarprodi1()
{
$data['title'] = 'Grafik Berdasarkan Prodi 1';
$prodi = $this->p_pmb->listProdi();
foreach ($prodi as $key => $p) {
$prodi[$key]['jumlah'] = $this->p_pmb->jumlahPendaftarProdi1($p['id_prodi']);
$prodi[$key]['jumlah2'] = $this->p_pmb->jumlahPendaftarProdi2($p['id_prodi']);
$prodi[$key]['size'] = rand(10, 30);
}
//grafik 1
$result = null;
foreach ($prodi as $p => $prod) {
// if ($prod['jumlah'] > $sum) {
// $sum = $prod['jumlah'];
// $sliced = true;
// $selected = true;
// }
$result[$p] = [
"name" => $prod['nama_prodi'],
"jumlah" => $prod['jumlah'],
"y" => $prod['size'],
// "sliced" => $sliced,
// 'selected' => $selected
];
}
$data['pendaftar'] = $prodi;
$data['grafik1'] = json_encode($result);
$this->render('index/grafik1', $data);
}
public function pendaftarprodi2()
{
$data['title'] = 'Grafik Berdasarkan Prodi 2';
$prodi = $this->p_pmb->listProdi();
foreach ($prodi as $key => $p) {
$prodi[$key]['jumlah'] = $this->p_pmb->jumlahPendaftarProdi1($p['id_prodi']);
$prodi[$key]['jumlah2'] = $this->p_pmb->jumlahPendaftarProdi2($p['id_prodi']);
$prodi[$key]['size'] = rand(10, 30);
}
//grafik 2
$hasil = null;
foreach ($prodi as $p => $prod) {
$hasil[$p] = [
"name" => $prod['nama_prodi'],
"jumlah" => $prod['jumlah2'],
"y" => $prod['size'],
// "sliced" => $sliced,
// 'selected' => $selected
];
}
$data['pendaftar'] = $prodi;
$data['grafik2'] = json_encode($hasil);
$this->render('index/grafik2', $data);
}
public function pendaftarprestasi()
{
$pendaftarprestasi = $this->p_pmb->listpendaftarprestasi();
foreach ($pendaftarprestasi as $key => $p) {
$pendaftarprestasi[$key]['jumlah'] = $this->p_pmb->jumlahpendaftarprestasi($p['tingkat_prestasi']);
$pendaftarprestasi[$key]['size'] = rand(10, 30);
}
$result = null;
$sum = 0;
foreach ($pendaftarprestasi as $p => $pendpres) {
//if ($pendpres['jumlah'] > $sum) {
// $sum = $pendpres['jumlah'];
// $sliced = true;
// $selected = true;
// }
$result[$p] = [
"name" => $pendpres['tingkat_prestasi'],
'jumlah' => $pendpres['jumlah'],
'y' => $pendpres['size'],
// $sliced => $sliced,
// $selected => $selected
];
}
$data['pendaftarprestasi'] = $pendaftarprestasi;
$data['grafikprestasi'] = json_encode($result);
$this->render('index/grafikprestasi', $data);
}
public function jalurmasuk()
{
$pendaftar = $this->p_pmb->listjalurpendaftar();
foreach ($pendaftar as $key => $p) {
$pendaftar[$key]['jumlah'] = $this->p_pmb->jumlahjalurpendaftar($p['nama_jalur']);
$pendaftar[$key]['jumlah'] = rand(10, 30);
}
$result = null;
$sum = 0;
foreach ($pendaftar as $p => $jalmask) {
//if ($jalmask['jumlah'] > $sum) {
// $sum = $jalmask['jumlah'];
// $sliced = true;
// $selected = true;
// }
$result[$p] = [
"name" => $jalmask['nama_jalur'],
'jumlah' => $jalmask['jumlah'],
'y' => $jalmask['jumlah'],
// $sliced => $sliced,
// $selected => $selected
];
}
$data['jalur_masuk'] = $jalmask;
$data['grafikmasuk'] = json_encode($result);
$this->render('index/grafikmasuk', $data);
}
public function pendapatan()
{
$data['title'] = 'Grafik Pendapatan Berdasarkan Bank';
$bank = $this->p_pmb->listBank();
$pendaftar = $this->p_pmb->pendaftarBank();
$categories = null;
$lunas = null;
$belum_lunas = null;
$sumTotal = 0;
foreach ($bank as $i => $b) {
$categories[] = $b['bank'];
foreach ($pendaftar as $key => $value) {
if ($b['id_bank'] == $value['id_bank']) {
if ($value['is_bayar'] == '1') {
$sumTotal += intval($value['total']);
$lunas[] = intval($value['total']);
} else {
$belum_lunas[] = intval($value['total']);
}
}
}
}
$result[] = [
'name' => 'Pendapatan',
'data' => $lunas,
];
$data['subtitle'] = 'Total Pendapatan Rp.' . $sumTotal;
$grafik['id_bank'] = json_encode($result);
$grafik['categories'] = json_encode($categories);
$data['grafikpendapatan'] = $grafik;
$this->render('index/grafikpendapatan', $data);
}
public function bank()
{
$data['title'] = 'Grafik Pendapatan Berdasarkan Bank';
$bank = $this->p_pmb->listBank();
$pendaftar = $this->p_pmb->pendaftarBank();
$categories = null;
$lunas = null;
$belum_lunas = null;
$sumTotal = 0;
foreach ($bank as $i => $b) {
$categories[] = $b['bank'];
foreach ($pendaftar as $key => $value) {
if ($b['id_bank'] == $value['id_bank']) {
if ($value['is_bayar'] == '1') {
$sumTotal += intval($value['total']);
$lunas[] = intval($value['total']);
} else {
$sumTotal += $value['jumlah'];
$belum_lunas[] = intval($value['total']);
}
}
}
}
$result[] = [
'name' => 'Lunas',
'data' => $lunas,
];
$result[] = [
'name' => 'Belum Lunas',
'data' => $belum_lunas,
];
$data['subtitle'] = 'Total Pendaftar: ' . $sumTotal;
$data['id_bank'] = $bank;
$data['grafikbank'] = json_encode($result);
$this->render('index/grafikbank', $data);
}
}
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class BaseController extends CI_Controller
{
public function render($filename, $data)
{
$this->load->view('template/app_top', $data);
$this->load->view('template/template_scripts', $data);
$this->load->view($filename, $data);
$this->load->view('template/app_bottom', $data);
}
}
I have a application using Yii2 basic framework, and I'm using Kartik InputFile for upload file. The file successfully uploaded to the system, and the page also successfully redirect to next page, but a few second before the page redirect to next page, it display an error in progress bar like this
Why this widget show notification "upload failed" although the file successfully uploaded?
This is my code in _form.php:
<?php $form = ActiveForm::begin(); ?>
<?php
echo FileInput::widget([
'name' => 'file_uploads',
'language' => 'id',
'options' => [
'accept' => 'doc/*', 'file/*',
'multiple' => true,
'enableLabel' => true,
],
'pluginOptions' => [
'allowedFileExtensions' => ['xls', 'xlsx'],
'uploadUrl' => Url::to(['/pib/pib-data/create']),
'maxFileSize' => 1024,
'maxFileCount' => 1,
'showCaption' => false,
'showMessage'=>false,
'purifyHtml'=>false
]
]);
?>
<?php ActiveForm::end(); ?>
and this the code that I've used in controller:
<?php
public function actionCreate() {
$model = new PibData();
$connection = \Yii::$app->db;
$userId = Yii::$app->user->id;
if (Yii::$app->user->isGuest) {
return $this->redirect(['/site/login']);
}
$sqlHeader = "UPDATE pib_data SET is_exported = '1' WHERE user_id = '$userId'";
$exeQuery = Yii::$app->db->createCommand($sqlHeader)->execute();
$date = new DateTime('now', new \DateTimeZone('Asia/Jakarta'));
$created_at = $date->format('Y:m:d H:i:s');
$dirTrash = Yii::getAlias('#webroot/trash');
$dirSubTrash = Yii::getAlias('#webroot/trash/trash_pib');
if (!is_dir($dirTrash)) {
mkdir(Yii::getAlias('#webroot/trash'));
if (!is_dir($dirSubTrash)) {
mkdir(Yii::getAlias('#webroot/trash/trash_pib'));
}
} else {
if (!is_dir($dirSubTrash)) {
mkdir(Yii::getAlias('#webroot/trash/trash_pib'));
}
}
if (Yii::$app->request->post()) {
$file = UploadedFile::getInstancesByName('file_uploads');
$middleName = substr(md5(microtime() * 100000), rand(0, 9), 5);
if ($file !== null) {
$name = $userId . '_' . $middleName . '_' . date('Y-m-d') . '_' . $file[0]->getBaseName() . "." . $file[0]->getExtension();
$pathproduct = Yii::getAlias('#webroot/trash/trash_pib/') . $name;
$file[0]->saveAs($pathproduct);
Yii::$app->response->format = Response::FORMAT_JSON;
return [];
} else {
$error[] = "Silahkan pilih terlebih dahulu file" . "<strong>" . " Excel " . "</strong>" . "yang akan di convert.";
Yii::$app->session->setFlash('error', $error);
return $this->render('create', ['model' => $model]);
}
$modelUser = Users::find()->where(['id' => $userId])->one();
$parentId = $modelUser->parent_id;
$objPHPExcel = new \PHPExcel();
$fileName = Yii::getAlias('#webroot/trash/trash_pib/') . $name;
$inputFiles = fopen(Yii::getAlias('#webroot/trash/trash_pib/') . $name, "r");
try {
$inputFileType = \PHPExcel_IOFactory::identify($fileName);
$objReader = \PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($fileName);
} catch (Exception $ex) {
die('Error');
}
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestDataRow();
$highestColumn = $sheet->getHighestDataColumn();
$colNumber = PHPExcel_Cell::columnIndexFromString($highestColumn);
$col = $colNumber - 1;
$arrayData = [];
for ($row = 1; $row <= $highestRow; ++$row) {
$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, NULL, TRUE, FALSE);
$arrayData[] = array_map(function($values) {
$tempArray = [];
foreach ($values as $key => $value) {
$newKey = $key + 1;
$tempArray[] = $newKey . '_' . $value;
}
return $tempArray;
}, $rowData);
}
$arrayHeader = array_shift($arrayData);
$countArrayData = count($arrayData);
$countArrayHeader = count($arrayHeader[0]);
for ($i = 0; $i < $countArrayData; $i++) {
for ($j = 0; $j < $countArrayHeader; $j++) {
if ($j < 9) {
$finalData[$i][] = substr($arrayData[$i][0][$j], 2);
} else {
$finalData[$i][] = substr($arrayData[$i][0][$j], 3);
}
}
}
for ($x = 0; $x < $countArrayData; $x++) {
array_unshift($finalData[$x], "dummy");
}
$tempData = mysql_escape_string(json_encode($finalData));
$tempHeader = json_encode($arrayHeader);
$header = base64_encode($tempHeader);
$command_1 = "DELETE FROM pib_json_data WHERE user_id= '$userId'";
$query_1 = Yii::$app->db->createCommand($command_1)->execute();
$command_2 = "INSERT INTO pib_json_data(json_data, user_id, created_at) VALUES('$tempData', '$userId', '$created_at')";
$query_2 = Yii::$app->db->createCommand($command_2)->execute();
$_SESSION['header'] = $header;
$_SESSION['validHeader'] = 'validHeader';
return Yii::$app->response->redirect(['/pib/pib-header/select-header']);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
?>
anyhelp will be apreciated.
Thanks
Well... according to documentation, in "IMPORTANT" section:
You MUST send a valid JSON response from your server, else the upload
process will fail. Even if you do not encounter any error, you must at
least send an empty JSON object {} from your server.
So, i believe your code should look like this.
Controller :
<?php
public function actionCreate() {
$model = new PibData();
$connection = \Yii::$app->db;
$userId = Yii::$app->user->id;
if (Yii::$app->user->isGuest) {
return $this->redirect(['/site/login']);
}
$sqlHeader = "UPDATE pib_data SET is_exported = '1' WHERE user_id = '$userId'";
$exeQuery = Yii::$app->db->createCommand($sqlHeader)->execute();
$date = new DateTime('now', new \DateTimeZone('Asia/Jakarta'));
$created_at = $date->format('Y:m:d H:i:s');
$dirTrash = Yii::getAlias('#webroot/trash');
$dirSubTrash = Yii::getAlias('#webroot/trash/trash_pib');
if (!is_dir($dirTrash)) {
mkdir(Yii::getAlias('#webroot/trash'));
if (!is_dir($dirSubTrash)) {
mkdir(Yii::getAlias('#webroot/trash/trash_pib'));
}
} else {
if (!is_dir($dirSubTrash)) {
mkdir(Yii::getAlias('#webroot/trash/trash_pib'));
}
}
if (Yii::$app->request->post()) {
Yii::$app->response->format = Response::FORMAT_JSON;
$result = [];
$file = UploadedFile::getInstancesByName('file_uploads');
$middleName = substr(md5(microtime() * 100000), rand(0, 9), 5);
if ($file !== null) {
$name = $userId . '_' . $middleName . '_' . date('Y-m-d') . '_' . $file[0]->getBaseName() . "." . $file[0]->getExtension();
$pathproduct = Yii::getAlias('#webroot/trash/trash_pib/') . $name;
$file[0]->saveAs($pathproduct);
} else {
$error[] = "Silahkan pilih terlebih dahulu file" . "<strong>" . " Excel " . "</strong>" . "yang akan di convert.";
//Yii::$app->session->setFlash('error', $error);
//return $this->render('create', ['model' => $model]);
$result = [
'error' => $error
]; // change error notification used Kartik FileInput build-in error message
}
$modelUser = Users::find()->where(['id' => $userId])->one();
$parentId = $modelUser->parent_id;
$objPHPExcel = new \PHPExcel();
$fileName = Yii::getAlias('#webroot/trash/trash_pib/') . $name;
$inputFiles = fopen(Yii::getAlias('#webroot/trash/trash_pib/') . $name, "r");
try {
$inputFileType = \PHPExcel_IOFactory::identify($fileName);
$objReader = \PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($fileName);
} catch (Exception $ex) {
//die('Error');
$result = [
'error' => $ex
]; // change error notification used Kartik FileInput build-in error message
}
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestDataRow();
$highestColumn = $sheet->getHighestDataColumn();
$colNumber = PHPExcel_Cell::columnIndexFromString($highestColumn);
$col = $colNumber - 1;
$arrayData = [];
for ($row = 1; $row <= $highestRow; ++$row) {
$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, NULL, TRUE, FALSE);
$arrayData[] = array_map(function($values) {
$tempArray = [];
foreach ($values as $key => $value) {
$newKey = $key + 1;
$tempArray[] = $newKey . '_' . $value;
}
return $tempArray;
}, $rowData);
}
$arrayHeader = array_shift($arrayData);
$countArrayData = count($arrayData);
$countArrayHeader = count($arrayHeader[0]);
for ($i = 0; $i < $countArrayData; $i++) {
for ($j = 0; $j < $countArrayHeader; $j++) {
if ($j < 9) {
$finalData[$i][] = substr($arrayData[$i][0][$j], 2);
} else {
$finalData[$i][] = substr($arrayData[$i][0][$j], 3);
}
}
}
for ($x = 0; $x < $countArrayData; $x++) {
array_unshift($finalData[$x], "dummy");
}
$tempData = mysql_escape_string(json_encode($finalData));
$tempHeader = json_encode($arrayHeader);
$header = base64_encode($tempHeader);
$command_1 = "DELETE FROM pib_json_data WHERE user_id= '$userId'";
$query_1 = Yii::$app->db->createCommand($command_1)->execute();
$command_2 = "INSERT INTO pib_json_data(json_data, user_id, created_at) VALUES('$tempData', '$userId', '$created_at')";
$query_2 = Yii::$app->db->createCommand($command_2)->execute();
$_SESSION['header'] = $header;
$_SESSION['validHeader'] = 'validHeader';
//return Yii::$app->response->redirect(['/pib/pib-header/select-header']);
$result = [
'url' => Url::to(['/pib/pib-header/select-header'])
]; // return url variable to be used by jquery
return $result;
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
?>
View :
<?php
use yii\web\View;
...
<?php $form = ActiveForm::begin(); ?>
<?php
echo FileInput::widget([
'name' => 'file_uploads',
'language' => 'id',
'options' => [
'accept' => 'doc/*', 'file/*',
'multiple' => true,
'enableLabel' => true,
],
'pluginOptions' => [
'allowedFileExtensions' => ['xls', 'xlsx'],
'uploadUrl' => Url::to(['/pib/pib-data/create']),
'maxFileSize' => 1024,
'maxFileCount' => 1,
'showCaption' => false,
'showMessage'=>false,
'purifyHtml'=>false
]
]);
?>
<?php ActiveForm::end(); ?>
<?php
$this->registerJS("
$('#input-id').on('fileuploaded', function(event, data, previewId, index) { // replace input-id with your file input id
var response = data.response;
$(location).attr('href', response.url); // redirect use jquery
});", View::POS_END);
Hope it's help.
Happy coding. :)
<?php
function import_sales_request(){
$hostname = '****';
$username = '****';
$password = '*****';
global $base_url;
$inbox = imap_open($hostname, $username, $password) or die('Cannot connect to Gmail: ' . imap_last_error());
$emails = imap_search($inbox, 'UNSEEN', SE_UID);
$emailDates = array();
if ($emails) {
//$count = 1;
rsort($emails);
foreach ($emails as $email_number) {
$overview = imap_fetch_overview($inbox, $email_number, FT_UID);
$message = imap_fetchbody($inbox, $email_number, 2, FT_UID);
$structure = imap_fetchstructure($inbox, $email_number, FT_UID);
$emailDates[$email_number] = $overview[0]->date;
$message_header = imap_fetchheader($inbox, $email_number, 1);
$message_body = imap_fetchbody($inbox, $email_number, "1.1", FT_UID);
//file_put_contents(drupal_get_path('module', 'pricecal') . "/mail/" . $email_number . ".htm", nl2br($message_header) . $message_body);
$attachments = array();
if (isset($structure->parts) && count($structure->parts)) {
for ($i = 0; $i < count($structure->parts); $i++) {
$attachments[$i] = array('is_attachment' => false, 'filename' => '', 'name' => '', 'attachment' => '');
if ($structure->parts[$i]->ifdparameters) {
foreach ($structure->parts[$i]->dparameters as $object) {
if (strtolower($object->attribute) == 'filename') {
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['filename'] = $object->value;
}
}
}
if ($structure->parts[$i]->ifparameters) {
foreach ($structure->parts[$i]->parameters as $object) {
if (strtolower($object->attribute) == 'name') {
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['name'] = $object->value;
}
}
}
if ($attachments[$i]['is_attachment']) {
$attachments[$i]['attachment'] = imap_fetchbody($inbox, $email_number, $i + 1, FT_UID);
if ($structure->parts[$i]->encoding == 3) {
$attachments[$i]['attachment'] = base64_decode($attachments[$i]['attachment']);
} elseif ($structure->parts[$i]->encoding == 4) {
$attachments[$i]['attachment'] = quoted_printable_decode($attachments[$i]['attachment']);
}
}
}
}
foreach ($attachments as $attachment) {
if ($attachment['is_attachment'] == 1) {
$filename = $attachment['name'];
$fileinfo = pathinfo($filename);
if (in_array($fileinfo['extension'], array('csv', 'xls', 'xlsx'))) {
if (empty($filename))
$filename = $attachment['filename'];
if (empty($filename))
$filename = time() . ".dat";
$fp = fopen(drupal_get_path('module', 'pricecal') . "/mail/".$email_number."-".clean($overview[0]->from). "-" . clean($filename), "w+");
fwrite($fp, $attachment['attachment']);
fclose($fp);
}
}
}
//if($count++ >= $max_emails) break;
imap_setflag_full($inbox, $email_number, "\\Seen \\Flagged", ST_UID);
}
}
imap_close($inbox);
import_sales_request_into_database($emailDates);
return true;
}
/*
* Insert new and revised request into database
*/
function import_sales_request_into_database($emailDates = '', $flag = false) {
global $user;
global $base_url;
include_once(drupal_get_path('module', 'pricecal') . '/excel/Classes/PHPExcel/IOFactory.php');
$filelist = file_scan_directory(drupal_get_path('module', 'pricecal') . '/mail', '/^.*\.(csv|CSV|xls|XLS|xlsx|XLSX)$/');
if (!empty($filelist)) {
foreach ($filelist as $list) {
$objPHPExcel = PHPExcel_IOFactory::load($list->uri);
$sheetData = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
$resultArray = array();
$part_no = array();
$start_part_no = 0;
$temp = 0;
$ctoarray = array();
$transaction = db_transaction(); //start database transaction
try {
/*
* Prepare array structure to insert as a new or revised request
* $flag = true - it is not importing, it is from home page browse button
*/
$resultArray['requester_name'] = empty($sheetData[1]['B']) ? '' : $sheetData[1]['B'];
$resultArray['requester_email'] = empty($sheetData[2]['B']) ? '' : $sheetData[2]['B'];
$resultArray['request_number'] = empty($sheetData[3]['B']) ? '' : $sheetData[3]['B'];
$resultArray['customer_name'] = empty($sheetData[4]['B']) ? '' : $sheetData[4]['B'];
$resultArray['segment'] = empty($sheetData[5]['B']) ? '' : $sheetData[5]['B'];
$resultArray['dmu_cmr'] = empty($sheetData[6]['B']) ? '' : $sheetData[6]['B'];
$resultArray['cyborg_no'] = empty($sheetData[7]['B']) ? '' : $sheetData[7]['B'];
$resultArray['duty_type'] = empty($sheetData[8]['B']) ? '' : $sheetData[8]['B'];
$resultArray['country_code'] = empty($sheetData[9]['B']) ? '' : $sheetData[9]['B'];
$resultArray['billing_type'] = empty($sheetData[10]['B']) ? '' : $sheetData[10]['B'];
$resultArray['tier_1_partner'] = empty($sheetData[11]['B']) ? '' : $sheetData[11]['B'];
$resultArray['tier_2_partner'] = empty($sheetData[12]['B']) ? '' : $sheetData[12]['B'];
$resultArray['requested_tp'] = empty($sheetData[13]['B']) ? '' : (float)str_replace(',', '', $sheetData[13]['B']);
$resultArray['deal_justification'] = empty($sheetData[14]['B']) ? '' : $sheetData[14]['B'];
$cto_counter = 0 ;
$ctocounterarray = array();
if (!empty($sheetData)) {
foreach ($sheetData as $key => $value) {
if (!empty($resultArray)) {
if ($value['B'] == 'Part Number*') {
$start_part_no = $key;
}
if ($start_part_no != 0 && $key > $start_part_no && $value['B'] != '') {
if (($value['A'] == 'CTO' || $value['A'] == 'Regular') && $temp == 0) {
if($value['A'] == 'CTO'){
$part_no[] = array($value['B'] => array($value['C'], 'primary-cto'));
$cto_counter++;
$ctocounterarray[] = $value['B'];
}else{
$part_no[] = array($value['B'] => array($value['C'], 'primary'));
}
}
if ($value['A'] == 'Bundle-Base' && trim($value['B']) != "" && !empty($value['B'])) {
$temp = 1;
$new_part_number = $value['B'];
}
if ($temp) {
if($value['A'] == "Bundle-Remove"){
$value['C'] = -1 * abs($value['C']);
}
$part_no[] = array($value['B'] => array($value['C'], $value['A']));
$ctoarray[$new_part_number][] = array($value['B'] => array($value['C'], $value['A']));
}
if ($value['A'] == 'CTO' && $temp == 1 && in_array($value['B'], $ctocounterarray)) {
$temp = 0;
$cto_counter--;
}
}
$resultArray['part_no'] = $part_no;
}
}
}
$continue_flag = true;
if($cto_counter !== 0){
$transaction->rollback();
drupal_set_message(t($list->filename . ' import failed' . PHP_EOL), 'error');
import_sales_request_logfile($list->filename, 0,$resultArray['requester_email'],$resultArray['requester_name']);
$continue_flag = false;
$mail_id = ($flag) ? 0 : strstr($list->filename, '-', true); //split email id
}
$newRequest = '';
$quotationSummary = '';
$quotationLineItems = array();
$mail_id = ($flag) ? 0 : strstr($list->filename, '-', true); //split email id
$date = date("Y-m-d H:i:s"); //insert current date time in database
$email_date = (isset($emailDates) && isset($emailDates[$mail_id]) && array_key_exists($mail_id, $emailDates)) ? date("Y-m-d H:i:s", strtotime($emailDates[$mail_id])) : $date;
if (!$flag) {
$result = db_select('quotation_request', 'qr')->fields('qr', array('email_number'))->condition('email_number', $mail_id, '=')->execute()->fetchAssoc();
if (!empty($result)) {
drupal_set_message(t($list->filename . ' already imported.' . PHP_EOL), 'warning');
//import_sales_request_logfile($list->filename, 2);
$continue_flag = false;
}
}
$request_type = 'new';
if ($continue_flag && !empty($resultArray)) {
$request_number = '';
if (empty($resultArray['request_number'])) {
$request_number = import_sales_request_number(); //if the request is new
} else {
$revision = '';
$revise_request_number = array(trim($resultArray['request_number']),trim($resultArray['request_number']).'_R1',trim($resultArray['request_number']).'_R2',trim($resultArray['request_number']).'_R3',trim($resultArray['request_number']).'_R4',trim($resultArray['request_number']).'_R5',trim($resultArray['request_number']).'_R6',trim($resultArray['request_number']).'_R7',trim($resultArray['request_number']).'_R8',trim($resultArray['request_number']).'_R19',trim($resultArray['request_number']).'_R10',trim($resultArray['request_number']).'_R11',trim($resultArray['request_number']).'_R12',trim($resultArray['request_number']).'_R13',trim($resultArray['request_number']).'_R14',trim($resultArray['request_number']).'_R15',trim($resultArray['request_number']).'_R16',trim($resultArray['request_number']).'_R17');
$result = db_select('quotation_request', 'qr')->fields('qr', array('request_number'))->condition('request_number',$revise_request_number , 'IN')->execute();
$revision = $result->rowCount();
if (!empty($revision) && $revision > 0) {
$request_number = $resultArray['request_number'] . '_R' . $revision;
$request_type = 'revise';
} else {
drupal_set_message(t($list->filename . ' has invalid request number.' . PHP_EOL), 'warning');
import_sales_request_logfile($list->filename, 3,$resultArray['requester_email'],$resultArray['requester_name']);
$continue_flag = false;
}
}
/*
* If all OK then it will create a new or revised request in database
*/
if ($continue_flag) {
/*
* $newRequest - will have inserted request number
*/
try {
$newRequest = db_insert('quotation_request')->fields(array('email_number' => $mail_id, 'request_number' => $request_number,'request_type'=>$request_type, 'requester_name' => $resultArray['requester_name'], 'requester_email' => $resultArray['requester_email'], 'customer_name' => $resultArray['customer_name'], 'duty_type' => $resultArray['duty_type'], 'billing_type' => $resultArray['billing_type'], 'segment' => $resultArray['segment'],'request_file' => $list->filename, 'request_date_time' => $email_date, 'dmu_cmr' => $resultArray['dmu_cmr'], 'cyborg_no' => $resultArray['cyborg_no'], 'country_code' => $resultArray['country_code'], 'tier_1_partner' => $resultArray['tier_1_partner'], 'tier_2_partner' => $resultArray['tier_2_partner'], 'requested_tp' => $resultArray['requested_tp'], 'deal_justification' => $resultArray['deal_justification'], 'status' => 'generate quotation', 'created' => $date, 'uid' => $user->uid))->execute();
} catch (PDOException $e) {
drupal_set_message(t('Error: %message', array('%message' => $e->getMessage())), 'error');
}
if (!empty($newRequest)) {
try {
$quotationSummary = db_insert('quotation_summary')->fields(array('quotation_request_id' => $newRequest, 'created' => $date, 'uid' => $user->uid))->execute();
} catch (PDOException $e) {
drupal_set_message(t('Error: %message', array('%message' => $e->getMessage())), 'error');
}
if (!empty($quotationSummary) && !empty($resultArray['part_no'])) {
$base_part_no_id = 0;
foreach ($resultArray['part_no'] as $key => $value) {
$part_no = key($value);
$quantity = (isset($value[$part_no][0])) ? $value[$part_no][0] : 0;
$part_no_behaviour = (isset($value[$part_no][1])) ? $value[$part_no][1] : 'primary';
$query = db_select('cost_tape', 'ct')->fields('ct', array('cost_tape_id'))->fields('ctp', array('bmc_price'))->condition('ct.part_number', $part_no);
$query->leftJoin('cost_tape_price', 'ctp', 'ct.cost_tape_id=ctp.cost_tape_id');
$query->orderBy('ctp.created', 'DESC')->range(0, 1);
$resultArrayAssoc = $query->execute()->fetchAll();
if (count($resultArrayAssoc) > 0) {
foreach ($resultArrayAssoc as $node) {
$cost_tape_id = $node->cost_tape_id;
$bmc_price = $node->bmc_price;
$not_found_part_number = "";
}
} else {
$not_found_part_number = $part_no;
$cost_tape_id = null;
$bmc_price = 0.0;
}
if($part_no_behaviour == 'CTO' || $part_no_behaviour == 'primary-cto'){
$not_found_part_number = $part_no;
$not_found_part_desc = "Server";
$cost_tape_id = null;
}else{
$not_found_part_desc = "";
}
try {
$quotationLineItem = db_insert('quotation_lineitems')->fields(array('quotation_request_id' => $newRequest, 'quotation_summary_id' => $quotationSummary, 'cost_tape_id' => $cost_tape_id, 'not_found_part_no' => $not_found_part_number, 'not_found_desc' => $not_found_part_desc, 'part_behavior' => $part_no_behaviour, 'ref_id' => $base_part_no_id, 'bmc_price' => $bmc_price, 'qty' => $quantity, 'created' => $date, 'uid' => $user->uid))->execute();
$quotationLineItems[] = $quotationLineItem;
if ($part_no_behaviour == 'Bundle-Base' && isset($quotationLineItem)) {
$base_part_no_id = $quotationLineItem;
// $quotationLineItems[] = $quotationLineItem;
$num_updated = db_update('quotation_lineitems') // Table name no longer needs {}
->fields(array('ref_id' => $base_part_no_id))
->condition('quotation_lineitems_id', $base_part_no_id, '=')
->execute();
}
if ($part_no_behaviour == 'CTO' && $base_part_no_id != 0) {
$base_part_no_id = 0;
}
} catch (PDOException $e) {
drupal_set_message(t('Error: %message', array('%message' => $e->getMessage())), 'error');
}
}
}
}
}
}
if ($continue_flag && $newRequest && $quotationSummary && !empty($quotationLineItems)) {
drupal_set_message(t($list->filename . ' imported successfully' . PHP_EOL));
import_sales_request_logfile($list->filename, 1);
$requester_name = $resultArray['requester_name'];
$requester_email_id = $resultArray['requester_email'];
$params = array(
'subject' => "Price quote request has been received successfully. Customer Name :- ".$resultArray['customer_name']. " Request No :- ".$request_number,
'body' => "<p>Hi ".$requester_name.",<br/></p>
<p>Thanks for your email. DCG Pricing team will work on your price quote request and will shortly share the quotation with you.</p>
<p>Your request number is ".$request_number.".</p>
<p>Customer Name : ".$resultArray['customer_name'].".</p>
<p>
<strong>Attachment: </strong><a href='" . $base_url . "/sites/all/modules/pricecal/tmp/" . $list->filename . "'>Click here</a><br/>
</p>
<p>The dcgpricing#lenovo.com mailbox is dedicated to handle only price quote requests. For any other queries, please reach out to respective pricers.</p>
<p>*** This is a system generated email, please do not reply to this email ***</p>
<p>Thanks,<p/><p>DCG Pricing Team</p>",
);
drupal_mail('pricecal', 'success_sales_request', $resultArray['requester_email'], language_default(), $params);
$customer_name = $resultArray['customer_name'];
$params = array(
'subject' => "New price quote request received",
'body' => "<p>Hi Team,<br/></p>
<p>The DCG pricing tool has successfully uploaded a price quote input request and is now available for your working.</p>
<ul>
<li>Request Number : ".$request_number."</li>
<li>Customer name : ".$customer_name."</li>
<li>Requestor name : ".$requester_name."</li>
<li>Requestor email id : ".$requester_email_id."</li>
<li>Deal justification : ".$resultArray['deal_justification']."</li>
</ul>
<p>
<strong>Attachment: </strong><a href='" . $base_url . "/sites/all/modules/pricecal/tmp/" . $list->filename . "'>Click here</a><br/>
</p>
<p>*** This is a system generated email, please do not reply to this email ***</p>
<p>Thanks,<p/><p>DCG Pricing Team</p>",
);
//drupal_mail('pricecal', 'import_success_email', 'chintan.p#blueoceanmi.com', language_default(), $params);
} else if ($continue_flag) {
$transaction->rollback();
//drupal_set_message(t($list->filename . ' import failed' . PHP_EOL), 'error');
import_sales_request_logfile($list->filename, 0, $resultArray['requester_email'],$resultArray['requester_name']);
}
} catch (Exception $e) {
$transaction->rollback();
drupal_set_message(t($list->filename . ' import failed' . PHP_EOL), 'error');
import_sales_request_logfile($list->filename, 0, $resultArray['requester_email'],$resultArray['requester_name']);
}
rename($list->uri, drupal_get_path('module', 'pricecal') . '/tmp/' . $list->filename);
}
} else {
drupal_set_message(t('No email founds.' . PHP_EOL), 'warning'); //if no email found with unread status
}
return true;
}
/*
* Create new request number and check weather request number already exists
*/
function import_sales_request_number($length = 6) {
$selectPartId = db_query("select count(request_number) as request_number from quotation_request")->fetchAssoc();
if(empty($selectPartId['request_number'])){
$token = 101;
}else{
$token = $selectPartId['request_number'] + 101;
}
return $token;
}
function import_sales_request_logfile($filename = '', $update = 0,$requester_emailId = '',$requesterName = '') {
global $base_url;
$log_file_path = drupal_get_path('module', 'pricecal') . '/logs/' . date('Y-M-d') . '.dat';
$msg = ($update) ? $filename . ' imported success' . PHP_EOL : $filename . ' import failed' . PHP_EOL;
if ($update == 0) {
$msg = $filename . ' import failed' . PHP_EOL;
} else if ($update == 1) {
$msg = $filename . ' imported success' . PHP_EOL;
} else if ($update == 2) {
$msg = $filename . ' already imported' . PHP_EOL;
} else if ($update == 3) {
$msg = $filename . ' invalid request number' . PHP_EOL;
}
file_put_contents($log_file_path, date('h:i:sa ') . $msg, FILE_APPEND | LOCK_EX);
if(empty($requesterName)){
$requesterName = "Team";
}
if (in_array($update, array(0, 2, 3))) {
$mail_id = strstr($filename, '-', true);
$params = array(
'subject' => $msg,
'body' => "<p>Hi ".$requesterName.",<br/></p>
<p>The DCG pricing tool has failed to upload a price quote input request(attached here) . Request you to please review and correct the template.
</p>
<p>
<strong>Attachment: </strong><a href='" . $base_url . "/sites/all/modules/pricecal/tmp/" . $filename . "'>Click here</a><br/>
</p>
<p>*** This is a system generated email, please do not reply to this email ***</p>
<p>Thanks,<br/>DCG Pricing Team</p>",
);
if(!empty($requester_emailId)){
//drupal_mail('pricecal', 'import_success_email', 'chintan.p#blueoceanmi.com,'.$requester_emailId, language_default(), $params);
}else{
// drupal_mail('pricecal', 'import_success_email', 'chintan.p#blueoceanmi.com', language_default(), $params);
}
}
}
function clean($string) {
$string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
return preg_replace('/[^A-Za-z0-9\-#.]/', '', $string); // Removes special chars.
}
?>
I'm facing really serious issue on live server this code works fine 2 days before but now its saying memory exhausted, i tried to increase memory but still not working. Can you please somebody help me.
I have a error on my model I am trying to work out I have unserialize($query->row('permission')) but for some reason I get a error.
Can not seem to work it out very strange to me. Not sure what to do or how to fix it.
A PHP Error was encountered
Severity: Warning
Message: unserialize() expects parameter 1 to be string, array given
Filename: user/users_group_model.php
Line Number: 16
Get User Group Model Function
public function getUserGroup($user_group_id) {
$query = $this->db->query("SELECT DISTINCT * FROM " . $this->db->dbprefix . "user_group WHERE user_group_id = '" . (int)$user_group_id . "'");
$user_group = array(
'name' => $query->row('name'),
'permission' => unserialize($query->row('permission'))
);
return $user_group;
}
Controller Function
public function getForm() {
$data['heading_title'] = $this->lang->line('heading_title');
$data['text_select_all'] = $this->lang->line('text_select_all');
$data['text_unselect_all'] = $this->lang->line('text_unselect_all');
$data['entry_name'] = $this->lang->line('entry_name');
$data['entry_access'] = $this->lang->line('entry_access');
$data['entry_modify'] = $this->lang->line('entry_modify');
$data['button_save'] = $this->lang->line('button_save');
$data['button_cancel'] = $this->lang->line('button_cancel');
$data['breadcrumbs'] = array();
$data['breadcrumbs'][] = array(
'text' => $this->lang->line('text_home'),
'href' => site_url('admin/dashboard')
);
$data['breadcrumbs'][] = array(
'text' => $this->lang->line('heading_title'),
'href' => site_url('admin/users_group')
);
$data['cancel'] = site_url('admin/users_group');
$user_group_id = $this->uri->segment(4);
$data['user_group_id'] = $user_group_id;
$user_group_info = $this->users_group_model->getUserGroup($user_group_id);
if (isset($this->request->post['name'])) {
$data['name'] = $this->request->post['name'];
} elseif (!empty($user_group_info)) {
$data['name'] = $user_group_info['name'];
} else {
$data['name'] = '';
}
$this->load->model('admin/user/users_group_model');
$ignore = array(
'blank',
'dashboard',
'column_left',
'menu',
'startup',
'login',
'logout',
'forgotten',
'reset',
'not_found',
'permission',
'footer',
'header'
);
$data['permissions'] = array();
$files = glob(APPPATH . 'modules/admin/' . 'controllers/*/*.php');
foreach ($files as $file) {
$part = explode('/', dirname($file));
$permission = basename($file, '.php');
if (!in_array($permission, $ignore)) {
$data['permissions'][] = $permission;
}
}
$this->load->library('request');
if (isset($this->request->post['permission']['access'])) {
$data['access'] = $this->request->post['permission']['access'];
} elseif (isset($user_group_info['permission']['access'])) {
$data['access'] = $user_group_info['permission']['access'];
} else {
$data['access'] = array();
}
$this->load->view('user/users_group_form', $data);
}
I have fixed the problem was had to add !empty post method above the name area and now working. It has removed all errors by doing it this way.
public function getForm() {
$this->load->model('admin/user/users_group_model');
$this->load->library('request');
$data['heading_title'] = $this->lang->line('heading_title');
$data['text_select_all'] = $this->lang->line('text_select_all');
$data['text_unselect_all'] = $this->lang->line('text_unselect_all');
$data['entry_name'] = $this->lang->line('entry_name');
$data['entry_access'] = $this->lang->line('entry_access');
$data['entry_modify'] = $this->lang->line('entry_modify');
$data['button_save'] = $this->lang->line('button_save');
$data['button_cancel'] = $this->lang->line('button_cancel');
$data['breadcrumbs'] = array();
$data['breadcrumbs'][] = array(
'text' => $this->lang->line('text_home'),
'href' => site_url('admin/dashboard')
);
$data['breadcrumbs'][] = array(
'text' => $this->lang->line('heading_title'),
'href' => site_url('admin/users_group')
);
$data['cancel'] = site_url('admin/users_group');
$user_group_id = $this->uri->segment(4);
$data['user_group_id'] = $user_group_id;
if (!empty($user_group_id) && $this->request->server['REQUEST_METHOD'] != 'POST') {
$user_group_info = $this->users_group_model->getUserGroup($user_group_id );
}
if (isset($this->request->post['name'])) {
$data['name'] = $this->request->post['name'];
} elseif (!empty($user_group_info)) {
$data['name'] = $user_group_info['name'];
} else {
$data['name'] = '';
}
$ignore = array(
'blank',
'dashboard',
'column_left',
'menu',
'startup',
'login',
'logout',
'forgotten',
'reset',
'not_found',
'permission',
'footer',
'header'
);
$data['permissions'] = array();
$files = glob(APPPATH . 'modules/admin/' . 'controllers/*/*.php');
foreach ($files as $file) {
$part = explode('/', dirname($file));
$permission = basename($file, '.php');
if (!in_array($permission, $ignore)) {
$data['permissions'][] = $permission;
}
}
if (isset($this->request->post['permission']['access'])) {
$data['access'] = $this->request->post['permission']['access'];
} elseif (isset($user_group_info['permission']['access'])) {
$data['access'] = $user_group_info['permission']['access'];
} else {
$data['access'] = array();
}
$this->load->view('user/users_group_form', $data);
}
I have installed background_image.xml inside vqmod xml folder to change background image in opencart. This plugins works perfectly but throwing a notice at the header.
Notice: Undefined variable: server in C:\wamp\www\opencart\vqmod\vqcache\vq2-catalog_controller_common_header.php on line 54
this is the plugin link:
http://www.opencart.com/index.php?route=extension/extension/info&extension_id=16044&filter_search=background&filter_license=0
I also tried error_reporting(0) but no result. Here is the code of vqmod\vqcache\vq2-catalog_controller_common_header.php
class ControllerCommonHeader extends Controller {
protected function index() {
$this->data['title'] = $this->document->getTitle();
if (isset($this->request->server['HTTPS']) && (($this->request->server['HTTPS'] == 'on') || ($this->request->server['HTTPS'] == '1'))) {
$this->data['base'] = $this->config->get('config_ssl');
} else {
$this->data['base'] = $this->config->get('config_url');
}
$this->data['description'] = $this->document->getDescription();
$this->data['keywords'] = $this->document->getKeywords();
$this->data['links'] = $this->document->getLinks();
$this->data['styles'] = $this->document->getStyles();
$this->data['scripts'] = $this->document->getScripts();
$this->data['lang'] = $this->language->get('code');
$this->data['direction'] = $this->language->get('direction');
$this->data['google_analytics'] = html_entity_decode($this->config->get('config_google_analytics'), ENT_QUOTES, 'UTF-8');
// Whos Online
if ($this->config->get('config_customer_online')) {
$this->load->model('tool/online');
if (isset($this->request->server['REMOTE_ADDR'])) {
$ip = $this->request->server['REMOTE_ADDR'];
} else {
$ip = '';
}
if (isset($this->request->server['HTTP_HOST']) && isset($this->request->server['REQUEST_URI'])) {
$url = 'http://' . $this->request->server['HTTP_HOST'] . $this->request->server['REQUEST_URI'];
} else {
$url = '';
}
if (isset($this->request->server['HTTP_REFERER'])) {
$referer = $this->request->server['HTTP_REFERER'];
} else {
$referer = '';
}
$this->model_tool_online->whosonline($ip, $this->customer->getId(), $url, $referer);
}
if ($this->config->get('config_position')) {
$this->data['position'] = $this->config->get('config_position');
} else {
$this->data['position'] = '';
}
if ($this->config->get('config_backgroundimage') && file_exists(DIR_IMAGE . $this->config->get('config_backgroundimage'))) {
$this->data['backgroundimage'] = $server . 'image/' . $this->config->get('config_backgroundimage');
} else {
$this->data['backgroundimage'] = '';
}
$this->language->load('common/header');
if (isset($this->request->server['HTTPS']) && (($this->request->server['HTTPS'] == 'on') || ($this->request->server['HTTPS'] == '1'))) {
$server = HTTPS_IMAGE;
} else {
$server = HTTP_IMAGE;
}
if ($this->config->get('config_icon') && file_exists(DIR_IMAGE . $this->config->get('config_icon'))) {
$this->data['icon'] = $server . $this->config->get('config_icon');
} else {
$this->data['icon'] = '';
}
$this->data['name'] = $this->config->get('config_name');
if ($this->config->get('config_logo') && file_exists(DIR_IMAGE . $this->config->get('config_logo'))) {
$this->data['logo'] = $server . $this->config->get('config_logo');
} else {
$this->data['logo'] = '';
}
$this->data['text_home'] = $this->language->get('text_home');
$this->data['text_wishlist'] = sprintf($this->language->get('text_wishlist'), (isset($this->session->data['wishlist']) ? count($this->session->data['wishlist']) : 0));
$this->data['text_shopping_cart'] = $this->language->get('text_shopping_cart');
$this->data['text_search'] = $this->language->get('text_search');
$this->data['text_welcome'] = sprintf($this->language->get('text_welcome'), $this->url->link('account/login', '', 'SSL'), $this->url->link('account/register', '', 'SSL'));
$this->data['text_logged'] = sprintf($this->language->get('text_logged'), $this->url->link('account/account', '', 'SSL'), $this->customer->getFirstName(), $this->url->link('account/logout', '', 'SSL'));
$this->data['text_account'] = $this->language->get('text_account');
$this->data['text_checkout'] = $this->language->get('text_checkout');
$this->data['home'] = $this->url->link('common/home');
$this->data['wishlist'] = $this->url->link('account/wishlist', '', 'SSL');
$this->data['logged'] = $this->customer->isLogged();
$this->data['account'] = $this->url->link('account/account', '', 'SSL');
$this->data['shopping_cart'] = $this->url->link('checkout/cart');
$this->data['checkout'] = $this->url->link('checkout/checkout', '', 'SSL');
if (isset($this->request->get['filter_name'])) {
$this->data['filter_name'] = $this->request->get['filter_name'];
} else {
$this->data['filter_name'] = '';
}
// Menu
$this->load->model('catalog/category');
$this->load->model('catalog/product');
$this->data['categories'] = array();
$categories = array();
foreach ($categories as $category) {
if ($category['top']) {
$children_data = array();
$children = $this->model_catalog_category->getCategories($category['category_id']);
foreach ($children as $child) {
$data = array(
'filter_category_id' => $child['category_id'],
'filter_sub_category' => true
);
$product_total = $this->model_catalog_product->getTotalProducts($data);
$children_data[] = array(
'name' => $child['name'] . ($this->config->get('config_product_count') ? ' (' . $product_total . ')' : ''),
'href' => $this->url->link('product/category', 'path=' . $category['category_id'] . '_' . $child['category_id'])
);
}
// Level 1
$this->data['categories'][] = array(
'name' => $category['name'],
'children' => $children_data,
'column' => $category['column'] ? $category['column'] : 1,
'href' => $this->url->link('product/category', 'path=' . $category['category_id'])
);
}
}
$this->children = array(
'module/language',
'module/supermenu',
'module/supermenu_settings',
'module/currency',
'module/cart'
);
$this->data['categories'] = array();
if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/common/header.tpl')) {
$this->template = $this->config->get('config_template') . '/template/common/header.tpl';
} else {
$this->template = 'default/template/common/header.tpl';
}
$this->render();
}
}
Can anyone help me to solve this problem?
The problem is that - in default opencart, the below lines of code exists at the begginning of catalog/controller/common/header.php (line 6):
if (isset($this->request->server['HTTPS']) && (($this->request->server['HTTPS'] == 'on') || ($this->request->server['HTTPS'] == '1'))) {
$server = $this->config->get('config_ssl');
} else {
$server = $this->config->get('config_url');
}
In your case the above lines code got removed. Please check the file vqmod\vqcache\vq2-catalog_controller_common_header.php and make necessary changes to bring back the above lines of code. If you're using more vqmod files, check them also.
An easy fix is to change (probably in your xml file):
$this->data['backgroundimage'] = $server . 'image/' . $this->config->get('config_backgroundimage');
to
$this->data['backgroundimage'] = $this->data['base'] . 'image/' . $this->config->get('config_backgroundimage');
Have a nice day !