How to connect with OpenFire(xmpp) using RESTAPI plugin And PHP - php

I am using OpenFire to manage my xmpp server I want to add new users using a PHP, So I have installed RESETAPI Plugin to OpenFire to administrate with http request. I am using gidkom Project also. But getting a error
Parse error: syntax error, unexpected T_VARIABLE in C:\wamp\www\IM\registration.php on line 12
My code for registration.php is:
<?php
if(isset($_POST["User_Name"]) && isset($_POST["Name"]) )
{
$User_ID = $_POST["User_Name"];
$User_Name = $_POST["Name"];
$User_Email = $_POST["Email"];
include "Gidkom/OpenFireRestApi/OpenFireRestApi.php";
// Create the OpenfireUserservice object
$api = new Gidkom\OpenFireRestApi
// Set the required config parameters
$api->secret = "my keys";
$api->host = "domain.my.org";
$api->port = "9090"; // default 9090
// Optional parameters (showing default values)
$api->useSSL = false;
$api->plugin = "/plugins/restapi/v1"; // plugin
// Add a new user to OpenFire and add to a group
$result = $api->addUser($User_ID, 'Password', $User_Name, $User_Email, array('welcome'));
// Check result if command is succesful
if($result['status']) {
// Display result, and check if it's an error or correct response
echo 'Success: ';
echo $result['message'];
} else {
// Something went wrong, probably connection issues
echo 'Error: ';
echo $result['message'];
}
//Add to roster
$api->addToRoster('Administrator', 'admin');
}
else
{
echo 'Error: Something went wrong..... please go back ';
}
I want the page to add a new new user in the openfire and add admin to his roster.
Thanks !!!!

Semicolon is missing.
$api = new Gidkom\OpenFireRestApi\OpenFireRestApi;

The errors were caused because of an outdated version of PHP, YPdating PHP to latest version fixed it...

prerequirements: must to have composer.exe installed on your machine
from cmd.exe
go to your web root server(htdocs) then
go into your directory which contain the rest api sources
then from this cmd.exe(or create one batch)
c:/..../....> composer install
Remark: -this commnad(composer install) must to have in same directory the composer.json
-this command(composer install) will create one subdirectory "vendor" named
now into your index.php must insert on top, the following line:
<?php
include "vendor/autoload.php";
....
and continue your actual program
and is trully must to end the lines with ;
...
?

https://github.com/gnello/php-openfire-restapi
Easy Php REST API Client for the Openfire REST API Plugin which provides the ability to manage Openfire instance by sending an REST/HTTP request to the server
Please read documentation for further information on using this application.
Installation
composer require gnello/php-openfire-restapi
Authentication
There are two ways to authenticate:
Basic HTTP Authentication
$authenticationToken = new \Gnello\OpenFireRestAPI\AuthenticationToken('your_user', 'your_password');
Shared secret key
$authenticationToken = new \Gnello\OpenFireRestAPI\AuthenticationToken('your_secret_key');
Start
$api = new \Gnello\OpenFireRestAPI\API('your_host', 9090, $authenticationToken);
Users
//Add a new user
$properties = array('key1' => 'value1', 'key2' => 'value2');
$result = $api->Users()->createUser('Username', 'Password', 'Full Name', 'email#domain.com', $properties);
//Delete a user
$result = $api->Users()->deleteUser('Username');
//Ban a user
$result = $api->Users()->lockoutUser('Username');
//Unban a user
$result = $api->Users()->unlockUser('Username');
Open Link Fore more.

Related

PHP autoload.php not found

so this is my code:
<?php
echo 'hey1';
set_time_limit(0);
date_default_timezone_set('UTC');
echo 'hey2';
require __DIR__.'/../vendor/autoload.php';
echo 'hey3';
/////// CONFIG ///////
$username = 'NetsGets';
$password = 'NetsGetsWebsite';
$debug = true;
$truncatedDebug = false;
//////////////////////
$ig = new \InstagramAPI\Instagram($debug, $truncatedDebug);
try {
$ig->login($username, $password);
} catch (\Exception $e) {
echo 'Something went wrong: '.$e->getMessage()."\n";
exit(0);
}
try {
$feed = $ig->discover->getExploreFeed();
// Let's begin by looking at a beautiful debug output of what's available in
// the response! This is very helpful for figuring out what a response has!
$feed->printJson();
// Now let's look at what properties are supported on the $feed object. This
// works on ANY object from our library and will show what functions and
// properties are supported, as well as how to call the functions! :-)
$feed->printPropertyDescriptions();
// The getExploreFeed() has an "items" property, which we need. As we saw
// above, we should get it via "getItems()". The property list above told us
// that it will return an array of "Item" objects. Therefore it's an ARRAY!
$items = $feed->getItems();
// Let's get the media item from the first item of the explore-items array...!
$firstItem = $items[0]->getMedia();
// We can look at that item too, if we want to... Let's do it! Note that
// when we list supported properties, it shows everything supported by an
// "Item" object. But that DOESN'T mean that every property IS available!
// That's why you should always check the JSON to be sure that data exists!
$firstItem->printJson(); // Shows its actual JSON contents (available data).
$firstItem->printPropertyDescriptions(); // List of supported properties.
// Let's look specifically at its User object!
$firstItem->getUser()->printJson();
// Okay, so the username of the person who posted the media is easy... And
// as you can see, you can even chain multiple function calls in a row here
// to get to the data. However, be aware that sometimes Instagram responses
// have NULL values, so chaining is sometimes risky. But not in this case,
// since we know that "user" and its "username" are always available! :-)
$firstItem_username = $firstItem->getUser()->getUsername();
// Now let's get the "id" of the item too!
$firstItem_mediaId = $firstItem->getId();
// Finally, let's get the highest-quality image URL for the media item!
$firstItem_imageUrl = $firstItem->getImageVersions2()->getCandidates()[0]->getUrl();
// Output some statistics. Well done! :-)
echo 'There are '.count($items)." items.\n";
echo "The first item has media id: {$firstItem_mediaId}.\n";
echo "The first item was uploaded by: {$firstItem_username}.\n";
echo "The highest quality image URL is: {$firstItem_imageUrl}.\n";
} catch (\Exception $e) {
echo 'Something went wrong: '.$e->getMessage()."\n";
}
?>
After running this code, the only things that print are hey1 and hey2. Based on my own reasearch, I concluded that autoload.php is one of the necessery files for the composer to run, but it also seems to be the problem that stops the php from running. This code is from https://github.com/mgp25/Instagram-API. Pease help!
1) If you don't have Composer, install it. For example:
sudo apt-get install composer -y
2) Run:
composer require mgp25/instagram-php
3) Type:
cd vendor
ls
The very first file you see listed should be autoload.php.

Error while importing Quickbook library in Laravel 5.3

I am integrating quickbooks with my laravel app. After integration I got this error,
PHP Warning: require_once(../QuickBooks.php): failed to open stream:
No such file or directory in
/home/vipin/projects/development/Quickbook/config/app.php on line 2
PHP Fatal error: require_once(): Failed opening required '../QuickBooks.php'
(include_path='.:/usr/share/php:/home/ubuntu/projects/development/Quickbook/vendor/consolibyte/quickbooks')
in /home/ubuntu/projects/development/Quickbook/config/app.php on line
2
Here is my controller Quickbook.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
// require_once '../QuickBooks.php';
use App\Http\Requests;
class QuickBooksController extends Controller
{
private $IntuitAnywhere;
private $context;
private $realm;
public function __construct(){
if (!\QuickBooks_Utilities::initialized(env('QBO_DSN'))) {
// Initialize creates the neccessary database schema for queueing up requests and logging
\QuickBooks_Utilities::initialize(env('QBO_DSN'));
}
$this->IntuitAnywhere = new \QuickBooks_IPP_IntuitAnywhere(env('QBO_DSN'), env('QBO_ENCRYPTION_KEY'), env('QBO_OAUTH_CONSUMER_KEY'), env('QBO_CONSUMER_SECRET'), env('QBO_OAUTH_URL'), env('QBO_SUCCESS_URL'));
}
public function qboConnect(){
if ($this->IntuitAnywhere->check(env('QBO_USERNAME'), env('QBO_TENANT')) && $this->IntuitAnywhere->test(env('QBO_USERNAME'), env('QBO_TENANT'))) {
// Set up the IPP instance
$IPP = new \QuickBooks_IPP(env('QBO_DSN'));
// Get our OAuth credentials from the database
$creds = $this->IntuitAnywhere->load(env('QBO_USERNAME'), env('QBO_TENANT'));
// Tell the framework to load some data from the OAuth store
$IPP->authMode(
\QuickBooks_IPP::AUTHMODE_OAUTH,
env('QBO_USERNAME'),
$creds);
if (env('QBO_SANDBOX')) {
// Turn on sandbox mode/URLs
$IPP->sandbox(true);
}
// This is our current realm
$this->realm = $creds['qb_realm'];
// Load the OAuth information from the database
$this->context = $IPP->context();
return true;
} else {
return false;
}
}
public function qboOauth(){
if ($this->IntuitAnywhere->handle(env('QBO_USERNAME'), env('QBO_TENANT')))
{
; // The user has been connected, and will be redirected to QBO_SUCCESS_URL automatically.
}
else
{
// If this happens, something went wrong with the OAuth handshake
die('Oh no, something bad happened: ' . $this->IntuitAnywhere->errorNumber() . ': ' . $this->IntuitAnywhere->errorMessage());
}
}
public function qboSuccess(){
return view('qbo_success');
}
public function qboDisconnect(){
$this->IntuitAnywhere->disconnect(env('QBO_USERNAME'), env('QBO_TENANT'),true);
return redirect()->intended("/yourpath");// afer disconnect redirect where you want
}
public function createCustomer(){
$CustomerService = new \QuickBooks_IPP_Service_Customer();
$Customer = new \QuickBooks_IPP_Object_Customer();
$Customer->setTitle('Ms');
$Customer->setGivenName('Shannon');
$Customer->setMiddleName('B');
$Customer->setFamilyName('Palmer');
$Customer->setDisplayName('Shannon B Palmer ' . mt_rand(0, 1000));
// Terms (e.g. Net 30, etc.)
$Customer->setSalesTermRef(4);
// Phone #
$PrimaryPhone = new \QuickBooks_IPP_Object_PrimaryPhone();
$PrimaryPhone->setFreeFormNumber('860-532-0089');
$Customer->setPrimaryPhone($PrimaryPhone);
// Mobile #
$Mobile = new \QuickBooks_IPP_Object_Mobile();
$Mobile->setFreeFormNumber('860-532-0089');
$Customer->setMobile($Mobile);
// Fax #
$Fax = new \QuickBooks_IPP_Object_Fax();
$Fax->setFreeFormNumber('860-532-0089');
$Customer->setFax($Fax);
// Bill address
$BillAddr = new \QuickBooks_IPP_Object_BillAddr();
$BillAddr->setLine1('72 E Blue Grass Road');
$BillAddr->setLine2('Suite D');
$BillAddr->setCity('Mt Pleasant');
$BillAddr->setCountrySubDivisionCode('MI');
$BillAddr->setPostalCode('48858');
$Customer->setBillAddr($BillAddr);
// Email
$PrimaryEmailAddr = new \QuickBooks_IPP_Object_PrimaryEmailAddr();
$PrimaryEmailAddr->setAddress('support#consolibyte.com');
$Customer->setPrimaryEmailAddr($PrimaryEmailAddr);
if ($resp = $CustomerService->add($this->context, $this->realm, $Customer))
{
//print('Our new customer ID is: [' . $resp . '] (name "' . $Customer->getDisplayName() . '")');
//return $resp;
//echo $resp;exit;
//$resp = str_replace('{','',$resp);
//$resp = str_replace('}','',$resp);
//$resp = abs($resp);
return $this->getId($resp);
}
else
{
//echo 'Not Added qbo';
print($CustomerService->lastError($this->context));
}
}
public function addItem(){
$ItemService = new \QuickBooks_IPP_Service_Item();
$Item = new \QuickBooks_IPP_Object_Item();
$Item->setName('My Item');
$Item->setType('Inventory');
$Item->setIncomeAccountRef('53');
if ($resp = $ItemService->add($this->context, $this->realm, $Item))
{
return $this->getId($resp);
}
else
{
print($ItemService->lastError($this->context));
}
}
public function addInvoice($invoiceArray,$itemArray,$customerRef){
$InvoiceService = new \QuickBooks_IPP_Service_Invoice();
$Invoice = new \QuickBooks_IPP_Object_Invoice();
$Invoice = new QuickBooks_IPP_Object_Invoice();
$Invoice->setDocNumber('WEB' . mt_rand(0, 10000));
$Invoice->setTxnDate('2013-10-11');
$Line = new QuickBooks_IPP_Object_Line();
$Line->setDetailType('SalesItemLineDetail');
$Line->setAmount(12.95 * 2);
$Line->setDescription('Test description goes here.');
$SalesItemLineDetail = new QuickBooks_IPP_Object_SalesItemLineDetail();
$SalesItemLineDetail->setItemRef('8');
$SalesItemLineDetail->setUnitPrice(12.95);
$SalesItemLineDetail->setQty(2);
$Line->addSalesItemLineDetail($SalesItemLineDetail);
$Invoice->addLine($Line);
$Invoice->setCustomerRef('67');
if ($resp = $InvoiceService->add($this->context, $this->realm, $Invoice))
{
return $this->getId($resp);
}
else
{
print($InvoiceService->lastError());
}
}
public function getId($resp){
$resp = str_replace('{','',$resp);
$resp = str_replace('}','',$resp);
$resp = abs($resp);
return $resp;
}
}
Config/app.php
<?php
require_once '../QuickBooks.php';
return [
'qbo_token' => env('QUICKBOOK_TOKEN'),
'qbo_consumer_key' => env('QBO_OAUTH_CONSUMER_KEY'),
'qbo_consumer_secret' => env('QBO_CONSUMER_SECRET'),
'qbo_sandbox' => env('QBO_SANDBOX'),
'qbo_encryption_key' => env('QBO_ENCRYPTION_KEY'),
'qbo_username' => env('QBO_USERNAME'),
'qbo_tenant' => env('QBO_TENANT'),
'qbo_auth_url' => 'http://app.localhost:8000/qbo/oauth',
'qbo_success_url' => 'http://app.localhost:8000/qbo/success',
'qbo_mysql_connection' => 'mysqli://'. env('DB_USERNAME') .':'. env('DB_PASSWORD') .'#'. env('DB_HOST') .'/'. env('DB_DATABASE'),
There are several areas to improve on here with the given code & approach.
As Anton correctly points out, you should not be directly requiring any of the quickbooks library files. If you've loaded this in via Composer then they will be automatically loaded because the Composer autoloader will load the QuickBooks file from the vendor. This is correct for Laravel as well as general Composer-based applications - the only difference with Laravel is that there isn't a specific Laravel Package ServiceProvider that's been written for this SDK, but that doesn't matter.
The QuickBooks library tries to jump on top of autoloading any class that starts with 'QuickBooks', so you're better off making a QuickBooks folder for your controller class. This is more of a 'gotcha' and has been pointed out in the repo issues.
The reason you're getting the Driver/.php error is because you have not specified your QBO_DSN, or have done so incorrectly - this DSN environment variable that you're passing to the initialisation is being run through parse_url() in the SDK code, coming up false or null and breaking the auto-loader for initalisation. If this was set to a proper connection string (e.g. mysqli://username:password#host:port/database and note that port must be a number or it's considered malformed), it would correctly process the DSN and continue to load the page. Be aware that initialisation will attempt to parse and fetch the network address of the host, so you can't just put a dummy value in there and expect it to work - this needs to exist first.
You're mixing your environment variables and application configuration, without using either of them properly. If you wanted your DB connection string (a.k.a. QBO_DSN) to be constructed a particular way into the application configuration setting qbo_mysql_connection, then you should be using the configuration setting when trying to initialise/load/etc. Instead of using env('QBO_DSN'), you should be using config('app.qbo_mysql_connection') to load the constructed version from your app settings. Typically you would not be loading so many environment variables into a controller at all - that should be handled by the application, and then the controller calling the application configuration so it's agnostic of how they were defined.
You shouldn't need to require anything from inside the app configuration file either - that file is just for configuration variables being set up.
Since the QuickBooks SDK isn't properly namespaced (yet), there isn't a nice PSR-4 way of loading (and use-ing) the classes, but it's still good practice to use use clauses at the top of the file (e.g. use QuickBooks_Utilities;) so that you can use the classes without fear of forgetting the preceding backslash (i.e. no more \QuickBooks_Utilities, just QuickBooks_Utilities in usage) - there are several instances in the given code where this has been forgotten, and will not work because the Laravel application is namespaced and will look for those classes in the App\Http\Controllers namespace (e.g. errors like "Cannot find class App\Http\Controllers\QuickBooks_Utilities").
Indentation - pick a style (e.g. tabs, 2-space, PSR-2, etc) and then stick to it. Run phpcs or some other clean-up tool over all of your code before committing to your repository or posting on SO - readability is important!
Using require instead of autoloader is a bad practice in modern frameworks (and generally in modern PHP). I highly recommend using the package manager (eg composer) to properly add modules to the project.
For example, to add a quickbooks library into the project using composer, you need to run only one command:
composer require consolibyte/quickbooks
Add this line in footer of Config/app.php
require_once '../QuickBooks.php';

Magento Integration With T-Hub

am setting up a sand box for a T-Hub Integration with Magento and quickbooks. I've set my life site up locally using WAMP server, and now Its on to trying to tie that local Magento site into T-hub.
The first error that I received stated the
"Connection to Magento store failed. Service authentication failure - Notice: Undefined index: httponly in c:\wamp\www\testsite\appcode\core\mage\Core\Model\Session\Abtract\Varien.php on line 98."
After some searching I found the the general consensus on that one was I had to put an ssl on my local server, done, that problem's gone. Now I'm get a general error message that simply says "Connection to Magento Failed"
I used the test page that atandra included with their files which returned this:
<RESPONSE Version="4.1">
<Envelope>
<Command>GETORDERS</Command>
<StatusCode>9001</StatusCode>
<StatusMessage>
Service authentication failure - Warning: array_key_exists() expects parameter 2 to be array, string given in C:\wamp\www\adamsarms\app\code\core\Mage\Captcha\Model\Observer.php on line 166
</StatusMessage>
<Provider>Magento</Provider>
</Envelope>
</RESPONSE>
Which kicks back to this is the php file:
public function checkUserLoginBackend($observer)
{
$formId = 'backend_login';
$captchaModel = Mage::helper('captcha')->getCaptcha($formId);
$loginParams = Mage::app()->getRequest()->getPost('login', array());
$login = array_key_exists('username', $loginParams) ? $loginParams['username'] : null;
if ($captchaModel->isRequired($login)) {
if (!$captchaModel->isCorrect($this->_getCaptchaString(Mage::app()->getRequest(), $formId))) {
$captchaModel->logAttempt($login);
Mage::throwException(Mage::helper('captcha')->__('Incorrect CAPTCHA.'));
}
}
$captchaModel->logAttempt($login);
return $this;
}
This line is the one it directly points to:
$login = array_key_exists('username', $loginParams) ? $loginParams['username'] : null;
I'm not sure which direction I need to go to fix this error to make t-hub start talking to magento proper, I've included everything that I've got, if someone needs more information please let me know, I just need a better understanding of what might be causing this error to possibly find a path to fixing it.
This is an issue with a Legacy codebase with the T-Hub extension. It was created for PHP 5.3 & Magento versions 1.4 & below. They really should update this thing since people are using it.
The companies official response is this: http://support4.atandra.com/index.php?/Knowledgebase/Article/View/92/4/magento-array_key_exists-error
Which is horrible because it relies on overriding core files.
What's going on is Mage_Captcha_Model_Observer has an event checkUserLoginBackend() that gets fired. This expects the POST info for 'login' to be a certain format. This is something that has changed over the years since legacy code does not have it in this format.
This is a really hacky fix. But it's better than overriding core magento files.
Change the CheckUser() function of Mage/Thub/Model/Run/Run.php to this (I've removed some of their comments):
public function CheckUser()
{
try {
$username = $this->RequestParams['USERID'];
$password = $this->RequestParams['PASSWORD'];
//here we just set the POST to our specified format..
//which is what the observer model thinks it should be
Mage::app()->getRequest()->setPost('login', array(
'username' => $username,
'password' => $password
));
$user = Mage::getSingleton('admin/user');
$userRole = Mage::getSingleton('admin/role');
if ($user->authenticate($username, $password)) {
$loadRole = $userRole->load($user->getRoles($user));
} else {
print($this->xmlErrorResponse($this->RequestParams['COMMAND'], '9000',
'Order download service authentication failure - Login/Password supplied did not match', $this->STORE_NAME, ''));
exit;
}
} catch (Exception $e) {
$this->Msg[] = "Critical Error CheckUser (Exception e)=" . $e->getMessage(); //BB 11Nov2014
print($this->xmlErrorResponse($this->RequestParams['COMMAND'], '9001',
'Service authentication failure - ' . " " . $e->getMessage(), $this->STORE_NAME, ''));
// End - <TIBB> 13Dec2011
exit;
}
}
Another alternative is to extend the Mage_Captcha_Model_Observer class with your own version that removes those array checks in checkUserLoginBackend().

How to call WordPress functions in a custom PHP script

I have a PHP script I want to use for creating a new blog in WPMU. I am having trouble calling WordPress functions like wpmu_create_user and wpmu_create_blog.
My hope is to get this script running as a cron job from the command line and pick up new blog creation requests from an external db, create a new blog using the WordPress functions and update the database with the new blog information.
include wp-load.php file (in the root of your wordpress installation) in your php script file like so,
require_once("/path/to/wordpress/wp-load.php");
you will have to provide the abspath of the wp-load file,
now you can use all the functions of wordpress in your php script
I've got a universal solution that will work in any PHP file inside the wp-content folder without any adjustments or needing to know what is mysterious 'path/to/wordpress'
require_once(explode("wp-content", __FILE__)[0] . "wp-load.php");
It just automatically goes up to root of WordPress and loads wp-load.php.
You can just paste it anywhere, no matter if it's a plugin or theme file, and it will work.
I think stuff like ../../../.. looks extremely bad and when you modify the structure of your folders of a theme or plugin you can get crazy.
Note: This solution assumes you didn't rename your wp-content folder.
For wordpress 3.1, I had to specify the host/domain because wp-includes/ms-settings.php:100 needs it or it dies. So my script looks something like (note I am using it for a network/multiblog site):
#!/usr/bin/php -q
<?php
#for multi-blog only
$blog_id = 1;
#specify host or domain (needed for wp-includes/ms-settings.php:100)
$_SERVER[ 'HTTP_HOST' ] = 'localhost';
#location of wp-load.php so we have access to database and $wpdb object
$wp_load_loc = "/path/to/wordpress/wp-load.php";
require_once($wp_load_loc);
#for multi-blog only
switch_to_blog($blog_id);
#test to make sure we can access database
echo $wpdb->prefix;
?>
This should work:
require_once($_SERVER['DOCUMENT_ROOT'].'/wp-load.php');
i.e. When the php script is on the same server and WP is installed on the root. As most cases are.
Following is the code I am using:
<?PHP
require_once ('/path/to/wordpress/wp-load.php');
require_once ('/path/to/wordpress/wp-blog-header.php');
require_once ('/path/to/wordpress/wp-includes/registration.php');
do_action('wpmuadminedit', '');
//Code to Connect and Select the external database
//Code to Connect to the external DB and get the new order details:
NewBlogName=$name and AdminEmail=$email
if ( !email_exists($email) )
{
// email does exist, create a new user
$name = create_name_from_email($email);
$password = "use a default password";
$user_id=wpmu_create_user($name, $password, $email);
create_blog($email, $title, $user_id, $password);
}
else
{
// user exists, create new blog
$user_id=email_exists($email);
$password = "use existing wordpress password";
create_blog($email, $title, $user_id, $password);
}
function create_name_from_email ($email) {
preg_match('/[^#]+)#/',$email,$matches);
$name = $matches[1];
return $name;
}
//Creates a new blog, expects user to already exist.
function create_blog($email, $title, $user_id, $password)
{
//Code to Update external DB that the order is in process
$public = array("public" => 1);
if (constant('VHOST') == 'yes')
{
$newdomain = $domain . "." . $current_site->domain;
$path = $base;
}
else
{
$newdomain = $current_site->domain; $path = $base . $domain . '/';
}
$domain = strtolower($domain);
$newdomain = strtolower($newdomain);
$path = strtolower($path);
$meta = apply_filters('signup_create_blog_meta', array('lang_id' => 1, $public));
$meta = apply_filters("add_singup_meta", $meta);
wpmu_create_blog($newdomain, $path, $title, $user_id , $meta, $current_site->id);
do_action('wpmu_activate_blog', $blog_id, $user_id, $password, $title, $meta);
// Update external DB with BlogUrl, NewBlogName, AdminPassword,
OrderStatus=Complete.
mysql_close($con);
?>
require_once('../../../wp-load.php');
I think you have to add this line before any usage of wordpress function in your custom file. and make sure i have add ../ 3 times as per my wordpress installation structure.It's depends on your structure checks manually.
ex. if your custom file is inside your themes/yourtheme/custom.php then above code will works perfectly and if not then add ../ or remove one or more ../ as per your path.
WordPress uses a phpass function.
This worked for me as I had a password, and the hash in a table (migrated WordPress users) and had to find a way to check login details.
Grab this download here - https://github.com/sunnysingh/phpass-starter
All you need is this basic function to check a text password to a WordPress hash:
<?php
require_once("PasswordHash.php");
$hasher = new PasswordHash(8, false);
// Check that the password is correct
$check = $hasher->CheckPassword($password, $stored_hash);
if ($check) {
// Password good
} else {
// Password wrong
}
?>
All credits to Sunny Singh!

Example usage of AX in PHP OpenID

I'm using JanRain's PHP OpenID library. It comes with example script which is using SReg extension. But I want it to work with Google (and it works for auth actually), but Google uses AX (attribute exchange) instead of SReg for additional data. For some reason, JanRain's library is missing AX support in example script, and code comments in AX script are out of my understanding, though comments in SReg script are clear as 1-2-3.
Does anyone know how to implement AX without too much pain?
Ran into the same issue. Some digging in AX.php got me a working start. Haven't looked for any bugs, nor tested beyond basic, nor tested with anyone other than Google. This is not pretty: needs error handling, etc. But this should get you started. Will post an update if I have something robust...
First to throw ...
// oid_request.php
// Just tested this with/for Google, needs trying with others ...
$oid_identifier = 'https://www.google.com/accounts/o8/id';
// Includes required files
require_once "Auth/OpenID/Consumer.php";
require_once "Auth/OpenID/FileStore.php";
require_once "Auth/OpenID/AX.php";
// Starts session (needed for YADIS)
session_start();
// Create file storage area for OpenID data
$store = new Auth_OpenID_FileStore('./oid_store');
// Create OpenID consumer
$consumer = new Auth_OpenID_Consumer($store);
// Create an authentication request to the OpenID provider
$auth = $consumer->begin($oid_identifier);
// Create attribute request object
// See http://code.google.com/apis/accounts/docs/OpenID.html#Parameters for parameters
// Usage: make($type_uri, $count=1, $required=false, $alias=null)
$attribute[] = Auth_OpenID_AX_AttrInfo::make('http://axschema.org/contact/email',2,1, 'email');
$attribute[] = Auth_OpenID_AX_AttrInfo::make('http://axschema.org/namePerson/first',1,1, 'firstname');
$attribute[] = Auth_OpenID_AX_AttrInfo::make('http://axschema.org/namePerson/last',1,1, 'lastname');
// Create AX fetch request
$ax = new Auth_OpenID_AX_FetchRequest;
// Add attributes to AX fetch request
foreach($attribute as $attr){
$ax->add($attr);
}
// Add AX fetch request to authentication request
$auth->addExtension($ax);
// Redirect to OpenID provider for authentication
$url = $auth->redirectURL('http://localhost:4001', 'http://localhost:4001/oid_catch.php');
header('Location: ' . $url);
... and then to catch
<?php
// oid_catch.php
// Includes required files
require_once "Auth/OpenID/Consumer.php";
require_once "Auth/OpenID/FileStore.php";
require_once "Auth/OpenID/AX.php";
// Starts session (needed for YADIS)
session_start();
// Create file storage area for OpenID data
$store = new Auth_OpenID_FileStore('./oid_store');
// Create OpenID consumer
$consumer = new Auth_OpenID_Consumer($store);
// Create an authentication request to the OpenID provider
$auth = $consumer->complete('http://localhost:4001/oid_catch.php');
if ($response->status == Auth_OpenID_SUCCESS) {
// Get registration informations
$ax = new Auth_OpenID_AX_FetchResponse();
$obj = $ax->fromSuccessResponse($response);
// Print me raw
echo '<pre>';
print_r($obj->data);
echo '</pre>';
exit;
} else {
// Failed
}
Those ought to be the basics...
The request half is working, however I am getting failure in the Catch.
Should the line above
$auth = $consumer->complete('http://localhost:4001/oid_catch.php');
be
$response = $consumer->complete('http://localhost:4001/oid_catch.php');
Otherwise, where does the response object come from?
I am not getting returned the openid.current_url in my response to check the url with?

Categories