Get URL avatar of a specific person Mybb - mybb

I would like to get the url of the avatar of a member having only the nickname.
Thank you for your help.

if($mybb->user['username'] == $username)
{
$avatar = $mybb->user['avatar'];
}
else
{
$query = $db->simple_select('users', 'avatar', "username = ".$db->escape_string($username)."'", array('LIMIT' => 1));
$avatar = $db->fetch_field($query, 'avatar');
}
Where $username is the username of the user and the returned $avatar is the URL of the avatar.
Or, by using the inbuilt function:
if($mybb->user['username'] == $username)
{
$avatar = $mybb->user['avatar'];
}
elseif(get_user_by_username($username, array('exists' => true)) !== False)
{
$user = get_user_by_username($username, array('fields' => array('avatar'))); // Add other fields you want to the fields array.
$avatar = $user['avatar'];
}
else
{
error('Invalid user');
}
Also post at the MyBB Community Forums as that is where the MyBB Group provide official support.

Related

How to post Integer in Alamofire Parameters

i followed a tutorial for Register and Login Request in xcode.
But i have a problem with the Code because i changed some values of it.
My variables in the php script are ssiss (string, string, int, string, string). In the swift file i am using Alamofire. Here it is:
#IBAction func buttonRegister(_ sender: UIButton) {
let ageINT = Int(ageTF.text!);
//creating parameters for the post request
let parameters: Parameters=[
"name":nameTF.text!,
"username":usernameTF.text!,
"age": ageINT ?? 0,
"country":countryTF.text!,
"password":passwordTF.text!,
]
//Sending http post request
Alamofire.request(URL_USER_REGISTER, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: nil).responseJSON
{
response in
//printing response
print(response)
//getting the json value from the server
if let result = response.result.value {
//converting it as NSDictionary
let jsonData = result as! NSDictionary
//displaying the message in label
self.labelMessage.text = jsonData.value(forKey: "message") as! String?
}
}
I think the problem is i pass an String value instead of a integer value. That is why i already have changed the value for "age" from "age":ageTF.text!, to "age": ageINT ?? 0,
The error i am get is "Required parameters are missing".
I am getting this "error-response" message because of this php-script:
<?php
//importing required script
require_once '../includes/DbOperation.php';
$response = array();
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (!verifyRequiredParams(array('name', 'username', 'age', 'country', 'password'))) {
//getting values
$name = $_POST["name"];
$username = $_POST["username"];
$age = $_POST["age"];
$country = $_POST["country"];
$password = $_POST["password"];
//creating db operation object
$db = new DbOperation();
//adding user to database
$result = $db->createUser($name, $username, $age, $country, $password);
//making the response accordingly
if ($result == USER_CREATED) {
$response['error'] = false;
$response['message'] = 'User created successfully';
} elseif ($result == USER_ALREADY_EXIST) {
$response['error'] = true;
$response['message'] = 'User already exist';
} elseif ($result == USER_NOT_CREATED) {
$response['error'] = true;
$response['message'] = 'Some error occurred';
}
} else {
$response['error'] = true;
$response['message'] = 'Required parameters are missing';
}
} else {
$response['error'] = true;
$response['message'] = 'Invalid request';
}
//function to validate the required parameter in request
function verifyRequiredParams($required_fields)
{
//Getting the request parameters
$request_params = $_REQUEST;
//Looping through all the parameters
foreach ($required_fields as $field) {
//if any requred parameter is missing
if (!isset($request_params[$field]) || strlen(trim($request_params[$field])) <= 0) {
//returning true;
return true;
}
}
return false;
}
print_r(json_encode($response));
?>
And this is the other php script:
<?php
class DbOperation
{
private $conn;
//Constructor
function __construct()
{
require_once dirname(__FILE__) . '/Constants.php';
require_once dirname(__FILE__) . '/DbConnect.php';
// opening db connection
$db = new DbConnect();
$this->conn = $db->connect();
}
//Function to create a new user
public function createUser($name, $username, $age, $country, $password)
{
if (!$this->isUserExist($username)) {
$password = md5($pass);
$stmt = $this->conn->prepare("INSERT INTO user (name, username, age, country, password) VALUES (?, ?, ?, ?, ?)");
$stmt->bind_param("ssiss", $name, $username, $age, $country, $password);
if ($stmt->execute()) {
return USER_CREATED;
} else {
return USER_NOT_CREATED;
}
} else {
return USER_ALREADY_EXIST;
}
}
private function isUserExist($username)
{
$stmt = $this->conn->prepare("SELECT id FROM user WHERE username = ? ");
$stmt->bind_param("s", $username);
$stmt->execute();
$stmt->store_result();
return $stmt->num_rows > 0;
}
}

Laravel 5.6 Error NotFoundHttpException in RouteCollection.php (line 179)

I try login facebook it's error NotFoundHttpException in RouteCollection.php (line 179)
I using Laravel 5.6
public function facebookAuthRedirect()
{
return Socialite::with('facebook')->redirect();
}
if facebook login success it's Redirect to facebook
public function facebookSuccess()
{
$provider = Socialite::with('facebook');
if (Input::has('code')){
$user = $provider->stateless()->user();
//dd($user); // print value debug.
$email = $user->email;
$name = $user->name;
$password = substr($user->token,0,10);
$facebook_id = $user->id;
//เช็คว่า email เป็น null หรือไม่
if($email == null){ // case permission is not email public.
$user = $this->checkExistUserByFacebookId($facebook_id);
if($user == null){
$email = $facebook_id;
}
}
else
{
$user = $this->checkExistUserByEmail($email);
if($user != null){
if($user->facebook_id == ""){ // update account when not have facebook id.
$user->facebook_id = $facebook_id;
$user->save();
}
}
}
if($user!=null){ // Auth exist account.
Auth::login($user);
return redirect('index/');
}
else{ // new Account.
$user = $this->registerUser($email,$name,$password,$facebook_id);
Auth::login($user);
return redirect('index/');
}
}
return redirect('/');
}
Check Email and facebook
private function checkExistUserByEmail($email)
{
$user = \App\User::where('email','=',$email)->first();
return $user;
}
private function checkExistUserByFacebookId($facebook_id)
{
$user = \App\User::where('facebook_id','=',$facebook_id)->first();
return $user;
}
Member Register
private function registerUser($email,$name,$password,$facebook_id)
{
$user = new \App\User;
$user->email = $email;
$user->name = $name;
$user->password = Hash::make($password); // Hash::make
$user->balance = 0;
$user->level = "member";
$user->facebook_id = $facebook_id;
$user->save();
return $user;
}
M Route file web.php
Route::get('login/facebook', 'Auth\LoginController#facebookAuthRedirect');
Route::get('login/facebook/callback', 'Auth\LoginController#facebookSuccess');
Clear route cache:
php artisan route:cache
and then check results

Compare the token from an email to a user's token for account activation

I need to send a user an email with a link that they can click on to activate their account. Here is my code:
//ADD METHOD FROM USERS CONTROLLER, THIS SENDS THE EMAIL WHEN A NEW USER IS ADDED
public function add()
{
$user = $this->Users->newEntity();
if ($this->request->is('post')) {
$user = $this->Users->patchEntity($user, $this->request->data);
$newAuthToken = bin2hex(openssl_random_pseudo_bytes(16));
$user['authtoken'] = $newAuthToken;
$user['activated'] = null;
if ($this->Users->save($user)) {
$this->Flash->success(__('The user has been saved.'));
$ms='Click on the link below to complete registration ';
$ms.='urlhere.com/users/activate/t:'.$newAuthToken.'';
$ms=wordwrap($ms,70);
$email = new Email('default');
$email->viewVars();
$email->template('default')->viewVars(array('user' => $user))
->emailFormat('html')
->to($user['email'])
->from('admin#example.com')
->subject('Hello ' . $user['email'])
->send($ms);
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The user could not be saved. Please, try again.'));
}
}
$groups = $this->Users->Groups->find('list', ['limit' => 200]);
$answers = $this->Users->Answers->find('list', ['limit' => 200]);
$courses = $this->Users->Courses->find('list', ['limit' => 200]);
$this->set(compact('user', 'groups', 'answers', 'courses'));
$this->set('_serialize', ['user']);
}
Here is the function that should compare the email token(from the link) with the tokens in the Users table and set the timestamp to Activated if they match:
//ACTIVATE FUNCTION FROM USERS CONTROLLER, SHOULD SET TIMESTAMP FOR ACTIVATED
public function activate($id = null)
{
if (!empty($this->passedArgs['t'])){
$tokenhash = $this->passedArgs['t'];
$results = $this->User->find('first', array('conditions' => array('authtoken' => $tokenhash)));
if($results['authtoken']==$tokenhash) {
$this->User->id = $results['id'];
$this->User->saveField('activated', current_datetime());
$this->Flash->success(__('The user has been saved.'));
return $this->redirect(['action' => 'index']);
exit;
} else {
$this->Flash->error('Tokens do not match');
return $this->redirect(['action' => 'index']);
}
}
}
Any ideas as to why this isn't working?

set user id based on pk when logged in through facebook

I am able to login/logout on my web app using facebook. But the problem is when the user needs to update his profile on my application, he can't. It would say that he is restricted to view his own page. The only way for this to happen is that user identity is probably not set. But I am not sure how to correct this. When I tried Yii::app()->user->user_id the Id is actually correct id, which is the pk in user model. So how is it that he cannot get to update his own page?
in my facebookUserIdentity:
public function authenticate()
{
if($this->getIsAccessTokenValid() && $this->setFBUser())
{
$this->_user = $this->getUserFromDatabase();
if($this->_user === false)
return false;
$this->setState('isUser', false);
$this->setState('isAdmin', false);
$this->setState('isShop', false);
$this->setState('isSuper', false);
$this->setState('user',$this->_user);
$this->_id = $this->_FBUser['id'];
//I've tried doing something like $this->_id = Yii::app()->user->user_id; or like $this->_user->user_id; ?
$this->_name = $this->_FBUser['name'];
return true;
}
else {
return false;
}
}
getting user from db:
protected function getUserFromDatabase()
{
$FBUser = $this->_FBUser;
if($FBUser)
{
$user = User::model()->findByAttributes (array('oauth_uid'=>$FBUser['id']));
if(!$user)
{
$user = new User;
$user->oauth_uid = $FBUser['id'];
$user->username = $FBUser['id'];
$user->first_name = $FBUser['first_name'];
//other info etc
$user->image = "https://graph.facebook.com/" . $FBUser['id'] . "/picture?type=large";
}
else
{
if ($user->oauth_permission == 'n')
{
$this->errorMessage = self::ERROR_LOGIN_DISABLE;
return false;
}
$user->last_login_date = date('Y-m-d H:i:s');
}
if($user->save())
{
return $user;
}
else
$this->errorMessage = CJSON::encode ( $user->getErrors());
return false;
}
else {
$this->errorMessage = "Failed getting facebook user data";
return false;
}
}
and lastly, the controller page rules:
public function accessRules()
{
$params=array();
$id=Yii::app()->request->getParam('id');
$params['model']=$this->loadModel($id);
return array(
//stuff
array('allow', // allow authenticated user to perform 'create' and 'update' actions
'actions'=>array('create','update','RemoveImage'),
'roles'=>array('admin','super','owner'=>$params),
),
//stuff

Magento and salesforce integration to create opportunity as closed won inside salesfore once order become complete in magento store

I had implemented a salesforce integration with magento orders. To achieve this , i had followed the steps given below. I am doing something wrong in 4th step while inserting salesforce_company_id and salesforce_contact_id in user account.
1)Add custom option 'closed' in admin to make any order complete.
public function massCompleteAction(){
$orderIds = $this->getRequest()->getPost('order_ids', array());
$countCompleteOrder = 0;
foreach ($orderIds as $orderId) {
$order = Mage::getModel('sales/order')->load($orderId);
if ($order->canComplete()) {
$order->complete()->save();
$countCompleteOrder++;
}
}
if ($countCompleteOrder>0) {
$this->_getSession()->addSuccess($this->__('%s order(s) successfully put on complete', $countCompleteOrder));
}else {
// selected orders is not available for hold
}
$this->_redirect('*/*/');
}
2)Add two additional fields for user account, Salesforce Company and Salesforce Contact.
I had followed following link http://www.excellencemagentoblog.com/customer-registration-fields-magento1-6
3)Create a custom reseller registration form that will create a simple user in magento
public function createResellerAction()
{
$params = $this->getRequest()->getParams();
$customer = Mage::getModel('customer/customer');
$password = $params["password"];
$email = $params["email"];
$customer->setWebsiteId(Mage::app()->getWebsite()->getId());
$customer->loadByEmail($email);
//Zend_Debug::dump($customer->debug()); exit;
if(!$customer->getId()) {
$customer->setEmail($email);
$customer->setFirstname($params["firstname"]);
$customer->setLastname($params["lastname"]);
$customer->setPassword($password);
try {
$customer->save();
$customer->setConfirmation(null);
$customer->save();
Mage::getSingleton('customer/session')->loginById($customer->getId());
}
catch (Exception $ex) {
//Zend_Debug::dump($ex->getMessage());
}
$_custom_address = array (
'firstname' => $params["firstname"],
'lastname' => $params["lastname"],
'street' => array (
'0' => $params["add1"],
'1' => $params["add2"],
),
'city' => $params["city"],
'region_id' => '',
'region' => '',
'postcode' => $params["zipcode"],
'country_id' => '', /* Croatia */
'telephone' => $params["phone"],
);
$customAddress = Mage::getModel('customer/address');
$customAddress->setData($_custom_address)
->setCustomerId($customer->getId())
->setIsDefaultBilling('1')
->setIsDefaultShipping('1')
->setSaveInAddressBook('1');
try {
$customAddress->save();
}
catch (Exception $ex) {
//Zend_Debug::dump($ex->getMessage());
}
4) Create company and contact in salesforce during reseller action
$sObject1 = new stdclass();
$sObject1->Name = $params["company"];
$createResponse1 = $mySforceConnection->create(array($sObject1), 'Account');
foreach ($createResponse1 as $createResult1) {
$compid = $createResult1->id;
}
$sObject3 = new stdclass();
$sObject3->FirstName = $params["firstname"];
$sObject3->LastName = $params["lastname"];
$sObject3->Email = $params["email"];
$sObject3->AccountId = $compid;
$createResponse2 = $mySforceConnection->create(array($sObject3), 'Contact');
foreach ($createResponse2 as $createResult2) {
$contid = $createResult2->id;
}
$saledata = array (
'salesforce_company_id' => $compid,
'salesforce_contact_id' => $contid,
);
$customersale = Mage::getModel('customer/customer');
$customersale->setWebsiteId(Mage::app()->getWebsite()->getId());
$customersale->loadByEmail($email);
//Zend_Debug::dump($customer->debug()); exit;
if($customersale->getId()) {
$customersale->setData($saledata);
try {
$customersale->save();
$customersale->setConfirmation(null);
$customersale->save();
}
catch (Exception $ex) {
$message = $this->__($customer);
//Zend_Debug::dump($ex->getMessage());
Mage::getSingleton('core/session')->addError($message);
}
}
Please check the code where i am wrong at the bottem of 4th step
$saledata = array (
'salesforce_company_id' => $compid,
'salesforce_contact_id' => $contid,
);
$customersale = Mage::getModel('customer/customer');
$customersale->setWebsiteId(Mage::app()->getWebsite()->getId());
$customersale->loadByEmail($email);
//Zend_Debug::dump($customer->debug()); exit;
if($customersale->getId()) {
$customersale->setData($saledata);
try {
$customersale->save();
$customersale->setConfirmation(null);
$customersale->save();
}
catch (Exception $ex) {
$message = $this->__($customer);
//Zend_Debug::dump($ex->getMessage());
Mage::getSingleton('core/session')->addError($message);
}
}
I await your responses.
There is a great extension for magento which does that all for you and even more: https://products.crunchyconsulting.com/crunchy-products/crunchy-magforce.html
Take a look at help & docs tab where you can find even movies with use case scenarios
https://www.youtube.com/watch?v=TjxvjGcAGqY
https://www.youtube.com/watch?v=cmf4Ksv3uRM