/**
  * Assign template vars related to page content
  * @see FrontController::initContent()
  */
 public function initContent()
 {
     parent::initContent();
     $this->productSort();
     // Override default configuration values: cause the new products page must display latest products first.
     if (!Tools::getIsset('orderway') || !Tools::getIsset('orderby')) {
         $this->orderBy = 'date_add';
         $this->orderWay = 'DESC';
     }
     $nbProducts = (int) Product::getNewProducts($this->context->language->id, null, null, true);
     $this->pagination($nbProducts);
     $products = Product::getNewProducts($this->context->language->id, (int) $this->p - 1, (int) $this->n, false, $this->orderBy, $this->orderWay);
     $this->addColorsToProductList($products);
     $this->context->smarty->assign(array('HOOK_LEFT_COLUMN' => Hook::exec('displayLeftColumn'), 'products' => $products, 'add_prod_display' => Configuration::get('PS_ATTRIBUTE_CATEGORY_DISPLAY'), 'nbProducts' => (int) $nbProducts, 'homeSize' => Image::getSize(ImageType::getFormatedName('home')), 'comparator_max_item' => Configuration::get('PS_COMPARATOR_MAX_ITEM')));
     if ($this->ajax) {
         $product_list = $this->context->smarty->fetch(_PS_THEME_DIR_ . 'product-list.tpl');
         $pagination = $this->context->smarty->fetch(_PS_THEME_DIR_ . 'pagination.tpl');
         $nbLeftProducts = $nbProducts - ($this->n * ($this->p - 1) + count($products));
         $nbLeftProductsPercentage = ($nbProducts - $nbLeftProducts) / $nbProducts * 100;
         echo Tools::jsonEncode(array('productList' => utf8_encode($product_list), 'pagination' => $pagination, 'nbRenderedProducts' => $nbProducts, 'nbLeftProducts' => $nbLeftProducts, 'nbLeftProductsPercentage' => $nbLeftProductsPercentage));
         die;
     } else {
         $this->setTemplate(_PS_THEME_DIR_ . 'new-products.tpl');
     }
 }
Example #2
0
 public function sendQuestion()
 {
     if (Tools::getValue('enviar_mensaje')) {
         $params = array();
         $params['nombre'] = pSQL(Tools::getValue('nombre', ''));
         $params['email'] = pSQL(Tools::getValue('email', ''));
         $params['ciudad'] = pSQL(Tools::getValue('ciudad', ''));
         $params['provincia'] = pSQL(Tools::getValue('provincia', ''));
         $params['consulta'] = pSQL(Tools::getValue('consulta', ''));
         $params['id_producto'] = (int) Tools::getValue('id_producto', 0);
         $params['date_add'] = date('Y-m-d H:i:s', strtotime('now'));
         $params['validado'] = 0;
         DB::getInstance()->insert('lgconsultas', $params);
         $id_consulta = Db::getInstance()->Insert_ID();
         if ($id_consulta) {
             $consulta = Db::getInstance()->getRow('SELECT * FROM `' . _DB_PREFIX_ . 'lgconsultas` WHERE id_consulta=' . (int) $id_consulta);
             $producto = Db::getInstance()->getValue('SELECT name FROM ' . _DB_PREFIX_ . 'product_lang WHERE id_product=' . (int) $consulta['id_producto'] . ' AND id_lang=' . (int) Configuration::get('PS_LANG_DEFAULT'));
             $enlace = new Link();
             $urlproducto = $enlace->getProductLink($consulta['id_producto']);
             $templateVars = array('id_consulta' => $id_consulta, '{consulta}' => pSQL($consulta['consulta']), '{nombre}' => pSQL($consulta['nombre']), '{email}' => pSQL($consulta['email']), '{provincia}' => pSQL($consulta['provincia']), '{ciudad}' => pSQL($consulta['ciudad']), '{producto}' => $producto, '{urlproducto}' => $urlproducto);
             if (!Mail::Send((int) Configuration::get('PS_LANG_DEFAULT'), 'consulta_enviada', $this->l('You have received a new question about a product'), $templateVars, Configuration::get('LG_CONSULTAS_EMAIL'), null, Configuration::get('LG_CONSULTAS_EMAIL'), Configuration::get('PS_SHOP_NAME'), null, null, _PS_MODULE_DIR_ . 'lgconsultas/mails/')) {
                 $out = array('status' => 'nok', 'msg' => $this->l('An error occurred while sending your question'));
             } else {
                 $out = array('status' => 'ok', 'msg' => $this->l('Your question has been sent'));
             }
         } else {
             $out = array('status' => 'nok', 'msg' => $this->l('An error occurred while trying to add your question'));
         }
         echo Tools::jsonEncode($out);
         die;
     }
 }
Example #3
0
 /**
  * Performs a request and gets the results
  *
  * @param string $method - A String containing the name of the method to be invoked.
  * @param array $params - An Array of objects to pass as arguments to the method.
  * @return array
  */
 public function __call($method, $params)
 {
     static $request_id;
     // generating uniuqe id per process
     $request_id++;
     // check if given params are correct
     $validate_params = array(false === is_scalar($method) => 'Method name has no scalar value', false === is_array($params) => 'Params must be given as array');
     $this->checkForErrors($validate_params);
     // send params as an object or an array
     $params = $this->parameters_structure == 'object' ? $params[0] : array_values($params);
     // Request (method invocation)
     $request = Tools::jsonEncode(array('jsonrpc' => '2.0', 'method' => $method, 'params' => $params, 'id' => $request_id));
     // if is_debug mode is true then add url and request to is_debug
     $this->debug('Url: ' . $this->url . "\r\n", false);
     $this->debug('Request: ' . $request . "\r\n", false);
     $response = $this->getResponse($request);
     // if is_debug mode is true then add response to is_debug and display it
     $this->debug('Response: ' . $response . "\r\n", true);
     // decode and create array ( can be object, just set to false )
     $response = Tools::jsonDecode($response, true);
     // check if response is correct
     $validate_params = array($response['id'] != $request_id => 'Request id: ' . $request_id . ' is different from Response id: ' . $response['id']);
     if (isset($response['error'])) {
         $error_message = 'Request have return error: ' . $response['error']['message'] . '; ' . "\n" . 'Request: ' . $request . '; ';
         if (isset($response['error']['data'])) {
             $error_message .= "\n" . 'Error data: ' . $response['error']['data'];
         }
         $validate_params[!is_null($response['error'])] = $error_message;
     }
     $this->checkForErrors($validate_params);
     return $response['result'];
 }
 public function preProcess()
 {
     global $cart;
     if ($id_product = (int) Tools::getValue('id_product')) {
         $this->product = new Product($id_product, true, self::$cookie->id_lang);
     }
     if (Tools::isSubmit('ajax')) {
         if (Tools::isSubmit('submitCustomizedDatas')) {
             $this->pictureUpload($this->product, $cart);
             $this->textRecord($this->product, $cart);
             $this->formTargetFormat();
         }
         if (count($this->errors)) {
             die(Tools::jsonEncode(array('hasErrors' => true, 'errors' => $this->errors)));
         } else {
             die(Tools::jsonEncode(array('hasErrors' => false, 'conf' => Tools::displayError('Customization saved successfully.'))));
         }
     }
     if (!Validate::isLoadedObject($this->product)) {
         header('HTTP/1.1 404 Not Found');
         header('Status: 404 Not Found');
     } else {
         $this->canonicalRedirection();
     }
     parent::preProcess();
 }
 public function renderForm()
 {
     $update_htaccess = Tools::modRewriteActive() && (file_exists('.htaccess') && is_writable('.htaccess') || is_writable(dirname('.htaccess')));
     $this->multiple_fieldsets = true;
     if (!$update_htaccess) {
         $desc_virtual_uri = array('<span class="warning_mod_rewrite">' . $this->l('You need to activate URL Rewriting if you want to add a virtual URL.') . '</span>');
     } else {
         $desc_virtual_uri = array($this->l('You can use this option if you want to create a store with a URL that doesn\'t exist on your server (e.g. if you want your store to be available with the URL www.my-prestashop.com/my-store/shoes/, you have to set shoes/ in this field, assuming that my-store/ is your Physical URL).'), '<strong>' . $this->l('URL rewriting must be activated on your server to use this feature.') . '</strong>');
     }
     $this->fields_form = array(array('form' => array('legend' => array('title' => $this->l('URL options'), 'icon' => 'icon-cogs'), 'input' => array(array('type' => 'select', 'label' => $this->l('Shop'), 'name' => 'id_shop', 'onchange' => 'checkMainUrlInfo(this.value);', 'options' => array('optiongroup' => array('query' => Shop::getTree(), 'label' => 'name'), 'options' => array('query' => 'shops', 'id' => 'id_shop', 'name' => 'name'))), array('type' => 'switch', 'label' => $this->l('Main URL'), 'name' => 'main', 'class' => 't', 'values' => array(array('id' => 'main_on', 'value' => 1), array('id' => 'main_off', 'value' => 0)), 'desc' => array($this->l('If you set this URL as the Main URL for the selected shop, all URLs set to this shop will be redirected to this URL (you can only have one Main URL per shop).'), array('text' => $this->l('Since the selected shop has no main URL, you have to set this URL as the Main URL.'), 'id' => 'mainUrlInfo'), array('text' => $this->l('The selected shop already has a Main URL. Therefore, if you set this one as the Main URL, the older of the two will be set as the normal URL.'), 'id' => 'mainUrlInfoExplain'))), array('type' => 'switch', 'label' => $this->l('Enabled'), 'name' => 'active', 'required' => false, 'class' => 't', 'values' => array(array('id' => 'active_on', 'value' => 1), array('id' => 'active_off', 'value' => 0)))), 'submit' => array('title' => $this->l('Save')))), array('form' => array('legend' => array('title' => $this->l('Shop URL'), 'icon' => 'icon-shopping-cart'), 'input' => array(array('type' => 'text', 'label' => $this->l('Domain'), 'name' => 'domain', 'size' => 50), array('type' => 'text', 'label' => $this->l('Domain SSL'), 'name' => 'domain_ssl', 'size' => 50)), 'submit' => array('title' => $this->l('Save')))));
     if (!defined('_PS_HOST_MODE_')) {
         $this->fields_form[1]['form']['input'] = array_merge($this->fields_form[1]['form']['input'], array(array('type' => 'text', 'label' => $this->l('Physical URL'), 'name' => 'physical_uri', 'desc' => $this->l('This is the physical folder for your store on the server. Leave this field empty if your store is installed on the root path (e.g. if your store is available at www.my-prestashop.com/my-store/, you input my-store/ in this field).'), 'size' => 50)));
     }
     $this->fields_form[1]['form']['input'] = array_merge($this->fields_form[1]['form']['input'], array(array('type' => 'text', 'label' => $this->l('Virtual URL'), 'name' => 'virtual_uri', 'desc' => $desc_virtual_uri, 'size' => 50, 'hint' => !$update_htaccess ? $this->l('Warning: URL rewriting (e.g. mod_rewrite for Apache) seems to be disabled. If your URL doesn\'t work, please check with your host provider on how to activate URL rewriting.') : null), array('type' => 'text', 'label' => $this->l('Your final URL will be'), 'name' => 'final_url', 'size' => 76, 'readonly' => true)));
     if (!($obj = $this->loadObject(true))) {
         return;
     }
     self::$currentIndex = self::$currentIndex . '&id_shop=' . $obj->id;
     $current_shop = Shop::initialize();
     $list_shop_with_url = array();
     foreach (Shop::getShops(false, null, true) as $id) {
         $list_shop_with_url[$id] = (bool) count(ShopUrl::getShopUrls($id));
     }
     $this->tpl_form_vars = array('js_shop_url' => Tools::jsonEncode($list_shop_with_url));
     $this->fields_value = array('domain' => Validate::isLoadedObject($obj) ? $this->getFieldValue($obj, 'domain') : $current_shop->domain, 'domain_ssl' => Validate::isLoadedObject($obj) ? $this->getFieldValue($obj, 'domain_ssl') : $current_shop->domain_ssl, 'physical_uri' => Validate::isLoadedObject($obj) ? $this->getFieldValue($obj, 'physical_uri') : $current_shop->physical_uri, 'active' => true);
     return parent::renderForm();
 }
function ajax_agile_getcustomers()
{
    ${${"GLOBALS"}["jjszcyoinwyy"]} = explode(" ", Tools::getValue("customer_search"));
    ${"GLOBALS"}["btkmsumgqi"] = "customers";
    $lwjbynsy = "searches";
    $mfzpveyc = "to_return";
    $bmwjhsn = "customers";
    ${"GLOBALS"}["mcqemkddxvk"] = "searches";
    $cccuivsxp = "to_return";
    ${${"GLOBALS"}["kglmxvwgfexa"]} = array();
    ${${"GLOBALS"}["mcqemkddxvk"]} = array_unique(${$lwjbynsy});
    foreach (${${"GLOBALS"}["jjszcyoinwyy"]} as ${${"GLOBALS"}["dotono"]}) {
        $mimdxaoxdl = "results";
        if (!empty(${${"GLOBALS"}["dotono"]}) && (${$mimdxaoxdl} = Customer::searchByName(${${"GLOBALS"}["dotono"]}))) {
            foreach (${${"GLOBALS"}["itmfakpwu"]} as ${${"GLOBALS"}["dbgjiec"]}) {
                ${"GLOBALS"}["cgwtffyvk"] = "result";
                ${${"GLOBALS"}["kglmxvwgfexa"]}[${${"GLOBALS"}["dbgjiec"]}["id_customer"]] = ${${"GLOBALS"}["cgwtffyvk"]};
            }
        }
    }
    if (count(${${"GLOBALS"}["btkmsumgqi"]})) {
        ${$cccuivsxp} = array("customers" => ${$bmwjhsn}, "found" => true);
    } else {
        ${$mfzpveyc} = array("found" => false);
    }
    return Tools::jsonEncode(${${"GLOBALS"}["nduihox"]});
}
 public function getFields()
 {
     if (parent::validateFields()) {
         ShopgateLogger::getInstance()->log('Validation for shopgate database fields invalid', ShopgateLogger::LOGTYPE_ERROR);
     }
     if ($this->shopgate_order instanceof ShopgateOrder) {
         $this->shopgate_order = pSQL(base64_encode(serialize($this->shopgate_order)));
     }
     if (is_array($this->comments)) {
         if (method_exists("Tools", "jsonEncode")) {
             $encodedData = Tools::jsonEncode($this->comments);
         } else {
             $encodedData = json_encode($this->comments);
         }
         $this->comments = pSQL(base64_encode($encodedData));
     } else {
         $this->comments = pSQL($this->comments);
     }
     $fields = array();
     $fields['id_cart'] = (int) $this->id_cart;
     $fields['id_order'] = (int) $this->id_order;
     $fields['shopgate_order'] = pSQL(base64_encode(serialize($this->shopgate_order)));
     $fields['order_number'] = pSQL($this->order_number);
     $fields['shipping_service'] = pSQL($this->shipping_service);
     $fields['shipping_cost'] = (double) $this->shipping_cost;
     $fields['shop_number'] = pSQL($this->shop_number);
     $fields['comments'] = $this->comments;
     $fields['status'] = (int) $this->status;
     $fields['tracking_number'] = pSQL($this->tracking_number);
     $fields['is_sent_to_shopgate'] = (int) $this->is_sent_to_shopgate;
     return $fields;
 }
 public function run()
 {
     $this->init();
     $this->preProcess();
     if (Tools::getValue('ajax') == 'true') {
         if (Tools::getIsset('summary')) {
             if (Configuration::get('PS_ORDER_PROCESS_TYPE') == 1) {
                 if (self::$cookie->id_customer) {
                     $customer = new Customer((int) self::$cookie->id_customer);
                     $groups = $customer->getGroups();
                 } else {
                     $groups = array(1);
                 }
                 if ((int) self::$cart->id_address_delivery) {
                     $deliveryAddress = new Address((int) self::$cart->id_address_delivery);
                 }
                 $result = array('carriers' => Carrier::getCarriersForOrder((int) Country::getIdZone((isset($deliveryAddress) and (int) $deliveryAddress->id) ? (int) $deliveryAddress->id_country : (int) Configuration::get('PS_COUNTRY_DEFAULT')), $groups));
             }
             $result['summary'] = self::$cart->getSummaryDetails();
             $result['customizedDatas'] = Product::getAllCustomizedDatas((int) self::$cart->id);
             $result['HOOK_SHOPPING_CART'] = Module::hookExec('shoppingCart', $result['summary']);
             $result['HOOK_SHOPPING_CART_EXTRA'] = Module::hookExec('shoppingCartExtra', $result['summary']);
             die(Tools::jsonEncode($result));
         } else {
             $this->includeCartModule();
         }
     } else {
         $this->setMedia();
         $this->displayHeader();
         $this->process();
         $this->displayContent();
         $this->displayFooter();
     }
 }
 public function addQuickLink()
 {
     if (!isset($this->className) || empty($this->className)) {
         return false;
     }
     $this->validateRules();
     if (count($this->errors) <= 0) {
         $this->object = new $this->className();
         $this->copyFromPost($this->object, $this->table);
         $exists = Db::getInstance()->getValue('SELECT id_quick_access FROM ' . _DB_PREFIX_ . 'quick_access WHERE link = "' . pSQL($this->object->link) . '"');
         if ($exists) {
             return true;
         }
         $this->beforeAdd($this->object);
         if (method_exists($this->object, 'add') && !$this->object->add()) {
             $this->errors[] = Tools::displayError('An error occurred while creating an object.') . ' <b>' . $this->table . ' (' . Db::getInstance()->getMsgError() . ')</b>';
         } elseif (($_POST[$this->identifier] = $this->object->id) && $this->postImage($this->object->id) && !count($this->errors) && $this->_redirect) {
             PrestaShopLogger::addLog(sprintf($this->l('%s addition', 'AdminTab', false, false), $this->className), 1, null, $this->className, (int) $this->object->id, true, (int) $this->context->employee->id);
             $this->afterAdd($this->object);
         }
     }
     $this->errors = array_unique($this->errors);
     if (!empty($this->errors)) {
         $this->errors['has_errors'] = true;
         $this->ajaxDie(Tools::jsonEncode($this->errors));
         return false;
     }
     return $this->getQuickAccessesList();
 }
Example #10
0
 public static function loadPageDefault()
 {
     $langId = Context::getContext()->language->id;
     $shopId = Context::getContext()->shop->id;
     $groupID = intval($_POST['groupID']);
     $type = $_POST['type'];
     $itemId = intval($_POST['itemId']);
     $page = intval($_POST['page']);
     $itemWidth = intval($_POST['itemWidth']);
     $itemHeight = round($_POST['itemHeight'], 3);
     $css = 'width: ' . $itemWidth . 'px; height:' . $itemHeight . "px;";
     $group = DB::getInstance()->getRow("Select * From " . _DB_PREFIX_ . "groupcategory_groups Where id = " . $groupID);
     $response = '';
     $products = array();
     if ($group) {
         $module = new GroupCategory();
         $itemConfig = json_decode($group['itemConfig']);
         if (!$itemConfig->countItem || (int) $itemConfig->countItem <= 0) {
             $pageSize = 3;
         } else {
             $pageSize = $itemConfig->countItem;
         }
         $offset = $page * $pageSize;
         if ($itemId == 0) {
             $arrSubCategory = GroupCategoryLibraries::getCategoryIds($group['categoryId']);
             $arrSubCategory[] = $group['categoryId'];
             if ($type == 'saller') {
                 $products = GroupCategoryLibraries::getProducts_Sales($langId, $arrSubCategory, null, false, $pageSize, $offset);
             } elseif ($type == 'view') {
                 $products = GroupCategoryLibraries::getProducts_View($langId, $arrSubCategory, null, false, $pageSize, $offset);
             } elseif ($type == 'special') {
                 $products = GroupCategoryLibraries::getProducts_Special($langId, $arrSubCategory, null, false, $pageSize, $offset);
             } elseif ($type == 'arrival') {
                 $products = GroupCategoryLibraries::getProducts_AddDate($langId, $arrSubCategory, null, false, $pageSize, $offset);
             } else {
                 if ($group['type_default'] == 'saller') {
                     $products = GroupCategoryLibraries::getProducts_Sales($langId, $arrSubCategory, null, false, $pageSize, $offset);
                 } elseif ($group['type_default'] == 'view') {
                     $products = GroupCategoryLibraries::getProducts_View($langId, $arrSubCategory, null, false, $pageSize, $offset);
                 } elseif ($group['type_default'] == 'special') {
                     $products = GroupCategoryLibraries::getProducts_Special($langId, $arrSubCategory, null, false, $pageSize, $offset);
                 } else {
                     $products = GroupCategoryLibraries::getProducts_AddDate($langId, $arrSubCategory, null, false, $pageSize, $offset);
                 }
             }
         } else {
             $item = DB::getInstance()->getRow("Select * From " . _DB_PREFIX_ . "groupcategory_items Where id = " . $itemId);
             if ($item) {
                 $arrSubCategory = GroupCategoryLibraries::getCategoryIds($item['categoryId']);
                 $arrSubCategory[] = $item['categoryId'];
                 $products = GroupCategoryLibraries::getProducts_AddDate($langId, $arrSubCategory, null, false, $pageSize, $offset);
             }
         }
         if ($products) {
             $response = $module->generationHtml_default($products, $css);
         }
     }
     die(Tools::jsonEncode($response));
 }
 public function processBulkcssexport()
 {
     $order_box = Tools::getValue('orderBox');
     if (empty($order_box)) {
         $this->displayWarning($this->l('You must selected orders for the export'));
         return;
     }
     Tools::redirectAdmin('../modules/chronopost/importExport.php?shared_secret=' . Configuration::get('CHRONOPOST_SECRET') . '&cible=CSS&orders=' . implode(';', Tools::getValue('orderBox')) . '&multi=' . addslashes(Tools::jsonEncode(Tools::getValue('multi'))));
 }
 public function ajaxProcessGamificationTasks()
 {
     if (!Configuration::get('GF_INSTALL_CALC')) {
         $this->processRefreshData();
         $this->processInstallCalculation();
         Configuration::updateGlobalValue('GF_INSTALL_CALC', 1);
     }
     die(Tools::jsonEncode(array('refresh_data' => $this->processRefreshData(), 'daily_calculation' => $this->processMakeDailyCalculation(), 'advice_validation' => $this->processAdviceValidation(), 'advices_to_display' => $this->processGetAdvicesToDisplay(), 'level_badge_validation' => $this->processLevelAndBadgeValidation(), 'header_notification' => $this->module->renderHeaderNotification())));
 }
Example #13
0
 public function setErrorMessage($message)
 {
     $old_message = $this->cookie->{self::DPD_GROUP_ERROR_MESSAGE};
     if ($old_message && Validate::isSerializedArray($old_message)) {
         $old_message = Tools::jsonDecode($old_message);
         $message = array_merge($message, $old_message);
     }
     $this->cookie->{self::DPD_GROUP_ERROR_MESSAGE} = is_array($message) ? Tools::jsonEncode($message) : $message;
 }
 protected function update()
 {
     if (Tools::isSubmit('saveBtn')) {
         $config = [];
         $config['show_barcode'] = Tools::getValue('show_barcode');
         Configuration::updateValue($this->name, Tools::jsonEncode($config));
         return $this->displayConfirmation('Settings updated');
     }
 }
 /**
  * Assign template vars related to page content
  * @see FrontController::initContent()
  */
 public function initContent()
 {
     $original_query = Tools::getValue('q');
     $query = Tools::replaceAccentedChars(urldecode($original_query));
     if ($this->ajax_search) {
         $searchResults = Search::find((int) Tools::getValue('id_lang'), $query, 1, 10, 'position', 'desc', true);
         if (is_array($searchResults)) {
             foreach ($searchResults as &$product) {
                 $product['product_link'] = $this->context->link->getProductLink($product['id_product'], $product['prewrite'], $product['crewrite']);
             }
             Hook::exec('actionSearch', array('expr' => $query, 'total' => count($searchResults)));
         }
         $this->ajaxDie(Tools::jsonEncode($searchResults));
     }
     //Only controller content initialization when the user use the normal search
     parent::initContent();
     $product_per_page = isset($this->context->cookie->nb_item_per_page) ? (int) $this->context->cookie->nb_item_per_page : Configuration::get('PS_PRODUCTS_PER_PAGE');
     if ($this->instant_search && !is_array($query)) {
         $this->productSort();
         $this->n = abs((int) Tools::getValue('n', $product_per_page));
         $this->p = abs((int) Tools::getValue('p', 1));
         $search = Search::find($this->context->language->id, $query, 1, 10, 'position', 'desc');
         Hook::exec('actionSearch', array('expr' => $query, 'total' => $search['total']));
         $nbProducts = $search['total'];
         $this->pagination($nbProducts);
         $this->addColorsToProductList($search['result']);
         $this->context->smarty->assign(array('products' => $search['result'], 'search_products' => $search['result'], 'nbProducts' => $search['total'], 'search_query' => $original_query, 'instant_search' => $this->instant_search, 'homeSize' => Image::getSize(ImageType::getFormatedName('home'))));
     } elseif (($query = Tools::getValue('search_query', Tools::getValue('ref'))) && !is_array($query)) {
         $this->productSort();
         $this->n = abs((int) Tools::getValue('n', $product_per_page));
         $this->p = abs((int) Tools::getValue('p', 1));
         $original_query = $query;
         $query = Tools::replaceAccentedChars(urldecode($query));
         $search = Search::find($this->context->language->id, $query, $this->p, $this->n, $this->orderBy, $this->orderWay);
         if (is_array($search['result'])) {
             foreach ($search['result'] as &$product) {
                 $product['link'] .= (strpos($product['link'], '?') === false ? '?' : '&') . 'search_query=' . urlencode($query) . '&results=' . (int) $search['total'];
             }
         }
         Hook::exec('actionSearch', array('expr' => $query, 'total' => $search['total']));
         $nbProducts = $search['total'];
         $this->pagination($nbProducts);
         $this->addColorsToProductList($search['result']);
         $this->context->smarty->assign(array('products' => $search['result'], 'search_products' => $search['result'], 'nbProducts' => $search['total'], 'search_query' => $original_query, 'homeSize' => Image::getSize(ImageType::getFormatedName('home'))));
     } elseif (($tag = urldecode(Tools::getValue('tag'))) && !is_array($tag)) {
         $nbProducts = (int) Search::searchTag($this->context->language->id, $tag, true);
         $this->pagination($nbProducts);
         $result = Search::searchTag($this->context->language->id, $tag, false, $this->p, $this->n, $this->orderBy, $this->orderWay);
         Hook::exec('actionSearch', array('expr' => $tag, 'total' => count($result)));
         $this->addColorsToProductList($result);
         $this->context->smarty->assign(array('search_tag' => $tag, 'products' => $result, 'search_products' => $result, 'nbProducts' => $nbProducts, 'homeSize' => Image::getSize(ImageType::getFormatedName('home'))));
     } else {
         $this->context->smarty->assign(array('products' => array(), 'search_products' => array(), 'pages_nb' => 1, 'nbProducts' => 0));
     }
     $this->context->smarty->assign(array('add_prod_display' => Configuration::get('PS_ATTRIBUTE_CATEGORY_DISPLAY'), 'comparator_max_item' => Configuration::get('PS_COMPARATOR_MAX_ITEM')));
     $this->setTemplate(_PS_THEME_DIR_ . 'search.tpl');
 }
 private static function jsonOrUrlEncode($data)
 {
     if (function_exists('json_encode')) {
         return array(true, json_encode($data));
     } elseif (method_exists('Tools', 'jsonEncode')) {
         return array(true, Tools::jsonEncode($data));
     } else {
         return array(false, http_build_query($data));
     }
 }
 public function displayAjaxCheckFiles()
 {
     $this->file_list = array('missing' => array(), 'updated' => array());
     $xml = @simplexml_load_file('http://api.prestashop.com/xml/md5/' . _PS_VERSION_ . '.xml');
     if (!$xml) {
         die(Tools::jsonEncode($this->file_list));
     }
     $this->getListOfUpdatedFiles($xml->ps_root_dir[0]);
     die(Tools::jsonEncode($this->file_list));
 }
Example #18
0
 /**
  * Make a request to the Syspay API
  * @param  Syspay_Merchant_Request $request The request to send to the API
  * @return mixed The response to the request
  * @throws Syspay_Merchant_RequestException If the request could not be processed by the API
  */
 public function request(Syspay_Merchant_Request $request)
 {
     $this->body = $this->headers = $this->data = null;
     $headers = array('Accept: application/json', 'X-Wsse: ' . $this->generateAuthHeader($this->username, $this->secret));
     $url = rtrim($this->baseUrl, '/') . '/' . ltrim($request->getPath(), '/');
     $ch = curl_init();
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     curl_setopt($ch, CURLOPT_HEADER, true);
     curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
     // TODO: verify ssl and provide certificate in package
     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
     $method = Tools::strtoupper($request->getMethod());
     // Per-method special handling
     switch ($method) {
         case 'PUT':
         case 'POST':
             $body = Tools::jsonEncode($request->getData());
             array_push($headers, 'Content-Type: application/json');
             array_push($headers, 'Content-Length: ' . Tools::strlen($body));
             curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
             break;
         case 'GET':
             $queryParams = $request->getData();
             if (is_array($queryParams)) {
                 $url .= '?' . http_build_query($queryParams);
             }
             break;
         case 'DELETE':
             break;
         default:
             throw new Exception('Unsupported method given: ' . $method);
     }
     curl_setopt($ch, CURLOPT_URL, $url);
     curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
     curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
     $response = curl_exec($ch);
     if ($response === false) {
         throw new Exception(curl_error($ch), curl_errno($ch));
     }
     $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
     list($headers, $body) = explode("\r\n\r\n", $response, 2);
     $this->headers = $headers;
     $this->body = $body;
     if (!in_array($httpCode, array(200, 201))) {
         throw new Syspay_Merchant_RequestException($httpCode, $headers, $body);
     }
     $decoded = Tools::jsonDecode($body);
     if ($decoded instanceof stdClass && isset($decoded->data) && $decoded->data instanceof stdClass) {
         $this->data = $decoded->data;
         return $request->buildResponse($decoded->data);
     } else {
         throw new Syspay_Merchant_UnexpectedResponseException('Unable to decode response from json', $body);
     }
     return false;
 }
 public function processLogin()
 {
     require_once dirname(__FILE__) . '../../../../modules/designer/designer.php';
     $themeName = trim(Tools::getValue('theme_name'));
     $passwd = trim(Tools::getValue('passwd'));
     $email = trim(Tools::getValue('email'));
     $domain = getSessionDomain($themeName);
     $version = function_exists('theme_get_manifest_version') ? '&ver=' . theme_get_manifest_version($themeName) : '';
     $desktop = function_exists('getDesktopParams') ? getDesktopParams() : '';
     if (empty($email)) {
         $this->errors[] = Tools::displayError('E-mail is empty');
     } elseif (!Validate::isEmail($email)) {
         $this->errors[] = Tools::displayError('Invalid e-mail address');
     }
     if (empty($passwd)) {
         $this->errors[] = Tools::displayError('Password is blank');
     } elseif (!Validate::isPasswd($passwd)) {
         $this->errors[] = Tools::displayError('Invalid password');
     }
     if (!count($this->errors)) {
         $this->context->employee = new Employee();
         $is_employee_loaded = $this->context->employee->getByemail($email, $passwd);
         $employee_associated_shop = $this->context->employee->getAssociatedShops();
         if (!$is_employee_loaded) {
             $this->errors[] = Tools::displayError('Employee does not exist or password is incorrect.');
             $this->context->employee->logout();
         } elseif (empty($employee_associated_shop) && !$this->context->employee->isSuperAdmin()) {
             $this->errors[] = Tools::displayError('Employee does not manage any shop anymore (shop has been deleted or permissions have been removed).');
             $this->context->employee->logout();
         } else {
             $this->context->employee->remote_addr = ip2long(Tools::getRemoteAddr());
             $cookie = Context::getContext()->cookie;
             $cookie->id_employee = $this->context->employee->id;
             $cookie->email = $this->context->employee->email;
             $cookie->profile = $this->context->employee->id_profile;
             $cookie->passwd = $this->context->employee->passwd;
             $cookie->remote_addr = $this->context->employee->remote_addr;
             $cookie->write();
             if (Tools::getIsset('theme_name')) {
                 $url = $this->context->link->getAdminLink('AdminAjax') . '&ajax=1' . $domain . $version . $desktop;
             } else {
                 $tab = new Tab((int) $this->context->employee->default_tab);
                 $url = $this->context->link->getAdminLink($tab->class_name);
             }
             if (Tools::isSubmit('ajax')) {
                 die(Tools::jsonEncode(array('hasErrors' => false, 'redirect' => $url)));
             } else {
                 $this->redirect_after = $url;
             }
         }
     }
     if (Tools::isSubmit('ajax')) {
         die(Tools::jsonEncode(array('hasErrors' => true, 'errors' => $this->errors)));
     }
 }
 public static function getResApi($url, $verb, $params = null)
 {
     if (is_null($url) || is_null($verb) || !in_array($verb, array('GET', 'POST'))) {
         // $this->_html .= $this->displayError($this->l('Error In Configuration Of The Api'));
         return false;
     }
     $url_api = $url;
     $params_string = null;
     if (count($params)) {
         if ($verb == 'GET') {
             $params_string = http_build_query($params);
             $url_api .= '?' . $params_string;
         } elseif ($verb == 'POST') {
             $params_string = Tools::jsonEncode($params);
         }
     }
     $curl_obj = curl_init();
     curl_setopt($curl_obj, CURLOPT_URL, $url_api);
     // if ($verb == 'POST' && count($params))
     // {
     //     curl_setopt($curl_obj, CURLOPT_POST, true);
     //     curl_setopt($curl_obj, CURLOPT_POSTFIELDS, $params_string);
     //     curl_setopt($curl_obj, CURLOPT_HTTPHEADER, array(
     //         'Content-Type: application/json',
     //         'Content-Length: ' . strlen($params_string)
     //     ));
     // }
     if ($verb == 'POST') {
         curl_setopt($curl_obj, CURLOPT_POST, true);
         if (count($params)) {
             curl_setopt($curl_obj, CURLOPT_POSTFIELDS, $params_string);
             curl_setopt($curl_obj, CURLOPT_HTTPHEADER, array('Source-Id: ks-prestashop-1-rc-1-10', 'Content-Type: application/json', 'Content-Length: ' . Tools::strlen($params_string)));
         } else {
             curl_setopt($curl_obj, CURLOPT_HTTPHEADER, array('Source-Id: ks-prestashop-1-rc-1-10', 'Content-Type: application/json', 'Content-Length: 0'));
         }
     } else {
         curl_setopt($curl_obj, CURLOPT_HTTPHEADER, array('Source-Id: ks-prestashop-1-rc-1-10'));
     }
     curl_setopt($curl_obj, CURLOPT_RETURNTRANSFER, true);
     curl_setopt($curl_obj, CURLOPT_SSL_VERIFYPEER, false);
     curl_setopt($curl_obj, CURLOPT_NOSIGNAL, true);
     curl_setopt($curl_obj, CURLOPT_CONNECTTIMEOUT, 30);
     curl_setopt($curl_obj, CURLOPT_TIMEOUT, 30);
     $res_exec = curl_exec($curl_obj);
     $curl_errno = curl_errno($curl_obj);
     //$curl_error = curl_error($curl_obj);
     curl_close($curl_obj);
     if ($curl_errno) {
         // $this->_html .= $this->displayError($this->l('Error In API ') . $url . strval($curl_errno) . ' : ' . $curl_error);
         return false;
     } else {
         return Tools::jsonDecode($res_exec, true);
     }
 }
Example #21
0
 public function hookAjaxCallSearch($city_search)
 {
     if (empty($city_search)) {
         return null;
     }
     $result = City::getCitySearch($city_search);
     if (is_array($result) && count($result)) {
         die(Tools::jsonEncode($result));
     }
     return null;
 }
Example #22
0
 public static function returnAjax($redirect = null, $social_customer = null)
 {
     $return = array('hasError' => false);
     if ($redirect) {
         $return['redirect'] = $redirect;
     }
     if ($social_customer) {
         $return['customer'] = array('provider' => $social_customer->getProvider(), 'username' => $social_customer->username, 'lastname' => $social_customer->lastname, 'firstname' => $social_customer->firstname, 'email' => $social_customer->email, 'gender' => $social_customer->id_gender, 'like' => $social_customer->like);
     }
     die(Tools::jsonEncode($return));
 }
 /**
  * @see FrontController::initContent()
  */
 public function initContent()
 {
     Pilipay::log(sprintf("Calling %s with %s", __METHOD__, Tools::jsonEncode(func_get_args())));
     parent::initContent();
     $cart = $this->context->cart;
     if (!$this->module->checkCurrency($cart)) {
         Tools::redirect('index.php?controller=order');
     }
     $this->context->smarty->assign(array('nbProducts' => $cart->nbProducts(), 'cust_currency' => $cart->id_currency, 'currencies' => $this->module->getCurrency((int) $cart->id_currency), 'total' => $cart->getOrderTotal(true, Cart::BOTH), 'this_path' => $this->module->getPathUri(), 'this_path_bw' => $this->module->getPathUri(), 'this_path_ssl' => Tools::getShopDomainSsl(true, true) . __PS_BASE_URI__ . 'modules/' . $this->module->name . '/'));
     $this->setTemplate('payment_execution.tpl');
 }
 public function postProcess()
 {
     $method = Tools::getValue('method');
     $path = Tools::getValue('path');
     $data = Tools::getValue('data');
     $data = Tools::jsonDecode($data);
     if (!$data) {
         $data = array();
     }
     $response = $this->aplazame->callToRest($method, $path, $data);
     die(Tools::jsonEncode($response['payload']));
 }
 private static function setAside($id_product, $reference, $supplier_reference, $id_order, $quantity)
 {
     $message = array('id_product' => $id_product, 'reference' => $reference, 'supplier_reference' => $supplier_reference, 'id_order' => $id_order, "quantity" => $quantity);
     $sqs = new AmazonSQS();
     $sqs->set_region(AmazonSQS::REGION_APAC_SE1);
     $response = $sqs->send_message(STOCK_SYNC_QUEUE, Tools::jsonEncode($message));
     if (!$response->isOK()) {
         self::send_tech_mail('SQS Stock Sync send message', "Failed to send message to the queue. Product Id:{$id_product} , Order Id:{$id_order}, Qty:{$quantity}");
         return false;
     }
     return true;
 }
 public static function jsonEncode($json)
 {
     if (function_exists('json_encode')) {
         return json_encode($json);
     } elseif (method_exists('Tools', 'jsonEncode')) {
         return Tools::jsonEncode($json);
     } else {
         include_once dirname(__FILE__) . '/json.php';
         $pearJson = new Services_JSON();
         return $pearJson->encode($data);
     }
 }
 /**
  * Gets a list of all flash messages from the users cookie by type.
  *
  * @param string $type the type of messages (use class constants).
  * @return array the message array.
  */
 public function getList($type)
 {
     $flash_messages = array();
     $cookie = Context::getContext()->cookie;
     $cookie_data = isset($cookie->nostotagging) ? Tools::jsonDecode($cookie->nostotagging, true) : array();
     if (isset($cookie_data['flash_messages'][$type])) {
         $flash_messages = $cookie_data['flash_messages'][$type];
         unset($cookie_data['flash_messages'][$type]);
         $cookie->nostotagging = Tools::jsonEncode($cookie_data);
     }
     return $flash_messages;
 }
 /**
  * query all pilibaba supported currency
  * 
  * @return array
  */
 public static function register($array)
 {
     $header = array('Content-Type: application/json');
     $ch = curl_init();
     curl_setopt($ch, CURLOPT_URL, self::PILIPAY_AUTOREGISTER_URL);
     curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
     curl_setopt($ch, CURLOPT_POST, 1);
     curl_setopt($ch, CURLOPT_POSTFIELDS, Tools::jsonEncode($array));
     $response = curl_exec($ch);
     curl_close($ch);
     return $response;
 }
 public function initContent()
 {
     parent::initContent();
     $this->context->smarty->assign(array('errors' => $this->errors));
     $action = Tools::getValue('action');
     if (!Tools::isSubmit('myajax')) {
         $this->assign();
     } elseif (!empty($action) && method_exists($this, 'ajaxProcess' . Tools::toCamelCase($action))) {
         $this->{'ajaxProcess' . Tools::toCamelCase($action)}();
     } else {
         die(Tools::jsonEncode(array('error' => 'method doesn\'t exist')));
     }
 }
 public function ajaxProcessUpdatePosition()
 {
     $items = Tools::getValue('item');
     $total = count($items);
     $success = true;
     for ($i = 1; $i <= $total; $i++) {
         $success &= Db::getInstance()->update('themeconfigurator', array('item_order' => $i), '`id_item` = ' . preg_replace('/(item-)([0-9]+)/', '${2}', $items[$i - 1]));
     }
     if (!$success) {
         die(Tools::jsonEncode(array('error' => 'Update Fail')));
     }
     die(Tools::jsonEncode(array('success' => 'Update Success !', 'error' => false)));
 }