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!
Related
I'm currently making a PHP script and I need some help. Firstly it allows the user to enter database information on a file called install.html which presents a form to the user. The form uses GET to then send that information to a second install file which creates the relevant tables, enters the information into the tables and then allows the user to carry on with the script.
However I was wondering. In the second install file I used:
$databaseServer = $_GET["databaseServer"];
in order to get the information that was entered into the form. Is there anyway I can then send these variables ($databaseServer, $databaseName, $databaseUser, $databasePassword) to another file called db.php that I will include on top of every file I write that requires an SQL connection. I have looked at GLOBAL variables but they didn't work properly. I could have been doing something wrong however.
You could save a configuration array to a file:
<?php
class Config
{
public $path;
public function __construct($path)
{
$this->path = $path;
}
public function store($config)
{
$dump = var_export($config, true);
$dump = '<?php return ' . $dump . ';';
file_put_contents($this->path, $dump);
}
public function retrieve()
{
return include $this->path;
}
}
// Build your config array
$config['database'] = $_GET['database'];
$config['username'] = $_GET['username'];
// Make sure your server can write to this path
$configurator = new Config(__DIR__ . '/config/config.php');
// Save your config
$configurator->store($config);
// Get your config later
$read_config = $configurator->retrieve();
// Check our config against the saved version
assert($config == $read_config);
var_dump($read_config);
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.
My website having feature requirement of blogging. I have to make blog which would look same like my website appearance.
How to combine CodeIgniter and Wordpress blogging(only) functionality such that it should look like within same website?
I have seen this question: Wordpress template with codeigniter. But didn't got much clue.
Seems like a bit of overkill.
Why not use a Restful service like json_api to retrieve your posts, then copy over the css file(parts)?
You do this you will need to create 2 files and modify 2 existing functions. One function is in CodeIgniter and the other is in Wordpress.
Here are the steps.
1.) Open your configs/hooks.php file and create a pre_controller hook as follows:
$hook['pre_controller'] = array(
'class' => '',
'function' => 'wp_init',
'filename' => 'wordpress_helper.php',
'filepath' => 'helpers'
);
2.) Create a new file in your helpers directory called 'wordpress_helper.php', and add the following code to it:
/**
*
*/
function wp_init(){
$CI =& get_instance();
$do_blog = TRUE; // this can be a function call to determine whether to load CI or WP
/* here we check whether to do the blog and also we make sure this is a
front-end index call so it does not interfere with other CI modules.
*/
if($do_blog
&& ($CI->router->class == "index" && $CI->router->method == "index")
)
{
// these Wordpress variables need to be globalized because this is a function here eh!
global $post, $q_config, $wp;
global $wp_rewrite, $wp_query, $wp_the_query;
global $allowedentitynames;
global $qs_openssl_functions_used; // this one is needed for qtranslate
// this can be used to help run CI code within Wordpress.
define("CIWORDPRESSED", TRUE);
require_once './wp-load.php';
define('WP_USE_THEMES', true);
// Loads the WordPress Environment and Template
require('./wp-blog-header.php');
// were done. No need to load any more CI stuff.
die();
}
}
3.) Open wp-includes/link-template.php and made the following edit:
if ( ! function_exists('site_url'))
{
function site_url( $path = '', $scheme = null ) {
return get_site_url( null, $path, $scheme );
}
}
4.) Copy url_helper.php from the CodeIgniter helper folder to your APPPATH helper folder
and make the following edit:
if ( ! function_exists('site_url'))
{
function site_url($uri = '', $scheme = null)
{
// if we are in wordpress mode, do the wordpress thingy
if(defined('CIWORDPRESSED') && CIWORDPRESSED){
return get_site_url( null, $path, $scheme );
}else{
$CI =& get_instance();
return $CI->config->site_url($uri);
}
}
}
The steps above will allow you to dynamically load either your CI app or your WP site based on some simple filtering. It also gives you access to all CI functionality within WP of that is something you can use.
I am trying to configure HTMLPurifier to only display external links as plain text. I used DisplayLinkURI option but it display all links as a plain text. is there any configuration for that? here is my code:
$mySite='mysite';
$externalSite='external';
require_once 'include/htmlpurifier/library/HTMLPurifier.auto.php';
$Config = HTMLPurifier_Config::createDefault();
$Config->set('AutoFormat.DisplayLinkURI', true);
$purifier = new HTMLPurifier($Config);
$mySite= $purifier->purify($mySite);
$externalSite=$purifier->purify($externalSite);
echo $mySite;
echo $externalSite;
The output is
<a>mysite</a> (http://www.mysite.com/)
<a>external</a> (http://www.external.com/)
I want the output to be like this:
mysite
<a>external</a> (http://www.external.com/)
Update:
I want to keep external links for images without change. I only need to convert hyperlinks to plain text.
I believe this is the one you're looking for
http://htmlpurifier.org/live/configdoc/plain.html#URI.DisableExternal
There's an option named URI.DisableExternal and AutoFormat.Linkify. Set them both to TRUE and see what happens.
http://htmlpurifier.org/live/configdoc/plain.html#URI.DisableExternal
http://htmlpurifier.org/live/configdoc/plain.html#AutoFormat.Linkify
And AutoFormat.DisplayLinkURI disables all the links. I suggest you use both the above instead of AutoFormat.DisplayLinkURI.
http://htmlpurifier.org/live/configdoc/plain.html#AutoFormat.DisplayLinkURI
Ok, I succeeded to add a custom injector to HTMLPurifier, here it is:
First, Create a "DisplayRemoteLinkURI.php" in "include\htmlpurifier\library\HTMLPurifier\Injector" and write this in it
<?php
class HTMLPurifier_Injector_DisplayRemoteLinkURI extends HTMLPurifier_Injector
{
public $name = 'DisplayRemoteLinkURI';
public $needed = array('a');
public function handleElement(&$token) {
}
public function handleEnd(&$token) {
if (isset($token->start->attr['href'])){
$url = $token->start->attr['href'];
if($this->is_remote($url)){
unset($token->start->attr['href']);
$token = array($token, new HTMLPurifier_Token_Text(" ($url)"));
}
} else {
// nothing to display
}
}
public function is_remote($path){
$urlvar = parse_url($path);
$remote_schemes = array("mailto");
$local_schemes = array("javascript");
if(in_array($urlvar["scheme"],$remote_schemes)){
return true;
}else if(in_array($urlvar["scheme"],$local_schemes)){
return false;
}else{
if(empty($urlvar["host"]) || $urlvar["host"]==$_SERVER["HTTP_HOST"]){
return false;
}else{
return true;
}
}
}
}
?>
And then create another file named "AutoFormat.DisplayRemoteLinkURI.txt" in "include\htmlpurifier\library\HTMLPurifier\ConfigSchema\schema" and add this :
AutoFormat.DisplayRemoteLinkURI
TYPE: bool
VERSION: 3.2.0
DEFAULT: false
--DESCRIPTION--
<p>
This directive turns on the in-text display of Remote URIs in <a> tags, and disables
those links. For example, example becomes
example (<a>http://example.com</a>).
</p>
--# vim: et sw=4 sts=4
After that, Add this line
require 'HTMLPurifier/Injector/DisplayRemoteLinkURI.php';
under
require 'HTMLPurifier/Injector/DisplayLinkURI.php';
in include\htmlpurifier\library\HTMLPurifier.includes.php
Then, Add this line
require_once $__dir . '/HTMLPurifier/Injector/DisplayRemoteLinkURI.php';
under
require_once $__dir . '/HTMLPurifier/Injector/DisplayLinkURI.php';
in include\htmlpurifier\library\HTMLPurifier.safe-includes.php
After these edits, if your files are at local, run cmd.exe and go to your php directory. Then run "include/HTMLPurifier/maintenance/generate-schema-cache.php" from php.exe.
Or if you want to do this via browser, rename your .htaccess file inside "include/HTMLPurifier/maintenance/" to something else for a while, then add this line inside "generate-schema-cache.php" on the first line after the <?php tag;
php_set_env("PHP_IS_CLI",true);
and then run this file from browser. After you see "Saving schema.. done!", rename your .htaccess file back.
Then in your script, use "AutoFormat.DisplayRemoteLinkURI" as config, and voila!
Note that the is_remote() function inside the first file I gave here might be not so good, and I couldn't find a script that checks if a link is remote or local, so you might alter it later if you need.
I'm writing a WordPress plug-in and need to read the database name, username, and password (In order to do a sql dump). Is this possible?
Thanks-
Yes, they are defined in wp-config.php
Database Name: DB_NAME
Database User: DB_USER
Database password: DB_PASSWORD
Database Host: DB_HOST
They are define. See you wp-config.php in the root directory of Wordpress
Wordpress has some fairly goofy stuff going on throughout its OO code, this isn't the first one I've encountered as we dig deeper into the internals with each successive project at Moxune. See WP_User::__set doesn't persist custom fields as it claims.
The goofiness I refer to here of course is that something like the table prefix, aka wpdb::prefix is a public member variable, however things like dbname, dbpassword, and dbhost are protected and there are no public accessor methods.
I'm sure one of the Wordpress core devs will try to argue some rationale for it, but in the meantime may as well use some good 'ol OO to cope. My suggestion, a decorator.
class SaneDb
{
private $_oDb;
public function __construct(wpdb $oDb)
{
$this->_oDb = $oDb;
}
public function __get($sField)
{
if($sField != '_oDb')
return $this->_oDb->$sField;
}
public function __set($sField, $mValue)
{
if($sField != '_oDb')
$this->_oDb->$sField = $mValue;
}
public function __call($sMethod, array $aArgs)
{
return call_user_func_array(array($this->_oDb, $sMethod), $aArgs);
}
public function getDbName() { return $this->_oDb->dbname; }
public function getDbPass() { return $this->_oDb->dbpassword; }
public function getDbHost() { return $this->_oDb->dbhost; }
}
Then atop your plugin code (functions.php) setup a global in similar vein to wpdb.
global $sanedb;
$sanedb = new SaneDb($wpdb);
From there, just use $sanedb within your plugin instead of $wpdb.
Lastly, getting ahold of the database name et al.
$sanedb->getDbName();
This is super simple now. You can create a PHP file and use the following code.
$path = $_SERVER['DOCUMENT_ROOT'];
include_once $path . '/wp-config.php';
include_once $path . '/wp-load.php';
include_once $path . '/wp-includes/wp-db.php';
include_once $path . '/wp-includes/pluggable.php';
// We need the WordPress Database Credentials
global $wpdb;
$user = $wpdb->dbuser;
$pass = $wpdb->dbpassword;
$name = $wpdb->dbname;
If you need other data just do a print_r on the wpdb variable and you'll see everything inside of there.