joomla 1.7 user registration customization issue - php

-> i am trying for new user registration customization.
-> for that i create form and hidden variable through call function from controller.
-> in controller save function i write this code but some inner function which not work in 1.7 so create problem here.
function register_save()
{
global $mainframe;
$db =& JFactory::getDBO();
// Check for request forgeries
JRequest::checkToken() or jexit( 'Invalid Token' );
//clean request
$post = JRequest::get( 'post' );
$post['username'] = JRequest::getVar('username', '', 'post', 'username');
$post['password'] = JRequest::getVar('password', '', 'post', 'string', JREQUEST_ALLOWRAW);
$post['password2'] = JRequest::getVar('password2', '', 'post', 'string', JREQUEST_ALLOWRAW);
// get the redirect
$return = JURI::base();
// do a password safety check
if(strlen($post['password']) || strlen($post['password2'])) { // so that "0" can be used as password e.g.
if($post['password'] != $post['password2']) {
$msg = JText::_('PASSWORD NOT MATCH');
// something is wrong. we are redirecting back to edit form.
// TODO: HTTP_REFERER should be replaced with a base64 encoded form field in a later release
$return = str_replace(array('"', '<', '>', "'"), '', #$_SERVER['HTTP_REFERER']);
if (empty($return) || !JURI::isInternal($return)) {
$return = JURI::base();
}
$this->setRedirect($return, $msg, 'error');
return false;
}
}
// Get required system objects
$user = clone(JFactory::getUser());
$pathway = JFactory::getApplication();
//$pathway =& $mainframe->getPathway();
$config =& JFactory::getConfig();
//print_r($config)."<br>";
$authorize =& JFactory::getACL();
//print_r($authorize)."<br>"; /// some mistake here
$newUsertype = 'Registered';
// Bind the post array to the user object
if (!$user->bind( JRequest::get('post'), 'usertype' )) {
JError::raiseError( 500, $user->getError());
}
// Set some initial user values
$user->set('id', 0);
$user->set('usertype', $newUsertype);
$user->set('gid', $authorize->get_group_id( '', $newUsertype, 'ARO' ));
$date =& JFactory::getDate();
$user->set('registerDate', $date->toMySQL());
// If user activation is turned on, we need to set the activation information
jimport('joomla.user.helper');
$user->set('activation', JUtility::getHash( JUserHelper::genRandomPassword()) );
$user->set('block', '1');
// If there was an error with registration, set the message and display form
if ( !$user->save() )
{
JError::raiseWarning('', JText::_( $user->getError()));
$this->register();
return false;
}
$obj1 = new stdClass();
$obj1->userid = $user->id;
$obj1->points = 0;
$obj1->posted_on = $date->toMySQL();
$obj1->avatar = '';
$obj1->thumb = '';
$obj1->params = 'notifyEmailSystem=1
privacyProfileView=0
privacyPhotoView=0
privacyFriendsView=0
privacyVideoView=1
notifyEmailMessage=1
notifyEmailApps=1
notifyWallComment=0';
$db->insertObject('#__community_users', $obj1, 'userid');
$extra_field = array(1=>2,2=>3,3=>4,4=>6,5=>7,6=>8,7=>9,8=>10,9=>11,10=>12,11=>14,12=>15,13=>16);
$i = 1;
$obj2 = new stdClass();
while($extra_field[$i] != "")
{
$obj2->id = '';
$obj2->user_id = $user->id;
$obj2->field_id = $extra_field[$i];
$obj2->value = '';
$db->insertObject('#__community_fields_values', $obj2, 'id');
$i++;
}
////////// end of joomsocial customisation///////////////////////////
// Send registration confirmation mail
$password = JRequest::getString('password', '', 'post', JREQUEST_ALLOWRAW);
$password = preg_replace('/[\x00-\x1F\x7F]/', '', $password); //Disallow control chars in the email
UserControllerRegister::_sendMail($user, $password);
// Everything went fine, set relevant message depending upon user activation state and display message
$message = JText::_( 'Your account has been created and an activation link has been sent to the e-mail address you entered. Note that you must activate the account by clicking on the activation link when you get the e-mail before you can login.' );
$this->setRedirect('index.php', $message);
}
not insert record in table.
please help me.

I think you're right:
Joomla 1.5 ACL (Access Control Lists) is hierarchical: each user group inherits permissions from the groups below it.
In Joomla 1.7 ACL is not necessarily hierarchical. You can setup groups with whatever permissions you wish.
The difference between the ACL in Joomla 1.5 and 1.7 is not only in the behavior - but also in the implementation! which means that the authentication/registration mechanism will be implemented in different ways:
http://www.youtube.com/watch?v=ZArgffnPUo4

Related

Wordpress Admin Login programmatically

Im trying to create a small widget that gets the authenticated user from the actual web app, which is in python/django(hosted on example.com), and sets headers across subdomains(*.example.com). The users. The users logged in on example.com should be able to use WordPress(hosted on blog.example.com) without again having to register/login to wordpress.
Here I am trying to autologin(without password for WordPress) those users on WordPress so they can write blogs.
I have written a small shortcode that does the above thing. Though the user is logged in, the /wp-admin still redirects to the login page. Below is the shortcode I wrote:
<?php
echo "STARTED";
$url = "https://app.example.com/api/user_profile/?my=1";
$arguments = array(
'method' => 'GET',
'cookies' => $_COOKIE
);
$response = wp_remote_get($url, $arguments );
if ( !is_wp_error( $response ) ) {
$body = wp_remote_retrieve_body( $response );
$data = json_decode( $body );
$final_user = array();
$userID;
$email;
$username;
foreach ( $data as $datapoint ) {
$email = $datapoint->email;
$username = $datapoint->username;
}
$user_exists = get_user_by("email", $datapoint->email);
if (!$user_exists){
$user_info = array();
$new_user_id = wp_create_user($datapoint->username, $datapoint->username, $datapoint->email);
$final_user = get_user_by("id", $new_user_id);
} else {
$final_user = $user_exists;
}
// Login the user now
foreach ( $final_user as $fuser ) {
$userID = $final_user->ID;
}
echo "<br/>uerID - ";
echo $userID;
$user = get_user_by("login",$username);
wp_set_current_user($user->ID);
wp_set_auth_cookie($user->ID);
do_action( 'wp_login', $user->username, $user );
echo "<br/> inside done";
} else {
echo "Something went wrong";
}
echo "<br/>-----------done"
?>
Im not sure what is wrong with the above code. I want the user to access /wp-admin so they can write posts if they are loggedin on our webapp. We are making an API request to our web app from our wordpress(protected private API for our use only) to get authenticated users on our app.
This is the first time wrote PHP code, so it's not production ready (will write the optimal code later).
Any help would be very appreciated. Please do let me know if there is anything more I need to provide.

How have logged in user's email using oauth in PHP

I used yahoo oauth in my website. In code below that I found on github, for example $user -> query -> results -> profile -> givenName returns the first name of logged in user, $user -> query -> results -> profile -> familyName and so on.
I searched a lot but still I don't know how to get user's email address.
This is my code :
require('include/http.php');
require('include/oauth_client.php');
$client = new oauth_client_class;
$client->debug = false;
$client->debug_http = true;
$client->server = 'Yahoo';
$client->redirect_uri = 'http://www.example.com';
$client->client_id = '';
$application_line = __LINE__;
$client->client_secret = '';
if(($success = $client->Initialize()))
{
if(($success = $client->Process()))
{
if(strlen($client->access_token))
{
$success = $client->CallAPI(
'https://query.yahooapis.com/v1/yql',
'GET', array(
'q'=>'select * from social.profile where guid=me',
'format'=>'json'
), array('FailOnAccessError'=>true), $user);
}
}
$success = $client->Finalize($success);
}
if($client->exit)
exit;
if(strlen($client->authorization_error))
{
$client->error = $client->authorization_error;
$success = false;
}
if($success)
{
$yahname =$user->query->results->profile->givenName.$user->query->results->profile->familyName;
echo '<pre>', HtmlSpecialChars(print_r($user, 1)), '</pre>';
}
else
{
echo HtmlSpecialChars($client->error);
}
Please let me know if I am doing anything wrong.
I do not believe that the profile contains the users email address (it is not listed in the Yahoo profile docs). If you have requested the sdpp-w scope the the id token you get when exchanging an authorization code for an access token contains the email address of the user under the key email.

Twitter OAuth returning blank array if there is no tweet

I spent my last 5 hours in this issue and finally I came here for the solution.
I am doing log-in using twitter functionality in my site (Zend Framework + PHP) and everything is working fine. But I am facing the following issue in it:
If the user has no tweets (0 tweets) in his account then the
$tweets = json_decode($response->getBody());
echo "<pre>";
print_r($tweets);
exit;
Its showing me blank array. i.e. : Array(); :-(
And if I am adding some tweets there in twitter account then its showing me the complete array along with user information like display name, image, etc...like this:
Array
(
//other data
[0] => stdClass Object
(
[user] => stdClass Object
....
....
so on..
)
)
Following is my code :
public function twitterregisterAction() {
$path = realpath(APPLICATION_PATH . '/../library/');
set_include_path($path);
session_start();
require $path . "/Zend/Oauth/Consumer.php";
$config = array(
"callbackUrl" => "http://" . $_SERVER['HTTP_HOST'] . "/register/twittercallback",
"siteUrl" => "http://twitter.com/oauth",
"consumerKey" => "xxxxxxxxxxxxx",
"consumerSecret" => "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
);
$consumer = new Zend_Oauth_Consumer($config);
// fetch a request token
$token = $consumer->getRequestToken();
// persist the token to storage
$_SESSION["TWITTER_REQUEST_TOKEN"] = serialize($token);
// redirect the user
$consumer->redirect();
}
/*
* Ticket id #16
* twittercallbackAction method
*/
public function twittercallbackAction() {
$config = array(
"callbackUrl" => "http://" . $_SERVER['HTTP_HOST'] . "/register/twittercallback",
"siteUrl" => "http://twitter.com/oauth",
"consumerKey" => "xxxxxxxxxxxxxxxxxx",
"consumerSecret" => "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
);
$consumer = new Zend_Oauth_Consumer($config);
if (!$this->_getParam("denied")) {
if (!empty($_GET) && isset($_SESSION['TWITTER_REQUEST_TOKEN'])) {
$token = $consumer->getAccessToken($_GET, unserialize($_SESSION['TWITTER_REQUEST_TOKEN']));
} else {
// Mistaken request? Some malfeasant trying something?
exit('Invalid callback request. Oops. Sorry.');
}
// save token to file
// file_put_contents('token.txt', serialize($token));
$client = $token->getHttpClient($config);
$client->setUri('https://api.twitter.com/1/statuses/user_timeline.json?');
$client->setMethod(Zend_Http_Client::GET);
$client->setParameterGet('name');
$client->setParameterGet('profile_image_url');
$response = $client->request();
$tweets = json_decode($response->getBody());
$session = new Zend_Session_Namespace("userIdentity");
Zend_Session::rememberMe(63072000); //2years
$session->tw_id = $tweets[0]->user->id;
$session->tw_name = $tweets[0]->user->name;
$session->tw_image = $tweets[0]->user->profile_image_url;
if ($session->tw_id != "") {
$tw_id = $session->tw_id;
//Calling the function twitterAuthAction for email authentication
$twAuthArr = $this->twitterAuthAction($tw_id);
if ($twAuthArr['socialId'] == $tw_id) {
$session->userId = $twAuthArr['id'];
$session->email = $twAuthArr['emailId'];
$this->_redirect('/profile/showprofile');
} else {
$user = new UserRegistration();
$firstname = "";
$lastname = "";
$password = "";
$socialtype = "twitter";
$email = "";
$socialid = $session->tw_id;
$result = $user->registerUser($firstname, $lastname, $socialid, $socialtype, $email, $password);
$session->userId = $result;
$this->_redirect('/register');
}
}
$this->_redirect("/register");
} else {
$this->_redirect("/register");
}
}
My Questions are :
1) Why its not providing user array if there is no any tweet in my twitter account (or newly created twitter account)
2) I want user profile details from twitter account. How can I get it?
Need Help. Thanks
I think as per david's answer you need to use users/show url there instead of using statuses/user_timeline. You can use curl for requesting url so you'll get the response which contains the users information.
Try with following code:
$user_id = $client->getToken()->getParam('user_id');
$trends_url = "http://api.twitter.com/1/users/show.json?user_id=".$user_id;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $trends_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$curlout = curl_exec($ch);
curl_close($ch);
$response = json_decode($curlout, true);
$session = new Zend_Session_Namespace("userIdentity");
Zend_Session::rememberMe(63072000); //2years
$session->tw_id = $response['id'];
$session->tw_name = $response['name'];
$session->tw_image = $response['profile_image_url'];
Try this. Hope it will help you.
I think you are misreading the Twitter API docs for the statuses/user_timeline endpoint.
The field user that you identify is one of the fields within a returned tweet. If the user id to which you point has no tweets, then there will be no entries in the returned array, hence no user field.
If you need the user information even in the absence of any tweets, then you probably need to hit the users/show endpoint.

Posting to Twitter from any page after login/approval with PHP

Users on my website can login to Twitter and post their status on my website and twitter at once. I'm using https://github.com/abraham/twitteroauth to connect to Twitter. Login and posting is performed on different pages of website.
This is login script:
public function loginTwitter() {
$twitter = new TwitterOAuth(
$this->getContext()->params['social']['twitter']['consumerKey'],
$this->getContext()->params['social']['twitter']['consumerSecret']
);
$request_token = $twitter->getRequestToken($this->link('//User:connectFromTwitter'));
// Saving to session (Nette Framework)
$twitterSession = $this->getContext()->session->getSection('twSes');
$twitterSession->oauth_request_token = $token = $request_token['oauth_token'];
$twitterSession->oauth_request_token_secret = $request_token['oauth_token_secret'];
if ($twitter->http_code == 200) {
$requestLink = $twitter->getAuthorizeURL($token);
$this->redirectUrl($requestLink);
} else {
echo 'Error';
}
}
This is callback script (posting works right after user has been logged in):
public function twitterOauth() {
// $_GET parameter oauth_verifier
$oauthVerifier = $this->getParam('oauth_verifier');
// Session section
$twitterSession = $this->getContext()->session->getSection('twSes');
$twitter = new TwitterOAuth(
$this->getContext()->params['social']['twitter']['consumerKey'],
$this->getContext()->params['social']['twitter']['consumerSecret'],
$twitterSession->oauth_request_token,
$twitterSession->oauth_request_token_secret
);
$access_token = $twitter->getAccessToken($oauthVerifier);
$twitterSession->access_token = $access_token;
$user_info = $twitter->get('account/verify_credentials');
// Saving to DB to be able to post without login
$tm = new TwitterUserManager();
if (!$tm->isInDatabase($this->getUser()->getId())) {
$tu = new TwitterUser();
$tu->setUser($this->loggedUser);
$tu->setOauthProvider('twitter');
$tu->setOauthUid("'".$user_info->id."'");
$tu->setUsername("'".$user_info->screen_name."'");
$tu->setOauthToken("'".$access_token['oauth_token']."'"); // Saving the access token for further posting
$tu->setOauthSecret("'".$access_token['oauth_token_secret']."'");
$tm->persist($tu);
}
$twitter->post('statuses/update', array('status' => 'Hello ' . date('d.m.Y H:i:s'))); // <== HERE IT WORKS
$this->redirect('User:socialConnect'); // Redirect to another page
}
This is posting function (User posts from any page):
public function postToTwitter() {
$twitterSession = $this->getContext()->session->getSection('twitter');
$twitter = new TwitterOAuth(
$this->getContext()->params['social']['twitter']['consumerKey'],
$this->getContext()->params['social']['twitter']['consumerSecret'],
$twitterSession->access_token['oauth_token'],
$twitterSession->access_token['oauth_token_secret']
);
return $twitter->post('statuses/update', array('status' => 'Hello' . date('d.m.Y H:i:s')));
}
When I use posting function I get this error:
stdClass(2) {
request => "/1/statuses/update.json" (23)
error => "Could not authenticate you." (27)
}
Thanks for help in advance.
EDIT: Solution:
Use this to connect to Twitter (save all info into DB):
http://framework.zend.com/manual/1.12/en/zend.oauth.introduction.html
Use this to post from any page:
http://framework.zend.com/manual/1.12/en/zend.service.twitter.html
Nice example:
http://www.joeyrivera.com/2010/twitter-api-oauth-authentication-and-zend_oauth-tutorial/
I always used the Zend-Framework-Component: http://framework.zend.com/manual/1.12/en/zend.service.twitter.html
I think it's simple and I could confirm, that it works. You just have to read through the tutorial (see link above).

Joomla manual login with controller

I am developing a component for Joomla. It has integrations with popular social websites. I retrieve user information from database via given social profile. Then, I try to make this user login with the following code:
$fbuser = $facebook->api(
'/me',
'GET',
array(
'access_token' => $_SESSION['active']['access_token']
)
);
// Get a database object
$db =& JFactory::getDBO();
$query = "SELECT * FROM #__users WHERE email = '".$fbuser['email']."';";
$db->setQuery($query);
$row = $db->loadRow();
if(isset($row))
{
$app = JFactory::getApplication();
$user =& JUser::getInstance($row[0]);
$credentials = array();
$credentials['username'] = $user->get('username');
$credentials['password'] = $user->get('password'); // When I change this to related users plain password then it works
$options = array();
$options['remember'] = true;
$options['silent'] = true;
$app->login($credentials, $options);
}
else
{
return 'There is no account associated with facebook';
}
The problem is database return encoded password and this doesn't work. When I give decoded password to $credentials it works. What can be the problem?
One option is to create your own authentication plugin (quite simple task) that would log in any user with a specific password known only to you and the site.
Then you can supply that password along with known username.
For the sake of security, only allow that plugin to log in ordinary users, and not admins.
You need to MD5 hash the pwd (the way it's stored in the DB).
try this:
$salt = '19IQYkelXrqVH1Eht6PFOIZRe5T1SQHs';
$pwd = md5_hex($pwd . $salt) .":$salt";
$query = "select name,username,email,password from jos_users where password = $pwd;";
...
// --- login mamanam.com
$app = JFactory::getApplication();
$credentials = array();
$credentials['username'] = $username;
$credentials['password'] = $password;
$app->login($credentials);
Necessary parameters in array $credentials=array() for logon function Joomla! $app->login($credentials)
*Sorry my English is not so good

Categories