I am looking for a way to set the default locale for certain host servers.
Given the servername is server-spain, e.g. I would like to redirect by default to the spanish translation, preferably any page the user lands, besides browser settings. So by default, even the app language/locale is English by default, if accessing through website.es (spanish domain) the user will see spanish as default language.
$this['servername'] = gethostname(); // host name
{% if servername is same as('server-in-spain') %}
// reload with spanish locale
{% endif %}
Anybody found themselves in this situation? Anybody solved it?
Thanks!
You can add this code to your layout's code section and it should do the job.
use RainLab\Translate\Classes\Translator;
public function onStart() {
$translator = Translator::instance();
$currentLocale = $translator->getLocale();
$newLocale = 'es';
$translatedRedirect = false;
$servername = gethostname(); // <- YOUR FUNCTION TO FIND HOST
// MAKE SURE IF YOU DO NOT HAVE GIVEN LOCAE IN Backend
// THNE IT WILL REDIRECT TO DEFAULT SET LOCALE
if($servername === 'server-in-spain') {
$newLocale = 'es';
}
if($servername === 'server-in-germany') {
$newLocale = 'de';
}
// we do not want to redirect if user have already perfect locale
if($currentLocale !== $newLocale) {
$translatedRedirect = true;
}
if($translatedRedirect) {
$translator->setLocale($newLocale);
$currentUrl = $this->currentPageUrl();
$parts = parse_url($currentUrl);
$path = array_get($parts, 'path');
$pageUrl = http_build_url($parts, [
'path' => '/' . $translator->getPathInLocale($path, $newLocale)
]);
return Redirect::to($pageUrl);
}
}
It should do the job
if any doubt please comment
With Hardik's answer I could solve it.
The only issues I encountered with this solution were :
I wasnt able to select a different locale in a given domain. That is example.es , correctly displaying /es locale but unable to switch locales (as it was forced by the code)
I solved it with a first time cookie:
function onStart() {
//Set the cookie for firt time visit
$first_visit = !isset( $_COOKIE["fist_locale"] );
// Set the cookie so that the message doesn't show again
setcookie( "first_locale", 1, strtotime( '+1 week' ) );
if( $first_visit ){ // if user first time
$translator = Translator::instance();
$currentLocale = $translator->getLocale();
$newLocale = 'en';
$translatedRedirect = false;
$servername = gethostname(); // <- YOUR FUNCTION TO FIND HOST
// MAKE SURE IF YOU DO NOT HAVE GIVEN LOCAE IN Backend
// THNE IT WILL REDIRECT TO DEFAULT SET LOCALE
if($servername === 'example.es') {
$newLocale = 'es';
}
if($servername === 'example.de') {
$newLocale = 'de';
}
// we do not want to redirect if user have already perfect locale
if($currentLocale !== $newLocale) {
$translatedRedirect = true;
}
if($translatedRedirect) {
$translator->setLocale($newLocale);
$currentUrl = $this->currentPageUrl();
$parts = parse_url($currentUrl);
$path = array_get($parts, 'path');
$pageUrl = http_build_url($parts, [
'path' => '/' . $translator->getPathInLocale($path, $newLocale)
]);
return Redirect::to($pageUrl);
}
}//end of first time
}
The locale forced by the domain name function adds /(locale) after the domain as in example.de/de
Related
I wrote this code as a Cloudflare Service Worker which is meant to precisely emulate their native function for "Bypass cache on cookie". Specifically, if someone has a Wordpress cookie - it would bypass cache, otherwise it does not.
It does not seem to function at all - in that despite having a cookie and being logged in (confirmed via Chrome developer tools) - I still get a Cloudflare cache HIT on this example domain - Tallyfy. Anything wrong with it? Help appreciated!
// A Service Worker which skips cache if the request contains a cookie.
addEventListener('fetch', event => {
let request = event.request;
var flag=false;
if(request.headers.cookie) {
var pairs = request.headers.cookie.split(";");
var patt = new RegExp("wp-.*|wordpress.*|comment_.*|woocommerce_.*")
for(var i=0;i<pairs.length;i++){
if(patt.test(pairs[i])){
flag = true;
break;
}
}
}
if (request.headers.has('Cookie') && flag) {
// Cookie present. Add Cache-Control: no-cache.
let newHeaders = new Headers(request.headers)
newHeaders.set('Cache-Control', 'no-cache')
event.respondWith(fetch(request, {headers: newHeaders}))
}
// Use default behavior.
return
})
try this and let me know
addEventListener('fetch', event => {
let request = event.request
var flag = false;
if (request.headers.has('Cookie')) {
var cookie = request.headers.get('Cookie');
pairs = cookie.split(";");
var patt = new RegExp("wordpress_logged_in.*|wp_woocommerce_session.*");
for(var i=0;i<pairs.length;i++){
if(patt.test(pairs[i])){
flag = true;
break;
}
}
console.log(flag);
if (request.headers.has('Cookie') && flag) {
let newHeaders = new Headers(request.headers)
newHeaders.set('Cache-Control', 'no-cache')
newHeaders.set('Pragma', 'no-cache')
event.respondWith(fetch(request, {headers: newHeaders}))
}
// Use default behavior.
return;
}
})
I figured if the devtool can list all created IndexedDB, then there should be an API to retrieve them...?
Dose anyone know how I get get a list of names with the help of a firefox SDK?
I did dig into the code and looked at the source. unfortunately there wasn't any convenient API that would pull out all the databases from one host.
The way they did it was to lurk around in the user profiles folder and look at all folder and files for .sqlite and make a sql query (multiple times in case there is an ongoing transaction) to each .sqlite and ask for the database name
it came down this peace of code
// striped down version of: https://dxr.mozilla.org/mozilla-central/source/devtools/server/actors/storage.js
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
const {async} = require("resource://gre/modules/devtools/async-utils");
const { setTimeout } = require("sdk/timers");
const promise = require("sdk/core/promise");
// A RegExp for characters that cannot appear in a file/directory name. This is
// used to sanitize the host name for indexed db to lookup whether the file is
// present in <profileDir>/storage/default/ location
const illegalFileNameCharacters = [
"[",
// Control characters \001 to \036
"\\x00-\\x24",
// Special characters
"/:*?\\\"<>|\\\\",
"]"
].join("");
const ILLEGAL_CHAR_REGEX = new RegExp(illegalFileNameCharacters, "g");
var OS = require("resource://gre/modules/osfile.jsm").OS;
var Sqlite = require("resource://gre/modules/Sqlite.jsm");
/**
* An async method equivalent to setTimeout but using Promises
*
* #param {number} time
* The wait time in milliseconds.
*/
function sleep(time) {
let deferred = promise.defer();
setTimeout(() => {
deferred.resolve(null);
}, time);
return deferred.promise;
}
var indexedDBHelpers = {
/**
* Fetches all the databases and their metadata for the given `host`.
*/
getDBNamesForHost: async(function*(host) {
let sanitizedHost = indexedDBHelpers.getSanitizedHost(host);
let directory = OS.Path.join(OS.Constants.Path.profileDir, "storage",
"default", sanitizedHost, "idb");
let exists = yield OS.File.exists(directory);
if (!exists && host.startsWith("about:")) {
// try for moz-safe-about directory
sanitizedHost = indexedDBHelpers.getSanitizedHost("moz-safe-" + host);
directory = OS.Path.join(OS.Constants.Path.profileDir, "storage",
"permanent", sanitizedHost, "idb");
exists = yield OS.File.exists(directory);
}
if (!exists) {
return [];
}
let names = [];
let dirIterator = new OS.File.DirectoryIterator(directory);
try {
yield dirIterator.forEach(file => {
// Skip directories.
if (file.isDir) {
return null;
}
// Skip any non-sqlite files.
if (!file.name.endsWith(".sqlite")) {
return null;
}
return indexedDBHelpers.getNameFromDatabaseFile(file.path).then(name => {
if (name) {
names.push(name);
}
return null;
});
});
} finally {
dirIterator.close();
}
return names;
}),
/**
* Removes any illegal characters from the host name to make it a valid file
* name.
*/
getSanitizedHost: function(host) {
return host.replace(ILLEGAL_CHAR_REGEX, "+");
},
/**
* Retrieves the proper indexed db database name from the provided .sqlite
* file location.
*/
getNameFromDatabaseFile: async(function*(path) {
let connection = null;
let retryCount = 0;
// Content pages might be having an open transaction for the same indexed db
// which this sqlite file belongs to. In that case, sqlite.openConnection
// will throw. Thus we retey for some time to see if lock is removed.
while (!connection && retryCount++ < 25) {
try {
connection = yield Sqlite.openConnection({ path: path });
} catch (ex) {
// Continuously retrying is overkill. Waiting for 100ms before next try
yield sleep(100);
}
}
if (!connection) {
return null;
}
let rows = yield connection.execute("SELECT name FROM database");
if (rows.length != 1) {
return null;
}
let name = rows[0].getResultByName("name");
yield connection.close();
return name;
})
};
module.exports = indexedDBHelpers.getDBNamesForHost;
If anyone want to use this then here is how you would use it
var getDBNamesForHost = require("./getDBNamesForHost");
getDBNamesForHost("http://example.com").then(names => {
console.log(names);
});
Think it would be cool if someone were to build a addon that adds indexedDB.mozGetDatabaseNames to work the same way as indexedDB.webkitGetDatabaseNames. I'm not doing that... will leave it up to you if you want. would be a grate dev tool to have ;)
I have a plugin which I have to support both on Chrome and Firefox browsers. The plugin does cross script loading.
In Chrome, by adding the content security policy in my manifest.json file, I could get away with it. How can I do it Firefox extension?
I couldn't find a simple solution for my problem and upon looking up some firefox plugin extensions i had to come up with my own solution as below. The below solution was tested on FF 24.0 but should work on other versions as well.
Cc["#mozilla.org/observer-service;1"].getService(Ci.nsIObserverService)
.addObserver(_httpExamineCallback, "http-on-examine-response", false);
function _httpExamineCallback(aSubject, aTopic, aData) {
var httpChannel = aSubject.QueryInterface(Ci.nsIHttpChannel);
if (httpChannel.responseStatus !== 200) {
return;
}
var cspRules;
var mycsp;
// thre is no clean way to check the presence of csp header. an exception
// will be thrown if it is not there.
// https://developer.mozilla.org/en-US/docs/XPCOM_Interface_Reference/nsIHttpChannel
try {
cspRules = httpChannel.getResponseHeader("Content-Security-Policy");
mycsp = _getCspAppendingMyHostDirective(cspRules);
httpChannel.setResponseHeader('Content-Security-Policy', mycsp, false);
} catch (e) {
try {
// Fallback mechanism support
cspRules = httpChannel.getResponseHeader("X-Content-Security-Policy");
mycsp = _getCspAppendingMyHostDirective(cspRules);
httpChannel.setResponseHeader('X-Content-Security-Policy', mycsp, false);
} catch (e) {
// no csp headers defined
return;
}
}
};
/**
* #var cspRules : content security policy
* For my requirement i have to append rule just to 'script-src' directive. But you can
* modify this function to your need.
*
*/
function _getCspAppendingMyHostDirective(cspRules) {
var rules = cspRules.split(';'),
scriptSrcDefined = false,
defaultSrcIndex = -1;
for (var ii = 0; ii < rules.length; ii++) {
if ( rules[ii].toLowerCase().indexOf('script-src') != -1 ) {
rules[ii] = rules[ii] + ' <My CSP Rule gets appended here>';
scriptSrcDefined = true;
}
if (rules[ii].toLowerCase().indexOf('default-src') != -1) {
defaultSrcIndex = ii;
}
}
// few publishers will put every thing in the default (default-src) directive,
// without defining script-src. We need to modify those as well.
if ((!scriptSrcDefined) && (defaultSrcIndex != -1)) {
rules[defaultSrcIndex] = rules[defaultSrcIndex] + ' <My CSP rule gets appended here>';
}
return rules.join(';');
};
There are plans in the future to add content policy natively in the SDK (bug 852297), but there is a 3rd party module that should get you close to where you want to be: policy.js
I m very much new to the jQuery and AJAX technology. I am trying to create a form which will insert the values in the database without refresh the page. Most of the code are working as expected. But among there are two case which is not working as expected.
I am fetching values through checkbox. When I select only one checkbox it works but when I select multiple checkbox, the value stored in the database as Array.
I want to display a message once the form data submitted succesfully but its not working.
Please find the below respective code for the same.
Jquery:
$('#add').click(function(){
var domain_type = $('#domain').val();
var domain_zone = $('#domain_zone').val();
var client_name = $('#client_name').val();
//var language[] = "";
var lang = new Array();
if(language==1){
//alert("You select one language");
valid = true;
lang = "English";
}else{
//alert("You select multiple language");
var i =0;
$.each($('input[name=lang]:checked'), function(){
lang.push($(this).val());
});
var count = lang.length;
if(count ==1){
alert("You need to select two languages");
var valid = false;
}else if(count>2){
alert("You can select only two languages");
var valid = false;
}else{
valid = true;
}
}
var formMsge = $('#formStatus');
$('#formStatus').html('<img src="./img/loader.gif"> Please wait while adding the data in database.');
$.ajax({
type: "POST",
url: "./test/test.php",
data: {domain_type:domain_type, domain_zone:domain_zone, client_name:client_name, 'lang[]':lang},
success:function(conf){
$('#formStatus').ajaxComplete(
function(event,request){
if(conf=="OK"){
$('#formSuccess').show();
$('#addClient').hide();
}else{
$('#formError').show();
$('#forError').text("Please try again");
}
}
);
}
});
return false;
});
test.php:
include('../../classes/access_user/all.class.inc.php');
echo $workstream->addClient()
;
php class file:
public function addClient(){
$domain_type = isset($_POST['domain_type'])?$_POST['domain_type']:'';
$domain_zone = isset($_POST['domain_zone'])?$_POST['domain_zone']:'';
$client_name = isset($_POST['client_name'])?$_POST['client_name']:'';
$lang = isset($_POST['lang'])?$_POST['lang']:'';
$add_by = 'Robindra Singha';
$add_on = date("Y-m-d");
if(isset($domain_type) || isset($domain_zone) || isset($client_name) || isset($lang)){
$sql = "INSERT INTO client_list (domain_type_id, client_name, domain_zone, language, add_on, add_by, last_update_on, last_update_by) VALUES('$domain_type','$client_name','$domain_zone','$lang','$add_on','$add_by','$add_on','$add_by')";
$res = mysql_query($sql) or die(mysql_error());
if(mysql_inserted_id() != 0){
$msg = "OK";
}else{
$msg = "System face an issue while adding client details!";
}
}else{
$msg = "System face an issue while adding client details, please try again!";
}
return $msg;
}
In above code, my issue is checkbox value are not able to pass when I select the multiple checkbox, second I am not able to display any text once the form is successfully submit. Except this two issues, my code able to insert the information successfully. I would be glad if any one guide me in completing the work properly. Thank you in advance for your kind support.
Note: I am not able to add the HTML file as i paste here, it display as normal text. please suggest.
Before all, sorry for my poor english.
Good night/day/afternoon (depending of your location)
Sorry if I ask something that could be searched here, and I searched, even found it, but maybe I di not understand.
I need to check authentication in my controllers, so, I implement a master controller and extend all my real controllers to it. In my master controller I check authentication and do it well, but when I try to redirect an unauthenticated user it crashes!
Searching in web, I realized that "init, preDispatch, etc" methods even don't exist more, just the "construct" method, so I try in it, but in construct there is not an event manager, so I stop here...
This is my code:
public function __construct(){
$r = new SimpleRouteStack();
$r->addRoute('logoff', Literal::factory(array(
'route'=>'/suporte/logoff',
'defaults' => array(
'action' => 'logoff',
'controller' => 'Suporte\Controller\Index',
)
)
)
);
$e = new MvcEvent();
$e->setRouter($r);
$this->setEvent($e);
$this->getEvent()->setResponse(new Response());
$this->getEventManager()->attach('*',array($this,'mvcPreDispatch'),100);
public function mvcPreDispatch(){
$uri = explode('/',substr($_SERVER['REQUEST_URI'],1));
$uri[2] = !isset($uri[2]) ? "index" : $uri[2];
$auth = new AuthenticationService();
$identity = $auth->getStorage()->read();
$acl = $identity[2];
if (!$auth->hasIdentity()){
$this->redirect()->toRoute('suporte/logoff');
}elseif ( !$acl->hasResource($uri[0].'/'.$uri[1])
||
!$acl->isAllowed($identity[1],
$uri[0].'/'.$uri[1],
$uri[2]
)
)
$this->redirect()->toRoute('logoff');
else{
/* $this->layout()->id = $identity[0]->getId();
$this->layout()->nome = $identity[0]->getNome();
$this->layout()->cargo = $identity[0]->getCargo(); */
echo "permitido";
//$this->layout()->recursos = $this->acl->getResources();
}
}
is your Suporte\Controller\logoff also extending the masterclass. If yes then it will lead to an infinite loop indexController>masterController(!loggedin)>logoutController>masterController(!loggedin)>logoutController>..
How I used to say "IT is witchcraft"!!!
When I wake up today, turn on my computer, test the controller and BAZINGA!!! is running ok...
Why? I don't dare to question...
my code is that:
abstract class PadraoControllerSuporte extends AbstractActionController{
public function setEventManager(EventManagerInterface $events){
parent::setEventManager($events);
$controller = $this;
$events->attach('dispatch', function ($e) use ($controller) {
if (is_callable(array($controller, 'verificaAuth'))){
call_user_func(array($controller, 'verificaAuth'));
}
}, 100);
}
public function verificaAuth(){
$uri = explode('/',substr($_SERVER['REQUEST_URI'],1));
$uri[2] = !isset($uri[2]) ? "index" : $uri[2];
$auth = new AuthenticationService();
$identity = $auth->getStorage()->read();
$acl = $identity[2];
if (!$auth->hasIdentity())
$this->redirect()->toRoute('suporte/logoff');
elseif ( !$acl->hasResource($uri[0].'/'.$uri[1]) !$acl->isAllowed( $identity[1],
$uri[0].'/'.$uri[1],
$uri[2]
)
)
$this->redirect()->toRoute('logoff');
else{
/* $this->layout()->id = $identity[0]->getId();
$this->layout()->nome = $identity[0]->getNome();
$this->layout()->cargo = $identity[0]->getCargo(); */
echo "permitido";
//$this->layout()->recursos = $this->acl->getResources();
}
}
What I understood:
I think that "setEventManager" was superimposed, so it sets to listen the "dispatch" event and call my verificaAuth function what redirects (if not authenticated) to logoff or allow it is authenticated.
Hope this is usefull...
Thanks for all!!!