How to retrieve $config['myConfig_array'] in Code Igniter - codeigniter

I've followed Codeigniter language and all seems to be setup as a hook.
function pick_language() {
require_once(APPPATH.'/config/language.php');
session_start();
// Lang set in URL via ?lang=something
if(!empty($_GET['lang']))
{
// Turn en-gb into en
$lang = substr($_GET['lang'], 0, 2);
$_SESSION['lang_code'] = $lang;
}
// Lang has already been set and is stored in a session
elseif( !empty($_SESSION['lang_code']) )
{
$lang = $_SESSION['lang_code'];
}
// Lang has is picked by a user.
// Set it to a session variable so we are only checking one place most of the time
elseif( !empty($_COOKIE['lang_code']) )
{
$lang = $_SESSION['lang_code'] = $_COOKIE['lang_code'];
}
// Still no Lang. Lets try some browser detection then
else if (!empty( $_SERVER['HTTP_ACCEPT_LANGUAGE'] ))
{
// explode languages into array
$accept_langs = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
log_message('debug', 'Checking browser languages: '.implode(', ', $accept_langs));
// Check them all, until we find a match
foreach ($accept_langs as $lang)
{
// Turn en-gb into en
$lang = substr($lang, 0, 2);
// Check its in the array. If so, break the loop, we have one!
if(in_array($lang, array_keys($config['supported_languages'])))
{
break;
}
}
}
// If no language has been worked out - or it is not supported - use the default
if(empty($lang) or !in_array($lang, array_keys($config['supported_languages'])))
{
$lang = $config['default_language'];
}
// Whatever we decided the lang was, save it for next time to avoid working it out again
$_SESSION['lang_code'] = $lang;
// Load CI config class
$CI_config =& load_class('Config');
// Set the language config. Selects the folder name from its key of 'en'
$CI_config->set_item('language', $config['supported_languages'][$lang]['folder']);
// Sets a constant to use throughout ALL of CI.
define('CURRENT_LANGUAGE', $lang);
}
Now when I try to access $config['supported_languages'] it returns null or errors. Why?

Related

laravel multi-language switch and change locale on load

I've implemented the language switch functionality following this post and it works perfectly but just when you click on the language switch, though I would like to change the locale and store it in the App when the page is loaded.
My function it's a bit different from the one in the post, I've added an else if just to make sure that the locale it's in the accepted languages
App/Middleware/Localization.php
public function handle($request, Closure $next)
{
$availableLangs = array('en', 'hu', 'pt', 'ro', 'sv');
$userLangs = substr($request->server('HTTP_ACCEPT_LANGUAGE'), 0, 2);
if (\Session::has('locale'))
{
\App::setlocale(\Session::get('locale'));
}
else if (in_array($userLangs, $availableLangs))
{
\App::setLocale($userLangs);
// Session::push('locale', $userLangs);
}
return $next($request);
}
How can I reuse this function or create a new function to achieve the same result but when you load the website?
I have a lot of route so I think that I will need a function in order to don't repeat the same code over and over.
I don't use the locale on the URL and I don't want to use it, so please don't propose a solution that includes that option.
Example of my URLS (each URL can be view with all the available languages)
domain/city1/
domain/city1/dashboard/
domain/city2/
domain/city2/dashboard/
domain/admin/
I don't want:
domain/city1/en/...
domain/city1/pt/...
Probably you need something like this, whenever the page load initially there won't be any server value so it cannot set value for the $userLangs variable. So as per your code, the if statement fails since there is no session value and the elseif condition also fails since there is no value set for $userLangs which cannot be found in the $availableLangs. Just add one else condition to set a default lanuage of the website when there is no prefered user language.
public function handle($request, Closure $next)
{
$availableLangs = array('en', 'hu', 'pt', 'ro', 'sv');
$userLangs = substr($request->server('HTTP_ACCEPT_LANGUAGE'), 0, 2);
if (\Session::has('locale'))
{
\App::setlocale(\Session::get('locale'));
}
else if (in_array($userLangs, $availableLangs))
{
\App::setLocale($userLangs);
Session::put('locale', $userLangs);
}
else {
\App::setLocale('en');
Session::put('locale', 'en');
}
return $next($request);
}

Setting Wordpress-language programmatically in version 4+

I developed my own huge WP-plugin and localized it in 3 languages. It works great when switching the language from wp-admin->settings, but it does not switch language when I switch the language per code like this:
add_filter( 'locale', 'wpse_52419_change_language' );
function wpse_52419_change_language( $locale ){
return 'fr_FR';
}
The rest of the site however is switching according to this code.
What could be wrong?
Ok, my fault was simpel: I included the load_plugin_textdomain-command too early.
Just as a note, maybe it will help someone, I now did the following which works like a charm:
add_filter( 'locale', 'slople_change_language' );
function slople_change_language( $locale )
{
$lang = 'en';
if(isset($_GET['lang'])) {
//get parameter is the most important factor
$lang = $_GET['lang'];
}else if(isset($_COOKIE['lang'])){
//cookie is the 2nd most important factor
$lang = $_COOKIE['lang'];
}else{
//try to make an educated guess about what the user wants to see
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
}
//store current language in cookie
setcookie('lang', $lang, time() + (10 * 365 * 24 * 60 * 60), "/");
$langIsoCode = $lang.'_'.strtoupper($lang);
return $langIsoCode;
}

options array in Joomla session?

I've been analyzing joomla session and I came across a few problems. One of the problems is the session name.
See this code:(seesion.php#894)
protected function _setOptions(array $options)
{
// Set name
if (isset($options['name']))
{
session_name(md5($options['name']));
}
// Set id
if (isset($options['id']))
{
session_id($options['id']);
}
// Set expire time
if (isset($options['expire']))
{
$this->_expire = $options['expire'];
}
// Get security options
if (isset($options['security']))
{
$this->_security = explode(',', $options['security']);
}
if (isset($options['force_ssl']))
{
$this->_force_ssl = (bool) $options['force_ssl'];
}
// Sync the session maxlifetime
ini_set('session.gc_maxlifetime', $this->_expire);
return true;
}
My problem is with the $options array , I add this to the script:
print_r($options);
the result was: Array ( [name] => 266e79f0eac297f66eaf7926636f03fa [expire] => 900 )
where did this element come from ? I mean is there a value that will allow me to do this:
md5('value');
and get the same [name] element
Hey i found the answer for this.
The session value is calculated as following.
$hash = md5(md5($secret.'site'));
where $secret is defined in the configuration file.
use following code to get the session value.
include_once(dirname(dirname(FILE)).DIRECTORY_SEPARATOR.'configuration.php');
$config = new JConfig;
$secret = $config->secret;
$hash = md5(md5($secret.'site'));
So for you the value of name variable comes from md5($secret.'site') which is session value. and if you take md5 again it will give you the session cookie value.

How to get Response of REST API in JSON format by Default in Magento

In magento as we use the REST url to access the data,as http://localhost/magemto/api/rest/products it returns in XML format.
But as my team requirement, I should send the data in JSON format to access AJAX calls easily.. I have used REST client to include a header as 'Content-Type:appilcation/json'.. Then it returns in JSON format.. But I want it as defaultly by the magento API..
Hey, I do have a solution for this, I would like to share with you.
First go to your magento root folder then go to following path
\app\code\core\Mage\Api2\Model\Request.php
Go to the method getAccepTypes() and change with this code below it will fulfill your requirement.
public function getAcceptTypes()
{
$qualityToTypes = array();
$orderedTypes = array();
foreach (preg_split('/,\s*/', $this->getHeader('Accept')) as $definition) {
$typeWithQ = explode(';', $definition);
$mimeType = trim(array_shift($typeWithQ));
// check MIME type validity
if (!preg_match('~^([0-9a-z*+\-]+)(?:/([0-9a-z*+\-\.]+))?$~i', $mimeType)) {
continue;
}
$quality = '1.0'; // default value for quality
if ($typeWithQ) {
$qAndValue = explode('=', $typeWithQ[0]);
if (2 == count($qAndValue)) {
$quality = $qAndValue[1];
}
}
$qualityToTypes[$quality][$mimeType] = true;
}
krsort($qualityToTypes);
foreach ($qualityToTypes as $typeList) {
$orderedTypes += $typeList;
}
unset($orderedTypes);
$orderedTypes=Array
("application/json" => 1);
return array_keys($orderedTypes);
}
Hope this help you.

Codeigniter change database config at runtime

Can I change the database config per method in a controller?
$db['default']['db_debug'] = TRUE;
The default is TRUE, while I need to make it false in a certain method to catch the error and do something else (for example show 404 page).
When I tried $this->config->load('database') it fails.
Another question :
Can I check an incorrect query and catch it to some variables rather than displaying it to users other than setting the db_debug config to FALSE?
I checked the code of system/database/DB_Driver and found that:
$this->db->db_debug = FALSE;
will work in my controller to enable/disable the debug thing on the fly.
Expanding on the answer by comenk, you can extend the database class and implement various methods by which to achieve your goal.
First, you'll need to extend the core Loader class by creating a MY_Loader.php file
class MY_Loader extends CI_Loader
{
function __construct()
{
parent::__construct();
}
/**
* Load the Standard and/or Extended Database function & Driver class
*
* #access public
* #return string
*/
function database( $params = '', $return = FALSE, $active_record = NULL )
{
$ci =& get_instance();
if (class_exists('CI_DB') AND $return == FALSE AND $active_record == NULL AND isset($ci->db) AND is_object($ci->db))
{
return FALSE;
}
$my_db = config_item('subclass_prefix').'DB';
$my_db_file = APPPATH.'core/'.$my_db.EXT;
if(file_exists($my_db_file))
{
require_once($my_db_file);
}
else
{
require_once(BASEPATH.'database/DB'.EXT);
}
// Load the DB class
$db =& DB($params, $active_record);
$my_driver = config_item('subclass_prefix').'DB_'.$db->dbdriver.'_driver';
$my_driver_file = APPPATH.'core/'.$my_driver.EXT;
if(file_exists($my_driver_file))
{
require_once($my_driver_file);
$db = new $my_driver(get_object_vars($db));
}
if ($return === TRUE)
{
return $db;
}
// Initialize the db variable. Needed to prevent
// reference errors with some configurations
$ci->db = '';
$ci->db = $db;
}
}
By implementing the above this will allow you to create a MY_DB_mysqli_driver.php whereby mysqli is replaced by whatever driver you're using in your CI database.php config.
At this point you'd add comenk's answer to MY_DB_mysqli_driver.php
function debug_on() {
return $this->db_debug = TRUE;
}
function debug_off() {
return $this->db_debug = FALSE;
}
function in_error() {
return (bool) $this->_error_number();
}
Then in your model/controller,
$this->db->debug_off();
$this->db->query('SELECT * FROM `table`');
if( $this->db->in_error() ) {
show_404();
}
$this->db->debug_on();
you must add function on system/database/DB_driver.php
function debug_on()
{
$this->db_debug = TRUE;
return TRUE;
}
function debug_off()
{
$this->db_debug = FALSE;
return FALSE;
}
after that you can simply do this command to changes at run-time
$this->db->debug_off();
$this->db->reconnect();
$this->db->db_debug = 0; // 0: off, 1: on
That worx for me...
You can look at the $GLOBALS variable to locate this generic setting.
To hide bad SQL (and other errors) from users, you need to set the php error reporting level. CodeIgniter ships in basically development mode.
Go to index.php and replace this
error_reporting(E_ALL);
with this
error_reporting(0);
This is the quick way to do it. You can also implement this using a hook, so you don't have to touch CI files. You can also add logic to that hook so that it only sets it on the production server.
For debugging SQL, you can create a class that inherits from CI_Model, then create all your model classes to extend that class. In that class, you can add code for running queries that writes the queries to the log so that you can debug them easier. This won't help if the query itself is bad, but you should be able to figure that out before you get to that point.

Resources