Force language change from custom account creation script through url - joomla

I have made a custom 'Account Creation' script so that users can login from my phone application.
What I want is to be able to change the responses from the server depending on their locale. So when I request a page I would add lang=en or lang=zh etc.
This works
http://mysite.com/phone/my_custom_account_creation.php?lang=en
Response:
<resource classification="error" code="Error (Code: 500)">
<message>Please enter your name:</message>
</resource>
This does not work:
http://mysite.com/phone/my_custom_account_creation.php?lang=zh
Response:
<resource classification="error" code="Error (Code: 500)">
<message>Please enter your name:</message>
</resource>
If I go into Joomla at set the default language to chinese, it works.
<resource classification="error" code="Error (Code: 500)">
<message>请输入您的姓名。</message>
</resource>
but
http://mysite.com/phone/my_custom_account_creation.php?lang=en
does not work, instead it continues to show the chinese version.
What might I be able to do here?
here is the code I am using for registration:
<?php
header ("content-type: text/xml");
/*
* Register a user from a phone interface using JAVA
*/
define( '_JEXEC', 1 );
//define('JPATH_BASE', dirname(__FILE__) );//this is when we are in the root
define('JPATH_BASE', dirname(__FILE__)."/../.." );//this is when we are in the root
define( 'DS', DIRECTORY_SEPARATOR );
require_once ( JPATH_BASE .DS.'includes'.DS.'defines.php' );
require_once ( JPATH_BASE .DS.'includes'.DS.'framework.php' );
//My functions
require_once('../shared_functions.php');
$mainframe =& JFactory::getApplication('site');
$mainframe->initialise();
//Don't use tokens for registration
//JRequest::checkToken() or jexit( 'Invalid Token' );
$user = clone(JFactory::getUser());
$pathway = & $mainframe->getPathway();
$config = & JFactory::getConfig();
$authorize = & JFactory::getACL();
$document = & JFactory::getDocument();
$usersConfig = &JComponentHelper::getParams( 'com_users' );
if ($usersConfig->get('allowUserRegistration') == '0')
{
xmlError("Access Forbidden (Code 403)","Registration has been temporarily disabled");
//JError::raiseError( 403, JText::_( 'Access Forbidden' ));
return;
}
$newUsertype = $usersConfig->get( 'new_usertype' );
if (!$newUsertype)
{
$newUsertype = 'Registered';
}
if (!$user->bind( JRequest::get('post'), 'usertype' ))
{
xmlError("Error (Code: 500)",$user->getError());
return;
//JError::raiseError( 500, $user->getError());
}
$user->set('id', 0);
$user->set('usertype', '');
$user->set('gid', $authorize->get_group_id( '', $newUsertype, 'ARO' ));
$date =& JFactory::getDate();
$user->set('registerDate', $date->toMySQL());
$useractivation = $usersConfig->get( 'useractivation' );
if ($useractivation == '1')
{
jimport('joomla.user.helper');
$user->set('activation', md5( JUserHelper::genRandomPassword()) );
$user->set('block', '1');
}
if (!$user->save()) { // if the user is NOT saved...
xmlError("Error (Code: 500)",$user->getError());
//JError::raiseWarning('', JText::_( $user->getError())); // ...raise an Warning
//return false; // if you're in a method/function return false
}
xmlMessage("ok",CODE_ACCOUNT_CREATED,"Success");
?>

I got it working
$lang =& JFactory::getLanguage();
$lang->setLanguage( $_GET['lang'] );
$lang->load();
I found that the language had to be in full format though en-GB or zh-CN

Related

Stripe payments are not working if I load Woocommerce checkout via AJAX

I'm trying to load Woocommerce checkout form via Ajax on a custom landing page so that it can have an instant checkout for the visitor.
I'm using the following code:
PHP function for AJAX:
add_action( 'wp_ajax_getCheckoutPageContent', 'getCheckoutPageContentCallBack' );
add_action( 'wp_ajax_nopriv_getCheckoutPageContent', 'getCheckoutPageContentCallBack' );
function getCheckoutPageContentCallBack() {
$product_id = absint( $_POST['product_id'] );
$quantity = absint( $_POST['quantity'] );
$product_status = get_post_status( $product_id );
$passed_validation = apply_filters( 'woocommerce_add_to_cart_validation', true, $product_id, $quantity );
if ( WC()->cart->add_to_cart( $product_id, $quantity ) ) {
do_action( 'woocommerce_ajax_added_to_cart', $product_id );
global $woocommerce;
$items = $woocommerce->cart->get_cart();
wc_setcookie( 'woocommerce_items_in_cart', count( $items ) );
wc_setcookie( 'woocommerce_cart_hash', md5( json_encode( $items ) ) );
do_action( 'woocommerce_set_cart_cookies', true );
define( 'WOOCOMMERCE_CHECKOUT', true );
echo do_shortcode('[woocommerce_checkout]');
}else{
define( 'WOOCOMMERCE_CHECKOUT', true );
echo do_shortcode('[woocommerce_checkout]');
}
die();
}
Javascrip code:
var wp_ajax_url= myAjax.ajaxurl;
var data = {
action: 'getCheckoutPageContent',
product_id: $('#land_prod_id').val(),
quantity: 1
};
jQuery.post( wp_ajax_url, data, function(content) {
jQuery("#buy_form_location").html(content);
});
} else{
All payment methods work except for Stripe where I get redirected to the actual checkout page, with the following error: Payment processing failed. Please retry.
On the regular checkout page the payment works, but I'd like it to work on the one loaded via AJAX too.
I'm using this plugin: woocommerce.com/products/stripe

facebook php sdk $sess returns null?

** My problem is I cant login with facebook using facebook php sdk v4 to my website through domain but when I try it on my localhost it works perfectly fine. What could be the problem?**
This is my index.php
<?php include'facebook/fbconnect.php';?>
<?php
require 'connection/connect.inc.php';
require 'connection/core.inc.php';
if(isset($_GET['username'])&&isset($_GET['password'])){
$user=$_GET['username'];
$pass=$_GET['password'];
$query="select Acc_Id from account where Acc_Status_Id=1 and BINARY Acc_Domain_Id=4 and Acc_Username='".$user."' and BINARY Acc_Password='".$pass."' and Acc_Type_Id=1";
if($query_run=mysql_query($query)or die(mysql_error())){
$mysql_rows=mysql_num_rows($query_run);
if($mysql_rows==1){
$user_id = mysql_result($query_run, 0, 'Acc_Id');
$_SESSION['acc_id']=$user_id;
header('Location:index.php');
}else{
?>
<script type="text/javascript">
alert("Invalid Data !");
history.back();
</script>
<?php
}
}
}
use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\GraphUser;
use Facebook\GraphSessionInfo;
use Facebook\FacebookHttpable;
use Facebook\FacebookCurlHttpClient;
use Facebook\FacebookCurl;
if(isset($sess)){
//store the token in the php session
$_SESSION['fb_token']=$sess->getToken();
//create request object,execute and capture response
$request = new FacebookRequest($sess,'GET','/me');
// from response get graph object
$response = $request->execute();
$graph = $response->getGraphObject(GraphUser::classname());
// use graph object methods to get user details
$name = $graph->getName();
$id = $graph->getId();
$image = 'https://graph.facebook.com/'.$id.'/picture?width=300';
$email = $graph->getProperty('email');
//db check for fb.
$query="select Acc_Id from account where Acc_Status_Id=1 and BINARY Acc_Domain_Id=1 and Acc_Username='$id' and Acc_Type_Id=1";
if($query_run1=mysql_query($query)or die(mysql_error())){
$mysql_rows1=mysql_num_rows($query_run1);
if($mysql_rows1==1){
$user_id1 = mysql_result($query_run1, 0, 'Acc_Id');
$_SESSION['acc_id']=$user_id1;
}else{
$ins="insert into account (Acc_Username,Acc_Name,Acc_Email,Acc_Type_Id,Acc_Status_Id,Acc_Domain_Id)values('$id','$name','$email',1,1,1)";
//echo $ins;
mysql_query($ins)or die(mysql_error());
$user_id = mysql_insert_id();
$_SESSION['acc_id']=$user_id;
}
}
include 'home_1.php';
}else{
if(loggedin()){
include 'home_1.php';
}else{
include 'home_1G.php';
}
}
?>
This is my fbconnect.php
<?php
require_once( 'lib/Facebook/FacebookSession.php');
require_once( 'lib/Facebook/FacebookRequest.php' );
require_once( 'lib/Facebook/FacebookResponse.php' );
require_once( 'lib/Facebook/FacebookSDKException.php' );
require_once( 'lib/Facebook/FacebookRequestException.php' );
require_once( 'lib/Facebook/FacebookRedirectLoginHelper.php');
require_once( 'lib/Facebook/FacebookAuthorizationException.php' );
require_once( 'lib/Facebook/GraphObject.php' );
require_once( 'lib/Facebook/GraphUser.php' );
require_once( 'lib/Facebook/GraphSessionInfo.php' );
require_once( 'lib/Facebook/Entities/AccessToken.php');
require_once( 'lib/Facebook/HttpClients/FacebookCurl.php' );
require_once( 'lib/Facebook/HttpClients/FacebookHttpable.php');
require_once( 'lib/Facebook/HttpClients/FacebookCurlHttpClient.php');
/* USE NAMESPACES */
use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\GraphUser;
use Facebook\GraphSessionInfo;
use Facebook\FacebookHttpable;
use Facebook\FacebookCurlHttpClient;
use Facebook\FacebookCurl;
/PROCESS/
//1.Stat Session
session_start();
//check if users wants to logout
if(isset($_REQUEST['logout'])){
unset($_SESSION['fb_token']);
}
//2.Use app id,secret and redirect url
$app_id = '**';
$app_secret = '**';
$redirect_url='**';
//3.Initialize application, create helper object and get fb sess
FacebookSession::setDefaultApplication($app_id,$app_secret);
$helper = new FacebookRedirectLoginHelper($redirect_url);
$sess = $helper->getSessionFromRedirect();
//check if facebook session exists
if(isset($_SESSION['fb_token'])){
$sess = new FacebookSession($_SESSION['fb_token']);
} ?>
I'm sure I made the app_id secret and even the url right.
We had a similar problem recently. Local and beta servers worked but our production server did not.
The problem, V4 requires PHP version 5.4 or higher.
https://developers.facebook.com/docs/php/gettingstarted/4.0.0
Might not be your problem but sounds really like ours. Hope it helps.

getting session information works only once what is going on

try to get session data from a joomla site with this code it work once but after logong out and in again get no more data.
define( '_JEXEC', 1 );
define( 'JPATH_BASE', realpath(dirname(__FILE__).'/../..' ));
require_once ( JPATH_BASE .'/includes/defines.php' );
require_once ( JPATH_BASE .'/includes/framework.php' );
$mainframe = JFactory::getApplication('site');
$mainframe->initialise();
$session = JFactory::getSession();
print_r($SESSION);
$user = JFactory::getUser();
echo $user;
$username=$user->get('username'); // username text same as database table
$userId = $user->get( 'id' ); //id text same as database table
$useremail=$user->get('email'); // email text same as database table
echo "UserID is: ".$userId;
echo '</br>';
echo "UserName is :".$username;
echo '</br>';
echo "User Email is :".$useremail;
the output is
JUserUserID is: 0
UserName is :
User Email is :
it worked for 1 session after that nothing

Joomla 2.5 Get User Data from External Script

I need to get the information of the user that's currently logged in to Joomla from a program outside of Joomla itself. I upgraded from 1.5 to 2.5, and what I had before doesn't work anymore.
<?php
define( '_VALID_MOS', 1 );
include_once( 'globals.php' );
require_once( 'configuration.php' );
require_once( 'includes/joomla.php' );
$option="test";
$mainframe = new mosMainFrame( $database, $option, '.' );
$mainframe->initSession();
$my = $mainframe->getUser();
$joomla_name = $my->name;
$joomla_email = $my->email;
$joomla_password = $my->password;
After some research, I've come up with this:
<?php
define( '_JEXEC', 1 );
define( 'JPATH_BASE', dirname(__FILE__) );
define( 'DS', '/' );
require_once ( JPATH_BASE .DS.'configuration.php' );
require_once ( JPATH_BASE .DS.'includes'.DS.'defines.php' );
require_once ( JPATH_BASE .DS.'includes'.DS.'framework.php' );
require_once ( JPATH_BASE .DS.'libraries'.DS.'joomla'.DS.'factory.php' );
$my =& JFactory::getUser();
$joomla_name = $my->name;
$joomla_email = $my->email;
$joomla_password = $my->password;
$joomla_username = $my->username;
It doesn't produce any errors but seems to work. However, the user object is empty. This script is in the same directory as the Joomla installation. What may be the problem? Thanks!
Sources:
http://www.cmsbloke.com/accessing-joomla-objects-from-an-external-script/
Taken from
http://docs.joomla.org/How_to_access_session_variables_set_by_an_external_script
Solution: Replace session_start(); in your external script with
define( '_JEXEC', 1 );
define( 'JPATH_BASE', realpath(dirname(__FILE__).'/../..' ));
define( 'DS', DIRECTORY_SEPARATOR );
require_once ( JPATH_BASE .DS.'includes'.DS.'defines.php' );
require_once ( JPATH_BASE .DS.'includes'.DS.'framework.php' );
$mainframe =& JFactory::getApplication('site');
$mainframe->initialise();
Be sure to change JPATH_BASE to suit your directory structure.
Replace the $_SESSION[ 'name' ] = "value"; in your external script with
$session =& JFactory::getSession();
$session->set('name', "value");
Now you can retrieve this session variable using:
$session =& JFactory::getSession();
echo $session->get('name');
It turns out, I had two problems:
My script was on www.example.com, while I was logged in under example.com, so the different domain was throwing off the session data.
I also wasn't initialising the application, which apparently is necessary.
Here are the results:
<?php
define( '_JEXEC', 1 );
define( 'JPATH_BASE', dirname(__FILE__) );
define( 'DS', '/' );
require_once ( JPATH_BASE .DS.'includes'.DS.'defines.php' );
require_once ( JPATH_BASE .DS.'includes'.DS.'framework.php' );
JFactory::getApplication('site')->initialise();
$user = JFactory::getUser();
$joomla_name = $user->name;
$joomla_email = $user->email;
$joomla_password = $user->password;
$joomla_username = $user->username;
I think people have had problems with this in Joomla 2.5 as things have changed. I haven't found a solution for the way you have requested but wrote this work around (excluding the password field though) that you may want to use.
define a connection to the database:
<?php
$host="localhost";
$username="DB_USERNAME";
$password="DB_PASSWORD";
$db_name="DB_NAME";
mysql_connect($host,$username,$password)or die(mysql_error());
mysql_select_db($db_name)or die(mysql_error());
?>
Echo create a query and echo the results in a table:
<table style="background:#FFF; color:#000;">
<?php
$query = "SELECT username,name,email FROM j25_users ";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
echo '<tr><td>',$row["username"],'</td><td>',$row["name"],'</td><td>',$row["email"],'</td></tr>' ;
}
?>
</table>
You will need to change j25_users to the correct prefix of your database tables.
Update: Much better to import the framework to get the user object.
Hope this comes in handy for you. Regards.
If you want to skip using Joomla! functions, you can query the Joomla! database. Join tables js25_session and js25_users with the user id. This way, you can get every currently logged-in user and all guests on the website (and possibly the number of online users).

Joomla 1.7 Authentication from external app

My aim is to check that a Joomla username and password is valid from my external application. It is not necessary that the user is logged into the system, just that their account exists.
I decided to create my own authentication plugin based on the Joomla Authentication (JOOMLA_PATH/plugins/authentication/joomla). I only changed the name:
<?php
/**
* #version $Id: joomla.php 21097 2011-04-07 15:38:03Z dextercowley $
* #copyright Copyright (C) 2005 - 2011 Open Source Matters, Inc. All rights reserved.
* #license GNU General Public License version 2 or later; see LICENSE.txt
*/
// No direct access
defined('_JEXEC') or die;
jimport('joomla.plugin.plugin');
/**
* Joomla Authentication plugin
*
* #package Joomla.Plugin
* #subpackage Authentication.Webservice
* #since 1.5
*/
class plgAuthenticationWebservice extends JPlugin
{
/**
* This method should handle any authentication and report back to the subject
*
* #access public
* #param array Array holding the user credentials
* #param array Array of extra options
* #param object Authentication response object
* #return boolean
* #since 1.5
*/
function onUserAuthenticate($credentials, $options, &$response)
{
jimport('joomla.user.helper');
$response->type = 'Webservice';
// Joomla does not like blank passwords
if (empty($credentials['password'])) {
$response->status = JAUTHENTICATE_STATUS_FAILURE;
$response->error_message = JText::_('JGLOBAL_AUTH_EMPTY_PASS_NOT_ALLOWED');
return false;
}
// Initialise variables.
$conditions = '';
// Get a database object
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('id, password');
$query->from('#__users');
$query->where('username=' . $db->Quote($credentials['username']));
$db->setQuery($query);
$result = $db->loadObject();
if ($result) {
$parts = explode(':', $result->password);
$crypt = $parts[0];
$salt = #$parts[1];
$testcrypt = JUserHelper::getCryptedPassword($credentials['password'], $salt);
if ($crypt == $testcrypt) {
$user = JUser::getInstance($result->id); // Bring this in line with the rest of the system
$response->email = $user->email;
$response->fullname = $user->name;
if (JFactory::getApplication()->isAdmin()) {
$response->language = $user->getParam('admin_language');
}
else {
$response->language = $user->getParam('language');
}
$response->status = JAUTHENTICATE_STATUS_SUCCESS;
$response->error_message = '';
} else {
$response->status = JAUTHENTICATE_STATUS_FAILURE;
$response->error_message = JText::_('JGLOBAL_AUTH_INVALID_PASS');
}
} else {
$response->status = JAUTHENTICATE_STATUS_FAILURE;
$response->error_message = JText::_('JGLOBAL_AUTH_NO_USER');
}
}
}
I added one more file to my plugin to access the authentication, I called it test_auth.php and it goes like this:
<?php
define('_JEXEC', 1 );
define('JPATH_BASE', 'C:\xampp\htdocs\joomla');
define( 'DS', DIRECTORY_SEPARATOR );
require_once ( JPATH_BASE .DS.'includes'.DS.'defines.php' );
require_once ( JPATH_BASE .DS.'includes'.DS.'framework.php' );
include("Webservice.php");
$credentials = array(
'username' => 'test',
'password' => 'test');
$options = array();
$response = array();
$auth = new plgAuthenticationWebservice();
$auth->onUserAuthenticate($credentials, $options, &$response);
var_dump($response);
But when I call it, it get these errors:
Warning: Missing argument 1 for JPlugin::__construct(), called in
C:\xampp\htdocs\joomla\plugins\authentication\Webservice\test_auth.php
on line 25 and defined in
C:\xampp\htdocs\joomla\libraries\joomla\plugin\plugin.php on line 57
Fatal error: Call to a member function attach() on a non-object in
C:\xampp\htdocs\joomla\libraries\joomla\base\observer.php on line 41
What am I doing wrong?
I think I could place all php scripts outside and independent from joomla and work with require_once(JPATH_BASE .DS.'includes'.DS.'defines.php') etc.
Or I could write a plugin, install it with the extension manager and won't struggle with an unavailable joomla framework. But in fact it won't work if I leave out defines.php and framework.php.
I think a guide for plugin creation in Joomla 1.7 would be helpful.
OK, i completely dropped my first try.
Instead I use JOOMLA_ROOT/libraries/joomla/user/authentication.php now (insprired by JOOMLA_ROOT/libraries/joomla/application/application.php).
My test_auth.php looks like this now:
<?php
define('_JEXEC', 1 );
define('DS', DIRECTORY_SEPARATOR);
define('JPATH_BASE', dirname(__FILE__) . DS . '..' . DS . '..' . DS . '..'); // assuming we are in the authorisation plugin folder and need to go up 3 steps to get to the Joomla root
require_once (JPATH_BASE .DS. 'includes' .DS. 'defines.php');
require_once (JPATH_BASE .DS. 'includes' .DS. 'framework.php');
require_once (JPATH_BASE .DS. 'libraries' .DS. 'joomla'. DS. 'user' .DS. 'authentication.php');
$mainframe =& JFactory::getApplication('site');
$mainframe->initialise();
$credentials = array(
'username' => 'test',
'password' => 'test');
$options = array();
$authenticate = JAuthentication::getInstance();
$response = $authenticate->authenticate($credentials, $options);
if ($response->status === JAUTHENTICATE_STATUS_SUCCESS) {
echo('<br />It works<br />');
}
var_dump($response);
For any improvements I would be deeply grateful!
EDIT: I dismissed the plugin installation. It is a simple external script, which wouldn't be called from Joomla itself. I simply moved it to a new folder in the Joomla root.

Resources