Is there any php code to change store? So for example if php detects the language is Spanish I would like it to change the whole store to other store.
So it can be used for example anytime when language is changed - then the store is changed also.
So for example if anyone is viewing the store1 in English and change language to Spanish then automatically the store1 is also changed to store2 toghether with the language. Any idea?
If you open file: index.php or startup.php (based on the OpenCart version you use) you will see that there is a code that checks the url of which the user has visited and then searches the database to see if it's default store (store_id = 0) or other store. If it's the default store, then nothing changes. If it's not though, then session variable (store_id) is changed to the specified store_id and the whole opencart will operate based on this store_id.
OpenCart 1.5.x index.php
// Store
if (isset($_SERVER['HTTPS']) && (($_SERVER['HTTPS'] == 'on') || ($_SERVER['HTTPS'] == '1'))) {
$store_query = $db->query("SELECT * FROM " . DB_PREFIX . "store WHERE REPLACE(`ssl`, 'www.', '') = '" . $db->escape('https://' . str_replace('www.', '', $_SERVER['HTTP_HOST']) . rtrim(dirname($_SERVER['PHP_SELF']), '/.\\') . '/') . "'");
} else {
$store_query = $db->query("SELECT * FROM " . DB_PREFIX . "store WHERE REPLACE(`url`, 'www.', '') = '" . $db->escape('http://' . str_replace('www.', '', $_SERVER['HTTP_HOST']) . rtrim(dirname($_SERVER['PHP_SELF']), '/.\\') . '/') . "'");
}
if ($store_query->num_rows) {
$config->set('config_store_id', $store_query->row['store_id']);
} else {
$config->set('config_store_id', 0);
}
OpenCart 2.x / 3.x - catalog/controller/startup/startup.php
// Store
if ($this->request->server['HTTPS']) {
$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "store WHERE REPLACE(`ssl`, 'www.', '') = '" . $this->db->escape('https://' . str_replace('www.', '', $_SERVER['HTTP_HOST']) . rtrim(dirname($_SERVER['PHP_SELF']), '/.\\') . '/') . "'");
} else {
$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "store WHERE REPLACE(`url`, 'www.', '') = '" . $this->db->escape('http://' . str_replace('www.', '', $_SERVER['HTTP_HOST']) . rtrim(dirname($_SERVER['PHP_SELF']), '/.\\') . '/') . "'");
}
if (isset($this->request->get['store_id'])) {
$this->config->set('config_store_id', (int)$this->request->get['store_id']);
} else if ($query->num_rows) {
$this->config->set('config_store_id', $query->row['store_id']);
} else {
$this->config->set('config_store_id', 0);
}
So, you can extend this code and you will check the browser's language and based on every language you will change the store_id to the one you need.
A sample code is the following, it's not the ideal, but it will give you the idea on how to implement it by yourself.
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
switch ($lang){
case "fr":
$this->config->set('config_store_id', 1);
break;
case "it":
$this->config->set('config_store_id', 2);
break;
case "en":
$this->config->set('config_store_id', 3);
break;
case "el":
$this->config->set('config_store_id', 4);
break;
default:
//else default store
$this->config->set('config_store_id', 0);
break;
}
Hope the above answer will help you. It's easy, but you need to understand how OpenCart works. Also, just my advice..."Don't wait for ready-made extensions, try to make yours." ;)
Cheers!
Related
I'm trying to prepare a module.
I need the module_id value.
I will draw data with the module_id value.
How do I get module_id in the controller on the front side.
you should create model file with some name mymodule.php where you should place something like this:
public function getModules() {
$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "module` ORDER BY `code`");
return $query->rows;
}
you will get all modules data.
or can get just only one by module code:
public function getModulesByCode($code) {
$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "module` WHERE `code` = '" . $this->db->escape($code) . "' ORDER BY `name`");
return $query->rows;
}
Then in your controller with corresponding name mymodule.php file you can call it:
$modules = $this->model_extension_module->getModulesByCode($code);
or
$modules = $this->model_extension_module->getModules();
Your suggestion may apply to single module.
My module has sub-modules.
But I found the solution.
Design layout have solved the work with files.
catalog / controller / common / common_left.php
catalog / controller / common / common_right.php
catalog / controller / common / head_top.php
catalog / controller / common / head_bottom.php
etc.
I added a starred code.
if (isset($part[1])) {
$setting_info = $this->model_setting_module->getModule($part[1]);
if ($setting_info && $setting_info['status']) {
***** $setting_info["module_id"] = $part[1]; *****
$output = $this->load->controller('extension/module/' . $part[0], $setting_info);
if ($output) {
$data['modules'][] = $output;
}
}
}
I need to create a system that will be able to output a template (a zip with an index.html with all js, css, img etc files as required) based on a set of options (include menu 1, use small footer etc).
So I can put code blocks in so it would not be hard to actually output to the browser the required look, but what if I want to save the rendered html (and this means we would need to change the locations of files like js etc) to a zip instead?
Any ideas? At the moment I'm thinking it would all need to be processed in PHP anyhow (the controller) and TWIG may not be too helpful, but that would make it more complicated.
So I worked this one out, here is the controller to output the required twig zipped:
<?php
namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class DefaultController extends Controller
{
/**
* #Route("/{variableName}", name="homepage"})
*/
public function indexAction($variableName = "Default")
{
//do whatever you need to get the template correct
//send rendered TWIG to a variable
$renderedhtml = $this->render('default/index.html.twig', [
'variableName' => $variableName
])->getContent();
$zipName = "template.zip";
$main = $this->get('kernel')->getRootDir() . '/../web/workingdir/';
$vername = time(); //we use the exact time to get a unique dir name
//remove any projects older than a few minutes (5 in this case)
$dirHandle = opendir($main);
while($item = readdir($dirHandle)){
if(is_dir($main . $item) && $item != '.' && $item != '..') {
if ( ( ( $item + ( 60 * 5 ) ) < $vername ) ) {
system('/bin/rm -rf ' . escapeshellarg($main . $item));
}
}
}
//make the project dir and populate it with files (in this case just the template as index.html, you would want to copy all other files here though)
mkdir($main.$vername);
file_put_contents($main.$vername."/index.html", $renderedhtml);
//create the zip
$zip = new \ZipArchive();
$zip->open($zipName, \ZipArchive::CREATE);
$zip = $this->createZip($zip, $main.$vername);
$zip->close();
//get the zip ready to return
header('Content-Type', 'application/zip');
header('Content-disposition: attachment; filename="' . $zipName . '"');
header('Content-Length: ' . filesize($zipName));
readfile($zipName);
}
// Create a zip with zip object and root dir params (find and include sub-dirs with content)
private function createZip($zip, $source) {
$source = str_replace('\\', '/', realpath($source));
if (is_dir($source) === true) {
$files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($source), \RecursiveIteratorIterator::SELF_FIRST);
foreach ($files as $file) {
$file = str_replace('\\', '/', $file);
if( in_array(substr($file, strrpos($file, '/')+1), array('.', '..')) )
continue;
$file = realpath($file);
if (is_dir($file) === true)
{
$zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
}
else if (is_file($file) === true)
{
$zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
}
}
}
return $zip;
}
}
Once you get it to this stage, you will just have to add any other required files into the working dir, but I think that could be done under a different issue, this one is about getting the website into a html in a zip.
Hope this helps someone.
Hi here is my code please check it and let me know what im missing.
im using amazon orders API for this.
<?php
require_once('.config.inc.php');
//$serviceUrl = "https://mws.amazonservices.com/Orders/2013-09-01";
// Europe
$serviceUrl = "https://mws-eu.amazonservices.com/Orders/2013-09-01";
// Japan
//$serviceUrl = "https://mws.amazonservices.jp/Orders/2013-09-01";
// China
//$serviceUrl = "https://mws.amazonservices.com.cn/Orders/2013-09-01";
$config = array (
'ServiceURL' => $serviceUrl,
'ProxyHost' => null,
'ProxyPort' => -1,
'ProxyUsername' => null,
'ProxyPassword' => null,
'MaxErrorRetry' => 3,
);
$service = new MarketplaceWebServiceOrders_Client(
AWS_ACCESS_KEY_ID,
AWS_SECRET_ACCESS_KEY,
APPLICATION_NAME,
APPLICATION_VERSION,
$config);
$request = new MarketplaceWebServiceOrders_Model_ListOrdersRequest();
$request->setSellerId(MERCHANT_ID);
// object or array of parameters
echo"<pre>";
print_r($service);
invokeListOrders($service, $request);
function invokeListOrders(MarketplaceWebServiceOrders_Interface $service, $request)
{
try {
$response = $service->ListOrders($request);
echo ("Service Response\n");
echo ("=============================================================================\n");
$dom = new DOMDocument();
$dom->loadXML($response->toXML());
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
echo $dom->saveXML();
echo("ResponseHeaderMetadata: " . $response->getResponseHeaderMetadata() . "\n");
} catch (MarketplaceWebServiceOrders_Exception $ex) {
echo("Caught Exception: " . $ex->getMessage() . "\n");
echo("Response Status Code: " . $ex->getStatusCode() . "\n");
echo("Error Code: " . $ex->getErrorCode() . "\n");
echo("Error Type: " . $ex->getErrorType() . "\n");
echo("Request ID: " . $ex->getRequestId() . "\n");
echo("XML: " . $ex->getXML() . "\n");
echo("ResponseHeaderMetadata: " . $ex->getResponseHeaderMetadata() . "\n");
}
}
This is the XMl im using for getting the details i request somebody to reply me as soon as possible.
Just add these two lines after the
$request->setSellerId(MERCHANT_ID);
after this line add these two lines.
$request->setMarketplaceId(MARKETPLACE_ID);
$request->setCreatedAfter('2016-04-01');
Hope this helps..
My Select function of my QueryManager:
/**
* Führt eine SELECT - Query durch
*
* #param $select = array( array(column, [...]), table, shortcut )
* $orderby = array(column, sorting-type)
* $where = array( array( column, value, type[or, and] ), [...] )
* $innerjoin = array( table, shortcut, condition )
* $pagination = array( page, limit )
*
* #return array $data
*/
public function select($select,$orderby, $where, $innerjoin, $pagination)
{
$qb = $this->conn->createQueryBuilder()
->select($select[0])
->from($select[1], $select[2])
;
if ($orderby) {
$qb->orderBy($orderby);
}
if ($where) {
foreach($where as $cond) {
$x = 0;
if ( key($cond) == 0 ) {
$qb
->where($cond[0] . ' = ?')
->setParameter($x,$cond[1]);
}
elseif ( $cond[2] == 'and' ) {
$qb
->andWhere($cond[0] . ' = ?')
->setParameter($x,$cond[1]);
}
elseif ( $cond[2] == 'and' ) {
$qb
->orWhere($cond[0] . ' = :' . $x)
->setParameter($x,$cond[1]);
}
$x++;
}
}
if ($innerjoin) {
$qb->join($select[2],$innerjoin);
}
$this->sql = $qb->getSQL();
$this->totalRowCount = count( $qb->execute() ) ;
if ($pagination) {
$max = $pagination[0] * $pagination[1];
$first = $max - $limit;
$qb
->setFirstResult($first)
->setMaxResults($max)
;
}
$stmt = $qb->execute();
return $stmt->fetchAll();
}
I don't know why, but in action, this function produces a select query without inserted values for the parameters:
/**
* Lädt einen User nach dessen Username
*
* #param $username
* #return User $user | null
*/
public function getUser($username)
{
if($data = $this->select(array('*','users','u'), null, array( array('username',$username) ), null,null)) {
return $user = $this->hydrate($data);
}
return null;
}
I didn't get a result, and the query is not setup correctly:
array(0) { }
SELECT * FROM users u WHERE username = ?
In my opinion the Builder doesn't supstitute my parameters with the provided values ...
I got the latest version of Doctrine DBAL (2.4) and this version should support this features!
Thanks for Help and Suggestions :)
I also had this Problem. I have readed here doctrine 2 querybuilder with set parameters not working that:
You cant bind parameters to QueryBuilder, only to Query
But im creating SQL conditions as collected AND & OR experssions in deep nested objects, and the toppest object creates the query object. So i cant create the query object before, i always return expression objects.
So i solved the problem with direct including the variable into the prepared variable's position.
$qb->where($cond[0] . '=' . $cond[1]);
And because i expect strings there i added hard coded quotes. This is not the desired way, but at the moment i dont know how to solve that in an other way with binding parameters to the QueryBuilder object.
$expr = $d_qb->expr()->between($t_c, "'" . $date_from . "'", "'" . $date_from . "'");
Other suggestions?
Following codes results:
$expr = $d_qb->expr()->between($t_c, ':from', ':to');
$d_qb->setParameter('from', 1);
$d_qb->setParameter('to', 1);
or
$expr = $d_qb->expr()->between($t_c, ':from', ':to');
$d_qb->setParameter(':from', 1);
$d_qb->setParameter(':to', 1);
Results:
e0_.created BETWEEN ? AND ?
does anybody know how I can achieve the following:
I have a custom post type called 'projects' I have 5 different page
layouts (each with a different number of images at different sizes
that are arranged differently). I think that if I can ID the images I
can position them using CSS. If each layout has it's own template page
with containers for the required images and each also has CSS to
position the images.
I am wondering if it's possible to add a
template select on right hand side of post editor view, like you have
available for pages this way it's possible to assign a template (from
1-5) for each post.
I am adding custom meta boxes for the image upload fields
and the other data in the main post editor, but ideally this should
change for the other pages to only display the required upload
fields.
Any ideas anybody? I did consider setting up a custom post type for each layout (the 5 templates) allowing you to post a new project under the layout type you require, then on the page query the loop with all 5 custom-post-types (layouts). I worry this might be messy though, because to find projects to edit later you will need to know which template page (custom-post-type) they belong to but more importantly the url to projects wouldn't be www.sitename.co.uk/projects but instead be www.sitename.co.uk/custom-post-type1, www.sitename.co.uk/custom-post-type2 ??? Wouldn't it?
Any help really appreciated as always. Thanks
here is code I have identified so far, any ideas how to customise?
Should this go in functions.php?
// Check if the post has a special template
$template = get_post_meta($post->ID, '_wp_mf_page_template', true);
if (!$template || $template == 'default') {
return;
}
$template = TEMPLATEPATH.'/'.$template;
if ( $template = apply_filters( 'template_include', $template ) ) {
include($template);
die();
}
return;
Second code:
// Check if the post_type has page attributes
// if is the case is necessary need save the page_template
if ($_POST['post_type'] != 'page' && isset($_POST['page_template'])) {
add_post_meta($post_id, '_wp_mf_page_template', $_POST['page_template'], true) or update_post_meta($post_id, '_wp_mf_page_template', $_POST['page_template']);
}
Third code:
//MF Meta box for select template
function mf_metabox_template () {
global $post;
if ( 0 != count( get_page_templates() ) ) {
$template = get_post_meta($post->ID, '_wp_mf_page_template', TRUE);
$template = ($template != '') ? $template : false;
?>
<label class="screen-reader-text" for="page_template"><?php _e('Page Template') ?></label><select name="page_template" id="page_template">
<option value='default'><?php _e('Default Template'); ?></option>
<?php page_template_dropdown($template); ?>
</select>
<?php
}
}
You can create meta box using this code. Please paste this code in your function.php.
/*********************custom meta box********************************/
add_action( 'add_meta_boxes', 'add_events_metaboxes' );
function add_events_metaboxes() {
add_meta_box('wpt_school_location', 'Business Listing Data:','wpt_school_location', 'businesses', 'side', 'default');
}
//add_meta_box( $id, $title, $callback, $page, $context, $priority, $callback_args );
// Add the Events Meta Boxes
// The Event Location Metabox
function wpt_school_location() {
global $post;
// Noncename needed to verify where the data originated
echo '<input type="hidden" name="eventmeta_noncename" id="eventmeta_noncename" value="' .
wp_create_nonce( plugin_basename(__FILE__) ) . '" />';
// Get the location data if its already been entered
$email = get_post_meta($post->ID, '_location', true);
$tel = get_post_meta($post->ID, '_location1', true);
$web = get_post_meta($post->ID, '_location2', true);
$city = get_post_meta($post->ID, '_location3', true);
// Echo out the field
echo '<div class="heading">Address</div>';
echo '<input type="text" name="_location" value="' . $email . '" class="widefat" />';
echo '<div class="heading">Telephone</div>';
echo '<input type="text" name="_location1" value="' . $tel . '" class="widefat" />';
echo '<div class="heading">E-mail</div>';
echo '<input type="text" name="_location2" value="' . $web . '" class="widefat" />';
echo '<div class="heading">Web</div>';
echo '<input type="text" name="_location3" value="' . $city . '" class="widefat" />';
}
// Save the Metabox Data
function wpt_save_events_meta($post_id, $post) {
// verify this came from the our screen and with proper authorization,
// because save_post can be triggered at other times
if ( !wp_verify_nonce( $_POST['eventmeta_noncename'], plugin_basename(__FILE__) )) {
return $post->ID;
}
// Is the user allowed to edit the post or page?
if ( !current_user_can( 'edit_post', $post->ID ))
return $post->ID;
// OK, we're authenticated: we need to find and save the data
// We'll put it into an array to make it easier to loop though.
$events_meta['_location'] = $_POST['_location'];
$events_meta['_location1'] = $_POST['_location1'];
$events_meta['_location2'] = $_POST['_location2'];
$events_meta['_location3'] = $_POST['_location3'];
// Add values of $events_meta as custom fields
foreach ($events_meta as $key => $value) { // Cycle through the $events_meta array!
if( $post->post_type == 'revision' ) return; // Don't store custom data twice
$value = implode(',', (array)$value); // If $value is an array, make it a CSV (unlikely)
if(get_post_meta($post->ID, $key, FALSE)) { // If the custom field already has a value
update_post_meta($post->ID, $key, $value);
} else { // If the custom field doesn't have a value
add_post_meta($post->ID, $key, $value);
}
if(!$value) delete_post_meta($post->ID, $key); // Delete if blank
}
}
add_action('save_post', 'wpt_save_events_meta', 1, 2); // save the custom fields
// Add the Events Meta Boxes