I've extended the CI_Lang to handle multilanguage.
Now i wanna get the site_lang from the cookie to see if there is already a language chosen
class MY_Lang extends CI_Lang
{
var $currentLanguage;
function __construct() {
global $URI, $CFG, $IN;
$config =& $CFG->config;
/*Get array with available languages*/
$index_page = $config['index_page'];
$default_abbr = $config['lang_abbr'];
$lang_uri_abbr = $config['lang_uri_abbr'];
/* get the language abbreviation from uri */
$uri_abbr = $URI->segment(1);
/* adjust the uri string leading slash */
$URI->uri_string = preg_replace("|^\/?|", '/', $URI->uri_string);
/* get the language_abbreviation from cookie */
$lang_abbr = $IN->cookie('site_lang');
// check validity against config array
if (isset($lang_uri_abbr[$uri_abbr])) {
// reset uri segments and uri string
$URI->segment(array_shift($URI->segments));
$URI->uri_string = preg_replace("|^\/?$uri_abbr|", '', $URI->uri_string);
if(!empty(LOCATION)){
$this->currentLanguage = strtolower('nl');
// set config language values to match the user language
$config['language'] = $this->currentLanguage;
$config['lang_abbr'] = 'nl-be';
}else{
$this->currentLanguage = strtolower($lang_uri_abbr[$uri_abbr]);
// set config language values to match the user language
$config['language'] = $lang_uri_abbr[$uri_abbr];
$config['lang_abbr'] = $uri_abbr;
}
// check and set the uri identifier
$index_page .= empty($index_page) ? $uri_abbr : "/$uri_abbr";
// reset the index_page value
$config['index_page'] = $index_page;
} else {
$config['lang_splash_ignore'] = FALSE;
}
}
now the value of that $lang_abbr is
string '9e25c0674e5616408f3b1fedd0c43243c0e25335dc92962238f6b2d5fcd0ed5b34d78fe5eceef80e447eaef904965f18699a58c082fde710d0e9976afc7373e9RL3VywiN5Ga7GDnac/vhphR+Ls4NnEi6fHZNm0bGrsQ=' (length=172)
The var_dump of $_COOKIE
array (size=4)
'httpTokens' => string 'd18e3a9aff2ee16e7366ac2bf15c7332d1a6afde32ce9db3be4f9193459706feea8925a54ba4369404adbbaf3803e470cd435b3beaf9d8ba3bff9134d351f79f26iSUDpBMwABR6eElE9igxS55I+KEvntC5NgVeQB768=' (length=172)
'httpUser' => string '74f0cc1d2fb1fd22d963bada94a7ea7cd3221cb8f4c023a66cc337986de0f26c87f44c155acb66d9dc56427e762c0b6906650d9e9c56ba83434e89cc06adc8fbNvdll6arPiQsdRJt/yaOL3J+WZWNfizLE9SRQ2KgyNU+qOz9bqPhVLhfB1yEVElXaw9gHoGp6WwqbsbUhH8Ca+g+dIACtHY1fAJUhc0Xpbs=' (length=236)
'ci_session' => string '69efc00e94d5eea572c53070ae32e831395c911e' (length=40)
'site_lang' => string '9e25c0674e5616408f3b1fedd0c43243c0e25335dc92962238f6b2d5fcd0ed5b34d78fe5eceef80e447eaef904965f18699a58c082fde710d0e9976afc7373e9RL3VywiN5Ga7GDnac/vhphR+Ls4NnEi6fHZNm0bGrsQ=' (length=172)
This should normally be 'en' or 'fr' or something.
How can I retrieve that actual value?
EDIT
I do also have my controller extended into MY_Controller:
class MY_Controller extends Auth_Controller
{
var $languages;
var $currentLanguage;
var $currentLanguageAbbr;
var $currentLanguageItem;
/**
* Class constructor
*/
public function __construct()
{
parent::__construct();
$this->is_logged_in();
$this->setCurrentLanguage();
$this->setSubdomainBackgroundColorGlobalVariable();
$this->setSupportedLanguages();
}
public function setCurrentLanguage(){
$ci =& get_instance();
//Get current language from the config
$currentLang = $ci->config->item('language');
$currentLangAbbr = $ci->config->item('lang_abbr');
//Force Dutch when local platform
if(!empty(LOCATION)){
$this->currentLanguage = strtolower('nl');
$this->currentLanguageAbbr = strtolower('nl-be');
}else{
$this->currentLanguage = strtolower($currentLang);
$this->currentLanguageAbbr = strtolower($currentLangAbbr);
}
//Set cookie and session with correct language
$this->session->set_userdata('site_lang', $this->currentLanguage);
$cookie = array(
'name' => 'site_lang',
'value' => $this->currentLanguage,
'expire' => 259200,
'secure' => COOKIE_XSS_FILTERING
);
$this->input->set_cookie($cookie);
defined('CURRENT_LANG') OR define('CURRENT_LANG', $this->currentLanguage);
}
Related
I would like to have some help in CodeIgniter 3. Every time I login and redirect to the index page, session is lost.
Here is my code:
Controller:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Secretariat extends CI_Controller {
public function __construct(){
parent::__construct();
$this->load->helper(array('form', 'url'));
$this->load->model('SecretariatModel');
$this->load->model('IndiRegModel');
$this->load->model('RoomModel');
$this->load->model('BuildingModel');
$this->load->model('BilletModel');
$this->load->model('BatchRegModel');
$this->load->library('form_validation');
$this->load->library('session');
}
public function secretariatLogin(){
if ($this->session->isSecretariat){
redirect('secretariat/index', $data);
} else{
$data['title'] = 'PACSA - Philippine Association of Campus Student Adviser';
$this->load->view('include/toppage', $data);
$this->load->view('include/defaultnavbar', $data);
$this->load->view('pacsa/slider');
$this->load->view('secretariat/secretariatLogin', $data);
$this->load->view('include/bottompage');
}
}
public function signin(){
$secretariat = array(
'sec_email' => $this->input->post('sec_email'),
'sec_password' => sha1($this->input->post('sec_password'))
);
$user = $this->SecretariatModel->getSecretariat($secretariat);
//print_r($user->name);die();
if(!$user == null){
$newdata = array(
'sec_id' => $user->sec_id,
'sec_name' => $user->sec_name,
'sec_lastname' => $user->sec_lastname,
'sec_email' => $user->sec_email,
'sec_password' => $user->sec_password,
'sec_status' => $user->sec_status,
'sec_address' => $user->sec_address,
'logged_in' => TRUE,
'isSecretariat' => TRUE
);
$this->session->set_userdata($newdata);
redirect('secretariat/index');
} else {
$data['title'] = 'PACSA - Philippine Association of Campus Student Adviser';
$data['message'] = 'Invalid email or password';
$this->load->view('include/toppage', $data);
$this->load->view('include/defaultnavbar', $data);
$this->load->view('pacsa/slider');
$this->load->view('secretariat/secretariatLogin', $data);
$this->load->view('include/bottompage');
}
}
public function index(){
$data['title'] = 'PACSA - Philippine Association of Campus Student Adviser';
$id = $this->session->sec_id;
var_dump($id);
echo die();
$this->load->view('include/toppage', $data);
$this->load->view('include/secretariatnavbar', $data);
$this->load->view('pacsa/slider');
$this->load->view('secretariat/index', $data);
$this->load->view('include/bottompage');
}
}
So after redirecting to the index page, I want to verify if there is a session involved. I tried to echo the id and the name of the user but I get a null value.
also check your php.ini file for this option:
session.auto_start=1
Go to
system/libraries/Session/session.php
at Line no 281 and replace
ini_set('session.name', $params['cookie_name']);
by
ini_set('session.id', $params['cookie_name']);
This problem occurs normally while upgrading PHP later version to 7.3 +
Have you loaded your session library
this->load->library('session')
Or via autoload
$autoload['libraries'] = array('session');
i just solved my problem turns out i have old version of codeigniter 3 i upgrade my CI to the latest version available on the website . thank you all for the help
I experienced this problem with the $config['sess_driver'] set to 'database'.
I was using a valid MySQL user so CodeIgniter 3 was not complaining about the sql connection but the user did not have all the right permissions to read/write from the table php_sessions (or the one set by $config['sess_save_path']).
In my case, I was using the default user 'debian-sys-maint' in my database.php.
Your problem doesn't come from the session itself.
Try to:
Comment the redirect method and add a var_dump($user) instead to see if your $user is correctly set. The problem could come from your $user object which contains null values for id and name.
Change if(!$user == null){ by if ($user != null) { or if ($user) {.
If you are using PHP 7.1+/7.2 then this problem will happen. Change PHP version to down (to check if it works).
We also get same issues. our spec : InvoicePlane, PHP 7.0, code igniter v.3.1.11. Every controllers which use redirect() helper got err_connection_refused from browser.
After spend hours exhaustive debugging. We solved this by change IP Address base_url to domain name and set certificate from letsencrypt.
Hope this helps, I'm working with Homestead - Vagrant - php7.4 and the only way I got it working was following this answer on Github
Add this in your
Project/application/config/config.php
/*
|--------------------------------------------------------------------------
| Cookie Related Variables
|--------------------------------------------------------------------------
|
| 'cookie_prefix' = Set a cookie name prefix if you need to avoid collisions
| 'cookie_domain' = Set to .your-domain.com for site-wide cookies
| 'cookie_path' = Typically will be a forward slash
| 'cookie_secure' = Cookie will only be set if a secure HTTPS connection exists.
| 'cookie_httponly' = Cookie will only be accessible via HTTP(S) (no javascript)
|
| Note: These settings (with the exception of 'cookie_prefix' and
| 'cookie_httponly') will also affect sessions.
|
*/
$config['cookie_prefix'] = '';
$config['cookie_domain'] = '';
$config['cookie_path'] = '/';
$config['cookie_secure'] = FALSE;
$config['cookie_httponly'] = FALSE;
also change lines from 289 to 352 in your
Project/system/core/Input.php
/**
* Set cookie
*
* Accepts an arbitrary number of parameters (up to 7) or an associative
* array in the first parameter containing all the values.
*
* #param string|mixed[] $name Cookie name or an array containing parameters
* #param string $value Cookie value
* #param int $expire Cookie expiration time in seconds
* #param string $domain Cookie domain (e.g.: '.yourdomain.com')
* #param string $path Cookie path (default: '/')
* #param string $prefix Cookie name prefix
* #param bool $secure Whether to only transfer cookies via SSL
* #param bool $httponly Whether to only makes the cookie accessible via HTTP (no javascript)
* #return void
*/
public function set_cookie($name, $value = '', $expire = 0, $domain = '', $path = '/', $prefix = '', $secure = NULL, $httponly = NULL)
{
if (is_array($name))
{
// always leave 'name' in last place, as the loop will break otherwise, due to $$item
foreach (array('value', 'expire', 'domain', 'path', 'prefix', 'secure', 'httponly', 'name') as $item)
{
if (isset($name[$item]))
{
$$item = $name[$item];
}
}
}
if ($prefix === '' && config_item('cookie_prefix') !== '')
{
$prefix = config_item('cookie_prefix');
}
if ($domain == '' && config_item('cookie_domain') != '')
{
$domain = config_item('cookie_domain');
}
if ($path === '/' && config_item('cookie_path') !== '/')
{
$path = config_item('cookie_path');
}
$secure = ($secure === NULL && config_item('cookie_secure') !== NULL)
? (bool) config_item('cookie_secure')
: (bool) $secure;
$httponly = ($httponly === NULL && config_item('cookie_httponly') !== NULL)
? (bool) config_item('cookie_httponly')
: (bool) $httponly;
if ( ! is_numeric($expire) OR $expire < 0)
{
$expire = 1;
}
else
{
$expire = ($expire > 0) ? time() + $expire : 0;
}
setcookie($prefix.$name, $value, $expire, $path, $domain, $secure, $httponly);
}
Try this
$this->output->profiler(true);
To see if session is really set and also check if the library is loaded
I am Codeigniter and i need dynamic language for users.
I have added drop-down at the header and i want to allow users to change language of site at the frontend.
i tried to change language with below code in one controller
$this->config->set_item('language','spanish');
but its not working its not changing language
i also tried with taking session with below code in one of my controller
$mylanguage = $this->session->set_userdata(array('my_language',$dynamiclang));
and tried to access this variable in config file but its also not working.
help me to make this work.
Finally I Got Success to make multi language
follow below steps
MY_Lang.php file in application\core folder
MY_Lang.php
<?php
(defined('BASEPATH')) OR exit('No direct script access allowed');
class MY_Lang extends CI_Lang
{
function __construct() {
global $URI, $CFG, $IN;
$config =& $CFG->config;
$index_page = $config['index_page'];
$lang_ignore = $config['lang_ignore'];
$default_abbr = $config['language_abbr'];
$lang_uri_abbr = $config['lang_uri_abbr'];
#exit('my_lang');
#print_r($URI);
/*if($index_page=='es')
{
#$config['index_page'] = 'es';
#$config['lang_uri_abbr'] = 'es';
#$IN->set_cookie('user_lang', 'es', $config['sess_expiration']);
#$URI->uri_string = str_replace('es','en',$URI->uri_string);
}
else{
#$config['index_page'] = 'en';
#$config['lang_uri_abbr'] = 'en';
#$IN->set_cookie('user_lang', 'en', $config['sess_expiration']);
}
/* get the language abbreviation from uri */
$uri_abbr = $URI->segment(1);
#$uri_abbr='es';
/* adjust the uri string leading slash */
#print $URI->uri_string;
$URI->uri_string = preg_replace("|^\/?|", '/', $URI->uri_string);
if ($lang_ignore) {
if (isset($lang_uri_abbr[$uri_abbr])) {
/* set the language_abbreviation cookie */
$IN->set_cookie('user_lang', $uri_abbr, $config['sess_expiration']);
} else {
/* get the language_abbreviation from cookie */
$lang_abbr = $IN->cookie($config['cookie_prefix'].'user_lang');
}
if (strlen($uri_abbr) == 2) {
/* reset the uri identifier */
$index_page .= empty($index_page) ? '' : '/';
// exit('654');
/* remove the invalid abbreviation */
$URI->uri_string = preg_replace("|^\/?$uri_abbr\/?|", '', $URI->uri_string);
/* redirect */
header('Location: '.$config['base_url'].$index_page.$URI->uri_string);
exit;
}
} else {
/* set the language abbreviation */
$lang_abbr = $uri_abbr;
}
/* check validity against config array */
if (isset($lang_uri_abbr[$lang_abbr])) {
/* reset uri segments and uri string */
//$URI->_reindex_segments(array_shift($URI->segments)); # this is commented becasue this is giving error : #$hok : 09/August/2015
$URI->uri_string = preg_replace("|^\/?$lang_abbr|", '', $URI->uri_string);
/* set config language values to match the user language */
$config['language'] = $lang_uri_abbr[$lang_abbr];
$config['language_abbr'] = $lang_abbr;
/* if abbreviation is not ignored */
if ( ! $lang_ignore) {
/* check and set the uri identifier */
$index_page .= empty($index_page) ? $lang_abbr : "/$lang_abbr";
/* reset the index_page value */
$config['index_page'] = $index_page;
}
/* set the language_abbreviation cookie */
$IN->set_cookie('user_lang', $lang_abbr, $config['sess_expiration']);
} else {
/* if abbreviation is not ignored */
if ( ! $lang_ignore) {
/* check and set the uri identifier to the default value */
$index_page .= empty($index_page) ? $default_abbr : "/$default_abbr";
if (strlen($lang_abbr) == 2) {
/* remove invalid abbreviation */
$URI->uri_string = preg_replace("|^\/?$lang_abbr|", '', $URI->uri_string);
}
/*echo '<pre>';
print_r($_SERVER);
print_r($config['base_url'].$index_page.$URI->uri_string);
exit;*/
$q = $_SERVER['QUERY_STRING'];
if($q)
$q = "/?".$q;
/* redirect */
header('Location: '.$config['base_url'].$index_page.$URI->uri_string.$q);
exit;
}
/* set the language_abbreviation cookie */
$IN->set_cookie('user_lang', $default_abbr, $config['sess_expiration']);
}
log_message('debug', "Language_Identifier Class Initialized");
}
}
/* translate helper */
function t($line) {
global $LANG;
//print_r($LANG);
// exit;
return ($t = $LANG->line($line)) ? $t : $line;
}
function _t($line,$params=array()) {
global $LANG;
if($params){
echo str_replace(array_keys($params),array_values($params),($t = $LANG->line($line)) ? $t : $line);
}
else
echo ($t = $LANG->line($line)) ? $t : $line;
} ?>
and added below things in config.php
$config['language'] = "english";
/* default language abbreviation */
$config['language_abbr'] = "en";
/* set available language abbreviations */
$config['lang_uri_abbr'] = array("en" => "english","es" => "spanish","ca" => "catalan");
/* hide the language segment (use cookie) */
$config['lang_ignore'] = TRUE;
added below code in route.php
$route['^en/(.+)$'] = "$1";
$route['^es/(.+)$'] = "$1";
$route['^ca/(.+)$'] = "$1";
$route['^(\w{2})$'] = $route['default_controller'];
$route['^(\w{2})/(.+)$'] = "$2";
and added language files in language folder like below
language/catalan
language/spanish
language/english
i hope this will help.
Have you tried to add this in Your controller?
$this->load->helper('language');
Load the current language in the cookie and load the language file using the language value in the cookie
Example whenever user selects a language use the function below to set the current language to the cookie
function language($lang = false) {
if($this->input->get('lang')){ $lang = $this->input->get('lang'); }
$folder = 'application/language/';
$languagefiles = scandir($folder);
if(in_array($lang, $languagefiles)){
$cookie = array(
'name' => 'lang',
'value' => $lang,
'expire' => '31536000',
'prefix' => 'my_',
'secure' => false
);
$this->input->set_cookie($cookie);
}
$this->config->set_item('language', $lang);
redirect($_SERVER["HTTP_REFERER"]);
}
Then on the constructor of your main Custom Controller or if you are just extending CI_Controller then load on each controller's constructor the language file(s) and like
$this->lang->load('language_filename', get_cookie('my_lang'));
You are done
I'm new to Kohana, using version 3.3.3.1, I'm trying to build a simple dynamic site with the content/pages stored in mySQL DB. The site should have multiple languages. I tried searching everywhere for a good solution/module but I couldn't find anything that works with latest version of Kohana. I tried also this: https://github.com/shockiii/kohana-multilang but it's not working on the latest kohana.
I want to put the language in URL like this (and possibly hide the parameter for the default language):
http://www.domain.com/topics/page-name-here.html -- this would be default EN
http://www.domain.com/de/test/some-page-name-here.html
http://www.domain.com/fr/category/other-page-name-here.html
In my bootstrap.php I have the following route (before adding the language logic):
Route::set('page', '(<category>)(/<pagename>.html)', array(
'category' => '.*',
'pagename' => '.*'))
->defaults(array(
'controller' => 'Page',
'action' => 'index',
));
I want to have all this multi-language logic inside a module if possible. But I read about overriding the Request, URL, Route, and other classes to be able to do that.
What is the best way I can do this? What should I do/change and where to start?
I know this is more a general question, but any help or guidance is greatly appreciated.
Thanks very much!
1) add <lang> into routes in bootstrap.php:
Route::set('default', '((<lang>)(/)(<controller>)(/<action>(/<id>)))', array('lang' => "({$langs_abr})",'id'=>'.+'))
->defaults(array(
'lang' => $default_lang,
'controller' => 'Welcome',
'action' => 'index',
));
- define $default_lang somehow - I use siteconfig.php file placed inside application/config -see below.
2) Extend/redefine factory method in Request Controller:
<?php defined('SYSPATH') or die('No direct script access.');
class Request extends Kohana_Request {
/**
* Main request singleton instance. If no URI is provided, the URI will
* be automatically detected using PATH_INFO, REQUEST_URI, or PHP_SELF.
*
* #param string URI of the request
* #return Request
*/
public static function factory( $uri = TRUE,$client_params = array(), $allow_external = TRUE, $injected_routes = array())
{
$instance = parent::factory($uri);
$index_page = Kohana::$index_file;
$siteconfig = Model_Siteconfig::load();
$lang_uri_abbr = $siteconfig['lang_uri_abbr'];
$default_lang = $siteconfig['language_abbr'];
$lang_ignore = $siteconfig['lang_ignore'];
$ignore_urls = $siteconfig['ignore_urls'];
/* get the lang_abbr from uri segments */
$segments = explode('/',$instance->detect_uri());
$uri_detection = array_intersect($segments, $ignore_urls);
if(empty($uri_detection))
{
$lang_abbr = isset($segments[1]) ? $segments[1]:'';
/* get current language */
$cur_lang = $instance->param('lang',$default_lang);
/* check for invalid abbreviation */
if( ! isset($lang_uri_abbr[$lang_abbr]))
{
/* check for abbreviation to be ignored */
if ($cur_lang != $lang_ignore) {
/* check and set the default uri identifier */
$index_page .= empty($index_page) ? $default_lang : "/$default_lang";
/* redirect after inserting language id */
header('Location: '.URL::base().$index_page . $instance->detect_uri());
die();
}
}
}
return $instance;
}
}
I use "siteconfig" array with language definitions:
array(
'language_abbr' => 'cs',
'lang_uri_abbr' => array("cs" => "Ĩesky", "en" => "english"),
'lang_ignore' => 'it',
)
3) Extend/redefine "redirect" method in Controller class for automatic language adding:
<?php defined('SYSPATH') or die('No direct script access.');
class Controller extends Kohana_Controller {
/**
* Issues a HTTP redirect.
*
* Proxies to the [HTTP::redirect] method.
*
* #param string $uri URI to redirect to
* #param int $code HTTP Status code to use for the redirect
* #throws HTTP_Exception
*/
public static function redirect($uri = '', $code = 302)
{
$lng = Request::current()->param('lang');
return HTTP::redirect( (string) '/'.$lng.$uri, $code);
}
}
If You would use HTML class (for templates for example), you should probably redefine some other methods like "anchor" for creating anchors with automatic language adding:
<?php defined('SYSPATH') OR die('No direct script access.');
class HTML extends Kohana_HTML {
/**
* Create HTML link anchors. Note that the title is not escaped, to allow
* HTML elements within links (images, etc).
*
* echo HTML::anchor('/user/profile', 'My Profile');
*
* #param string $uri URL or URI string
* #param string $title link text
* #param array $attributes HTML anchor attributes
* #param mixed $protocol protocol to pass to URL::base()
* #param boolean $index include the index page
* #return string
* #uses URL::base
* #uses URL::site
* #uses HTML::attributes
*/
public static function anchor($uri, $title = NULL, array $attributes = NULL, $protocol = NULL, $index = FALSE)
{
//default language
$lng = Request::current()->param('lang');
if ($title === NULL)
{
// Use the URI as the title
$title = $uri;
}
if ($uri === '')
{
// Only use the base URL
$uri = URL::base($protocol, $index).$lng;
}
else
{
if (strpos($uri, '://') !== FALSE)
{
if (HTML::$windowed_urls === TRUE AND empty($attributes['target']))
{
// Make the link open in a new window
$attributes['target'] = '_blank';
}
}
elseif ($uri[0] !== '#')
{
// Make the URI absolute for non-id anchors
$uri = URL::site($lng.$uri, $protocol, $index);
}
}
// Add the sanitized link to the attributes
$attributes['href'] = $uri;
return '<a'.HTML::attributes($attributes).'>'.$title.'</a>';
}
}
I found a great module that is working with Kohana 3.3.3: https://github.com/creatoro/flexilang
How to Logout action performed in my website who are login via facebook
my controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Main extends CI_Controller {
public function Main(){
parent::__construct();
parse_str( $_SERVER['QUERY_STRING'], $_REQUEST );
$CI = & get_instance();
$CI->config->load("facebook",TRUE);
$config = $CI->config->item('facebook');
$this->load->library('Facebook', $config);
}
function index(){
// Try to get the user's id on Facebook
$userId = $this->facebook->getUser();
// If user is not yet authenticated, the id will be zero
if($userId == 0){
// Generate a login url
$data['url'] = $this->facebook->getLoginUrl(array('scope'=>'email'));
$this->load->view('main_index', $data);
} else {
// Get user's data and print it
$user = $this->facebook->api('/me');
print_r($user);
}
}
}
?>
my view
Click here to login
config/facebook.php
<?php
$config['appId'] = 'xxxxxxxxxxxxxx';//i have my id like 1411574xxxxxxxxxxxxxx
$config['secret'] = 'xxxxxxxxxx';// i have my id like 2f3917995d2024xxxxxxxxxxxxxx
my library :Facebook.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* Copyright 2011 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
require_once "base_facebook.php";
/**
* Extends the BaseFacebook class with the intent of using
* PHP sessions to store user ids and access tokens.
*/
class Facebook extends BaseFacebook
{
const FBSS_COOKIE_NAME = 'fbss';
// We can set this to a high number because the main session
// expiration will trump this.
const FBSS_COOKIE_EXPIRE = 31556926; // 1 year
// Stores the shared session ID if one is set.
protected $sharedSessionID;
/**
* Identical to the parent constructor, except that
* we start a PHP session to store the user ID and
* access token if during the course of execution
* we discover them.
*
* #param Array $config the application configuration. Additionally
* accepts "sharedSession" as a boolean to turn on a secondary
* cookie for environments with a shared session (that is, your app
* shares the domain with other apps).
* #see BaseFacebook::__construct in facebook.php
*/
public function __construct($config) {
if (!session_id()) {
session_start();
}
parent::__construct($config);
if (!empty($config['sharedSession'])) {
$this->initSharedSession();
}
}
protected static $kSupportedKeys =
array('state', 'code', 'access_token', 'user_id');
protected function initSharedSession() {
$cookie_name = $this->getSharedSessionCookieName();
if (isset($_COOKIE[$cookie_name])) {
$data = $this->parseSignedRequest($_COOKIE[$cookie_name]);
if ($data && !empty($data['domain']) &&
self::isAllowedDomain($this->getHttpHost(), $data['domain'])) {
// good case
$this->sharedSessionID = $data['id'];
return;
}
// ignoring potentially unreachable data
}
// evil/corrupt/missing case
$base_domain = $this->getBaseDomain();
$this->sharedSessionID = md5(uniqid(mt_rand(), true));
$cookie_value = $this->makeSignedRequest(
array(
'domain' => $base_domain,
'id' => $this->sharedSessionID,
)
);
$_COOKIE[$cookie_name] = $cookie_value;
if (!headers_sent()) {
$expire = time() + self::FBSS_COOKIE_EXPIRE;
setcookie($cookie_name, $cookie_value, $expire, '/', '.'.$base_domain);
} else {
// #codeCoverageIgnoreStart
self::errorLog(
'Shared session ID cookie could not be set! You must ensure you '.
'create the Facebook instance before headers have been sent. This '.
'will cause authentication issues after the first request.'
);
// #codeCoverageIgnoreEnd
}
}
/**
* Provides the implementations of the inherited abstract
* methods. The implementation uses PHP sessions to maintain
* a store for authorization codes, user ids, CSRF states, and
* access tokens.
*/
protected function setPersistentData($key, $value) {
if (!in_array($key, self::$kSupportedKeys)) {
self::errorLog('Unsupported key passed to setPersistentData.');
return;
}
$session_var_name = $this->constructSessionVariableName($key);
$_SESSION[$session_var_name] = $value;
}
protected function getPersistentData($key, $default = false) {
if (!in_array($key, self::$kSupportedKeys)) {
self::errorLog('Unsupported key passed to getPersistentData.');
return $default;
}
$session_var_name = $this->constructSessionVariableName($key);
return isset($_SESSION[$session_var_name]) ?
$_SESSION[$session_var_name] : $default;
}
protected function clearPersistentData($key) {
if (!in_array($key, self::$kSupportedKeys)) {
self::errorLog('Unsupported key passed to clearPersistentData.');
return;
}
$session_var_name = $this->constructSessionVariableName($key);
unset($_SESSION[$session_var_name]);
}
protected function clearAllPersistentData() {
foreach (self::$kSupportedKeys as $key) {
$this->clearPersistentData($key);
}
if ($this->sharedSessionID) {
$this->deleteSharedSessionCookie();
}
}
protected function deleteSharedSessionCookie() {
$cookie_name = $this->getSharedSessionCookieName();
unset($_COOKIE[$cookie_name]);
$base_domain = $this->getBaseDomain();
setcookie($cookie_name, '', 1, '/', '.'.$base_domain);
}
protected function getSharedSessionCookieName() {
return self::FBSS_COOKIE_NAME . '_' . $this->getAppId();
}
protected function constructSessionVariableName($key) {
$parts = array('fb', $this->getAppId(), $key);
if ($this->sharedSessionID) {
array_unshift($parts, $this->sharedSessionID);
}
return implode('_', $parts);
}
}
my library base_facebook.php
my library fb_ca_chain_bundle.crt
now i am log in successfully but unable to logout how to log out implement in this please
Try this link
$params = array( 'next' => 'https://www.myapp.com/after_logout' );
$facebook->getLogoutUrl($params); // $params is optional.
use this in view and access the facebook
I'm using Zend-Framework 1.9.5 to make a web-application, But it's Url_Helper was quite tricky to me in the matter of parameter reset!, I know it's a good feature (parameter preserving) but in most cases I don't need it!.
So I'm thinking of overriding the default Router to force it loosing parameters Unless I ask for it or maybe specifying a certain parameters that it keeps like (lang, or something like that).
Also I want to make it the default router so I don't have to edit my Controllers, Views to get that done!
Any suggestions?
Update:
I spent the whole morning trying to write my url helper Admin_View_Helper_Xurl, But I couldn't do anything that solves the problem:
<?php
class Admin_View_Helper_Xurl extends Zend_View_Helper_Abstract
{
public function xurl(array $urlOptions = array(), $name = 'default', $reset = false, $encode = true)
{
$router = Zend_Controller_Front::getInstance()->getRouter();
$wanted_params = array('module', 'controller', 'action', 'lang', 'page', 'search');
$route = $router->getCurrentRoute();
$something = anyWayToGetThatObjectOrClass();
$params = $something->getParams();
foreach($params as $key => $val) {
if (!in_array($key, $wanted_params)) {
$params[$key] = null; // OR uset($params[$key]);
}
}
$something->clearParams();
$something->setParams($params);
return $router->assemble($urlOptions, $name, $reset, $encode);
}
}
I tried to get current URL parameters and filter them and clear the current parameters and pass my filtered ones but I couldn't do anything that does it without hard-code editing one Zend_Framework code :(.
Thanks
When generating a link a view, you can ask the helper to get rid of all aparamters with a simple boolean :
<?php echo $this->url(array('controller' => 'index', action => 'action'), 'default', true); ?>
The last parameter tells whether to reset parameters or not.
I came up with this solution. It took 7 hours to be functional.
class Zend_View_Helper_Xurl extends Zend_View_Helper_Abstract
{
const RESET_ALL = 'all';
const RESET_CUSTOM = 'normal';
const RESET_NON_MVC = 'mvc';
const RESET_NONE = 'none';
protected $_wantedParams = array('module', 'controller', 'action', 'lang', 'page', 'search');
protected $_router;
/**
* Generates an url given the name of a route.
*
* #access public
*
* #param array $urlOptions Options passed to the assemble method of the Route object.
* #param mixed $name The name of a Route to use. If null it will use the current Route
* #param bool $reset Whether or not to reset the route defaults with those provided
* #return string Url for the link href attribute.
*/
public function __construct()
{
$router = Zend_Controller_Front::getInstance()->getRouter();
$this->_router = clone $router;
}
public function xurl(array $urlOptions = array(), $reset = 'mvc', $encode = true)
{
$urlOptions = $this->_getFilteredParams($urlOptions, $reset);
return $this->_router->assemble($urlOptions, $name, true, $encode);
}
protected function _getFilteredParams($data = array(), $level)
{
// $filteredValues = array();
$request = Zend_Controller_Front::getInstance()->getRequest();
$filteredValues = $request->getUserParams();
$$filteredValues['module'] = $request->getModuleName();
$$filteredValues['controller'] = $request->getControllerName();
$$filteredValues['action'] = $request->getActionName();
switch ($level) {
case self::RESET_ALL:
$filteredValues['module'] = null;
$filteredValues['controller'] = null;
$filteredValues['action'] = null;
// break omitted intentionally
case self::RESET_NON_MVC:
$filteredValues['page'] = null;
$filteredValues['lang'] = null;
$filteredValues['search'] = null;
// break omitted intentionally
case self::RESET_CUSTOM:
foreach ($filteredValues as $key=>$val) {
if (!in_array($key, $this->_wantedParams)) {
$filteredValues[$key] = null;
}
}
break;
case self::RESET_NONE:
break;
default:
throw new RuntimeException('Unsuppoted Xurl URL helper reset level.');
break;
}
foreach ($filteredValues as $key => $val) {
if (!array_key_exists($key, $data)) {
$data[$key] = $val;
}
}
return $data;
}
}
Clearly it's a View Helper class, may be not the best solution but it works fine with me for now.