After lots of efforts we found something for IPB remote login, but it's not working correctly. We are able to fetch member information but not able to set this member in session.
Please help us to the set session for IPB.
Here is the code:
remote_login.php
<?php
$_SERVER['SCRIPT_FILENAME'] = __FILE__;
$path = '';
require_once $path . 'init.php';
\IPS\Session\Front::i();
$key = md5( md5( \IPS\Settings::i()->sql_user . \IPS\Settings::i()->sql_pass ) . \IPS\Settings::i()->board_start );
$login_type = 'email';
/* uncomment for more security */
// $ip_address = array('127.0.0.1', 'x.x.x.x'); // EDIT THIS LINE!!
// if(in_array($_SERVER['REMOTE_ADDR'], $ip_address) !== TRUE) {
// echo_json(array('status' => 'FAILD', 'msg' => 'BAD_IP_ADDR'));
// }
/* -~-~-~-~-~-~ Stop Editing -~-~-~-~-~-~ */
if( !\IPS\Request::i()->do || !\IPS\Request::i()->id || !\IPS\Request::i()->key || !\IPS\Login::compareHashes( \IPS\Request::i()->key, md5($key . \IPS\Request::i()->id))) {
echo_json(array('status' => 'FAILD', 'msg' => 'BAD_KEY'));
}
$member = \IPS\Member::load( \IPS\Request::i()->id, $login_type );
if( !$member->member_id ) {
echo_json(array('status' => 'FAILD', 'msg' => 'ACCOUNT_NOT_FOUND'));
}
switch(\IPS\Request::i()->do) {
case 'get_salt':
echo_json(array('status' => 'SUCCESS', 'pass_salt' => $member->members_pass_salt));
break;
case 'login':
if( \IPS\Login::compareHashes($member->members_pass_hash, \IPS\Request::i()->password) === TRUE ) {
/* Remove old failed login attempts */
if ( \IPS\Settings::i()->ipb_bruteforce_period and ( \IPS\Settings::i()->ipb_bruteforce_unlock or !isset( $member->failed_logins[ \IPS\Request::i()->ipAddress() ] ) or $member->failed_logins[ \IPS\Request::i()->ipAddress() ] < \IPS\Settings::i()->ipb_bruteforce_attempts ) )
{
$removeLoginsOlderThan = \IPS\DateTime::create()->sub( new \DateInterval( 'PT' . \IPS\Settings::i()->ipb_bruteforce_period . 'M' ) );
$failedLogins = $member->failed_logins;
if ( is_array( $failedLogins ) )
{
foreach ( $failedLogins as $ipAddress => $times )
{
foreach ( $times as $k => $v )
{
if ( $v < $removeLoginsOlderThan->getTimestamp() )
{
unset( $failedLogins[ $ipAddress ][ $k ] );
}
}
}
$member->failed_logins = $failedLogins;
}
else
{
$member->failed_logins = array();
}
$member->save();
}
/* If we're still here, the login was fine, so we can reset the count and process login */
if ( isset( $member->failed_logins[ \IPS\Request::i()->ipAddress() ] ) )
{
$failedLogins = $member->failed_logins;
unset( $failedLogins[ \IPS\Request::i()->ipAddress() ] );
$member->failed_logins = $failedLogins;
}
$member->last_visit = time();
$member->save();
/*==========================try to set session code start================*/
/* Create a unique session key and redirect */
\IPS\Session::i()->setMember( $member );
$expire = new \IPS\DateTime;
$expire->add( new \DateInterval( 'P7D' ) );
\IPS\Request::i()->setCookie( 'member_id', $member->member_id, $expire );
\IPS\Request::i()->setCookie( 'pass_hash', $member->member_login_key, $expire );
if ( $anonymous and !\IPS\Settings::i()->disable_anonymous )
{
\IPS\Request::i()->setCookie( 'anon_login', 1, $expire );
}
\IPS\Session::i()->setMember( $member );
\IPS\Session::i()->init();
\IPS\Request::i()->setCookie( 'ips4_member_id', $member->member_id, $expire );
\IPS\Request::i()->setCookie( 'ips4_pass_hash', $member->member_login_key, $expire );
/*$member->checkLoginKey();
$expire = new \IPS\DateTime;
$expire->add( new \DateInterval( 'P1Y' ) );
\IPS\Request::i()->setCookie( 'ips4_member_id', $member->member_id, $expire );
\IPS\Request::i()->setCookie( 'ips4_pass_hash', $member->member_login_key, $expire );*/
/*==========================try to set session code end================*/
echo_json(
array(
'status' => 'SUCCESS',
'connect_status' => ( $member->members_bitoptions['validating'] ) ? 'VALIDATING' : 'SUCCESS',
'email' => $member->email,
'name' => $member->name,
'connect_id' => $member->member_id,
'member' =>$member
)
);
}
break;
}
function echo_json(array $arr) {
echo json_encode($arr);
exit;
}
login.php
<?php
$ips_connect_key = '3325a51154becfc88fXXXXXXXXX';
$remote_login = 'IPB/remote_login.php';
$email = $_GET['email'];
$password = $_GET['password'];
$key = md5($ips_connect_key . $email);
// fetch salt first
$res = json_decode(file_get_contents($remote_login . "?do=get_salt&id={$email}&key={$key}"), true);
$hash = crypt( $password, '$2a$13$' . $res['pass_salt'] );
$res = json_decode(file_get_contents($remote_login . "?do=login&id={$email}&key={$key}&password={$hash}"), true);
$_COOKIE["ips4_member_id"]=41;
$_COOKIE['ips4_pass_hash']="e195d3939b62342481dfc32fcf360538";
$_COOKIE['ips4_IPSSessionFront']="sn359rogbto4j7jqhcqh10stl5";
print_r($res);
echo "<br/><br/><br/>";
print_r($_COOKIE);
calling login.php
login.php?email=XXXXX#gmail.com&password=XXXXXX!
Here we are able to get member information but not able to set that member as logged in.
Related
I need to interact with a third party plugin to send SMS. The plugin is Bookly, which is for making appointments. I edited the Ajax.php that Bookly uses for saving the appointment. I've sent the SMS succesfully on Ajax.php. However, I want to code an external plugin to make the process controllable on admin panel.
I use a custom hook named "bookly_appointment_saved" and send an array with that. And in my new plugin I catch the hook succesfully. The SMS is always sent but the Ajax.php of Bookly doesn't send the response to the frontend. It keeps showing the page as loading.
Please see the codes below and help.
Ajax.php (Bookly) - Only related method is included.
/**
* Save cart appointments.
*/
public static function saveAppointment()
{
$userData = new Lib\UserBookingData( self::parameter( 'form_id' ) );
if ( $userData->load() ) {
$failed_cart_key = $userData->cart->getFailedKey();
if ( $failed_cart_key === null ) {
$cart_info = $userData->cart->getInfo();
$is_payment_disabled = Lib\Config::paymentStepDisabled();
$skip_payment = BookingProxy\CustomerGroups::getSkipPayment( $userData->getCustomer() );
$gateways = self::getGateways( $userData, clone $cart_info );
if ( $is_payment_disabled || isset( $gateways['local'] ) || $cart_info->getPayNow() <= 0 || $skip_payment ) {
// Handle coupon.
$coupon = $userData->getCoupon();
if ( $coupon ) {
$coupon->claim()->save();
}
// Handle payment.
$payment = null;
if ( ! $is_payment_disabled && ! $skip_payment ) {
if ( $cart_info->getTotal() <= 0 ) {
if ( $cart_info->withDiscount() ) {
$payment = new Lib\Entities\Payment();
$payment
->setType( Lib\Entities\Payment::TYPE_FREE )
->setStatus( Lib\Entities\Payment::STATUS_COMPLETED )
->setPaidType( Lib\Entities\Payment::PAY_IN_FULL )
->setTotal( 0 )
->setPaid( 0 )
->save();
}
} else {
$payment = new Lib\Entities\Payment();
$status = Lib\Entities\Payment::STATUS_PENDING;
$type = Lib\Entities\Payment::TYPE_LOCAL;
$paid = 0;
foreach ( $gateways as $gateway => $data ) {
if ( $data['pay'] == 0 ) {
$status = Lib\Entities\Payment::STATUS_COMPLETED;
$type = Lib\Entities\Payment::TYPE_FREE;
$cart_info->setGateway( $gateway );
$payment->setGatewayPriceCorrection( $cart_info->getPriceCorrection() );
break;
}
}
if ( $status !== Lib\Entities\Payment::STATUS_COMPLETED ) {
$gift_card = $userData->getGiftCard();
if ( $gift_card ) {
$type = Lib\Entities\Payment::TYPE_CLOUD_GIFT;
$cart_info->setGateway( $type );
if ( $gift_card->getBalance() >= $cart_info->getPayNow() ) {
$status = Lib\Entities\Payment::STATUS_COMPLETED;
$paid = $cart_info->getPayNow();
$gift_card->charge( $paid )->save();
$payment->setGatewayPriceCorrection( $cart_info->getPriceCorrection() );
}
}
}
$payment
->setType( $type )
->setStatus( $status )
->setPaidType( Lib\Entities\Payment::PAY_IN_FULL )
->setTotal( $cart_info->getTotal() )
->setTax( $cart_info->getTotalTax() )
->setPaid( $paid )
->save();
}
}
// Save cart.
$order = $userData->save( $payment );
if ( $payment !== null ) {
$payment->setDetailsFromOrder( $order, $cart_info )->save();
}
// Send notifications.
Lib\Notifications\Cart\Sender::send( $order );
$response = array(
'success' => true,
);
} else {
$response = array(
'success' => false,
'error' => Errors::PAY_LOCALLY_NOT_AVAILABLE,
);
}
} else {
$response = array(
'success' => false,
'failed_cart_key' => $failed_cart_key,
'error' => Errors::CART_ITEM_NOT_AVAILABLE,
);
}
//Custom hook
$user_appointed=$userData->getData();
do_action('bookly_appointment_saved',
$appointment=[
'date'=>date("d/m/Y", strtotime($user_appointed['slots'][0][2]) ),
'time'=>date("H:i", strtotime($user_appointed['slots'][0][2]) ),
'full_name'=>$user_appointed['full_name']=''?$user_appointed['first_name'].' '.$user_appointed['last_name']:$user_appointed['full_name'],
'service_name'=>$userData->cart->getItemsTitle(),
]
);
// end of hook
$userData->sessionSave();
wp_send_json( $response );
}
Errors::sendSessionError();
}
custom-sms-sender-plugin.php (My plugin)
add_action('bookly_appointment_saved','send_sms');
function send_sms($appointment){
$phone = "66666666666";
$message="New appointment - ".$appointment['full_name']." Service: ".$appointment['service_name']." Date: ".$appointment['date']." Time:".$appointment['time'];
$message = urlencode($message);
$url= "//request url with parameters";
$request = wp_remote_get($url);
if ($request['body'] !=30 || $request['body'] !=20 || $request['body'] !=40 || $request['body'] !=50 || $request['body'] != 51 || $request['body'] != 70 || $request['body'] != 85) {
write_log("SENT - SMS Code : ".explode(" ",$request['body'])[1]);
} else {
write_log("ERROR - Code : ".$request['body']);
}
}
I've solved the problem. It is caused by the "write_log" commands as the command doesn't exist. After changing the log method, it worked like a charm. Thanks for all comments.
Im trying to send a MailChimp campaign, from a cron job in a cpanel, in a php file.
The idea is to have a condition and if realized, send a MC campaign.
The test is if there is an unseen message in a certain mailbox with a certain subject. The test is done trough an imap connexion as you will see below.
The unseen email test is working with a cron job, no pb.
But when i add the MC connexion and campaign sending, it is stuck.
Here is the entire code i have tried to write (actually, i tried to use others pieces of code).
Please help if possible.
<?php
//needed for the MailChimp connection
require_once (‘wp-config.php’);
$SCUpdate = 0 ;
$mailbox = imap_open('{imap.server.com:993/imap/ssl}INBOX', 'email#domain.com', 'password');
$unseenMessages = imap_search($mailbox, 'UNSEEN');
if ($unseenMessages != 0) {
$MailHeaders = imap_headers( $unseenMessages );
$Subject = "Subject_Search_Name";
Foreach ($MailHeaders as $Subject) {
$SCUpdate = 1 ;
}
If ($SCUpdate = 1) {
//make the MailChimp connection
function mailchimp_api_request($endpoint,$type=‘POST’,$body = ‘’) {
$api_key = 'xxxxxxx';
$endpoint = ‘https://<dc>.api.mailchimp.com/3.0/’;
list(, $datacenter) = explode( ‘-’, $api_key );
$endpoint = str_replace( ‘<dc>’, $datacenter, $endpoint );
$url = $endpoint . $endpoint;
$request_args = array(
‘method’ => $type,
‘timeout’ => 20,
‘headers’ => array(
‘Content-Type’ => ‘application/json’,
‘Authorization’ => ‘apikey ‘ . $api_key
)
);
if ( $body ) {
$request_args[‘body’] = json_encode( $body );
}
$request = wp_remote_post( $url, $request_args );
$response = is_wp_error( $request ) ? false : json_decode( wp_remote_retrieve_body( $request ) );
return $response;
}
//link campaign to template
$campaign_id = 'xxxxxxx';
function set_mail_campaign_content( $campaign_id, $template_content ) {
$set_content = '';
$set_campaign_content = mailchimp_api_request( "campaigns/$campaign_id/content", 'PUT', $template_content );
if ( $set_campaign_content ) {
if ( ! empty( $set_campaign_content->html ) ) {
$set_content = true;
}
}
return $set_content ? true : false;
}
$list_id = "your-list-id";
$date = date('Y-m-d',strtotime(current_time('mysql')));
$title = "campaign-title";
$subject = "campaign-subject";
$campaign_id = null;
$campaign_id = create_mailchimp_campaign( $list_id, $subject, $title );
if($campaign_id == null){
exit(2);
}
$template_content = array(
'template' => array(
// The id of the template to use.
'id' => xxxxxxx,
)
);
$set_campaign_content = set_mail_campaign_content( $campaign_id, $template_content );
if($set_campaign_content == false){
exit(3);
}
// Schedule time
$time = time();
$schedule = mailchimp_api_request( "campaigns/$campaign_id/actions/schedule", 'POST', array('schedule_time' => $time) );
$campaign = mailchimp_api_request( "/campaigns/$campaign_id", 'GET', '' );
mail('myemail#test.com', 'Test Subject', 'Test Name');
$SCUpdate = 0 ;
}
}
if ($unseenMessages) {
imap_setflag_full( $mailbox, implode(',', $unseenMessages ), '\Seen');
imap_close( $mailbox );
}
?>
I am receiving this warning in one of the Wordpress plugins.
copy(): Filename cannot be empty in /wp-content/plugins/nix-gravatar-cache/nf-gravatar-cache.php on line 181
Please help me correct this, if somebody can. I am not very good with PHP. Thanks
Here is the code.
<?php
class NFGC_Gravatar_Cache {
protected $upload_url;
protected $upload_path;
protected $plugin_dir_path;
public $plugin_name = 'NIX Gravatar Cache';
function __construct(){
if ( get_option( 'upload_url_path' ) ) {
$this->upload_url = get_option( 'upload_url_path' );
$this->upload_path = get_option( 'upload_path' );
}
else {
$up_dir = wp_upload_dir();
$this->upload_url = $up_dir['baseurl'];
$this->upload_path = $up_dir['basedir'];
}
$this->plugin_dir_path = plugin_dir_path( __FILE__ );
require_once $this->plugin_dir_path . '/messages.class.php';
NFGC_Messages::init();
$active = get_option( 'nf_c_a_options' );
if ( $active[0]['active'] == 1 ) {
add_filter( 'get_avatar', array( $this,'get_cached_avatar' ), -1000000000, 5 );
}
add_action( 'admin_menu', array( $this,'add_admin_menu' ) );
register_activation_hook( __FILE__, array( $this, 'activate' ) );
$this->init();
register_deactivation_hook( __FILE__, 'deactivate' );
register_uninstall_hook( __FILE__ , 'uninstall' );
if ( !is_writable( $this->upload_path.'/gravatar/' ) && is_dir( $this->upload_path.'/gravatar/' ) ) {
NFGC_Messages::add_message( 'error', 'Please set write permissions for "'. $this->upload_path .'/gravatar/"' );
}else{
if ( #!mkdir( $this->upload_path.'/gravatar/', 0777 ) && ! is_dir( $this->upload_path.'/gravatar/' ) ) {
NFGC_Messages::add_message( 'error', 'Could not create directory "gravatar". Please set write permissions for "'. $this->upload_path .'/gravatar/"' );
}
}
if ( isset ( $_POST['nf_clear_cache'] ) )
$this->clear_cache();
}
public function get_template_path() {
return $this->plugin_dir_path .'template';
}
// Activate plugin and update default option
public function activate() {
$dir = $this->upload_path.'/gravatar/';
// delete_option('nf_c_a_options');
if ( get_option( 'nf_c_a_options' ) == false ) {
$default_options = array('active' => 1,
'ttl_day' => 10,
'ttl_hour' => 0,
'ttl_min' => 0
);
update_option( 'nf_c_a_options', array( $default_options ) );
}
}
// Deactivate plugin and clear cache
public function deactivate() {
$this->clear_cache();
}
// Notice in plugin options page
public function admin_help_notice() {
global $current_screen;
if ( $current_screen->base == 'settings_page_'. basename( __FILE__,'.php' ) ) {
return true;
}
}
// convert ttl option to second
private function cache_to_second(){
$cache_time = get_option( 'nf_c_a_options' );
$cache_time = array_reverse( $cache_time[0] );
$action = array();
foreach ( $cache_time as $key => $value ) {
if ( $key == 'active' )
continue;
switch ( $key ) {
case 'ttl_min':
$cache_second = $value != 0 ? $value*60 : '';
break;
case 'ttl_hour':
$cache_second = $value != 0 ? ( $value*60*60 ) + $cache_second : $cache_second;
break;
case 'ttl_day':
$cache_second = $value != 0 ? ( $value*60*60*24 ) + $cache_second : $cache_second;
break;
}
}
if ( ! $cache_second ) {
$cache_second = 864000;// TTL of cache in seconds (10 days)
}
return $cache_second;
}
// The main functional
public function get_cached_avatar( $source, $id_or_email, $size, $default, $alt ) {
if ( !is_writable( $this->upload_path.'/gravatar/' ) || is_admin() ) {
return $source;
}
$time = $this->cache_to_second();
preg_match('/d=([^&]*)/', $source, $d_tmp);
$g_url_default_sorce = isset($d_tmp[1]) ? $d_tmp[1] : false;
preg_match('/forcedefault=([^&]*)/', $source, $d_tmp);
$g_forcedefault = isset($d_tmp[1]) ? $d_tmp[1] : false;
preg_match('/avatar\/([a-z0-9]+)\?s=(\d+)/', $source, $tmp);
$garvatar_id = $tmp[1];
$file_name = md5($garvatar_id.$g_url_default_sorce);
$g_path = $this->upload_path.'/gravatar/'.$file_name.'-s'.$size.'.jpg';
//* $g_path_default = $this->upload_path.'/gravatar/default'.'-s'.$size.'.jpg';
$g_url = $this->upload_url.'/gravatar/'.$file_name.'-s'.$size.'.jpg';
//* $g_url_default = $this->upload_url.'/gravatar/'.'default'.'-s'.$size.'.jpg';
// Check cache
static $nf_avatars_cache = null;
if ($nf_avatars_cache === null) $nf_avatars_cache = get_option('nf_avatars_cache');
if (! is_array($nf_avatars_cache)) $nf_avatars_cache = array();
if (isset($nf_avatars_cache[$garvatar_id][$size])) {
$g_url = $nf_avatars_cache[$garvatar_id][$size]['url'];
$g_path = $nf_avatars_cache[$garvatar_id][$size]['path'];
}
if (! is_file($g_path) || (time()-filemtime($g_path)) > $time) {
$curl_url = 'https://www.gravatar.com/avatar/'.$garvatar_id.'?s='.$size.'&r=G&d='.$g_url_default_sorce;
$ch = curl_init($curl_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
$response = curl_exec($ch);
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($response, 0, $header_size);
// Checking for redirect
$header_array = array();
preg_match('/^Location\: (.*)$/m', $header, $header_array);
$redirect_url = isset($header_array[1]) ? $header_array[1] : false;
if ($redirect_url) {
$g_url = $g_url_default;
$g_path = $g_path_default;
if (! is_file($g_path) || (time()-filemtime($g_path)) > $time) {
copy($redirect_url, $g_path);
}
}
else {
// Check mime type
$mime_str = curl_getinfo( $ch, CURLINFO_CONTENT_TYPE );
$mime_array = array();
preg_match( '#/([a-z]*)#i', $mime_str, $mime_array );
if (isset($mime_array[1])) {
// Write cache to file
$fp = fopen( $g_path, "wb" );
$body = substr( $response, $header_size );
fwrite( $fp, $body );
fclose( $fp );
}
}
curl_close($ch);
$nf_avatars_cache[$garvatar_id][$size]['url'] = $g_url;
$nf_avatars_cache[$garvatar_id][$size]['path'] = $g_path;
update_option( 'nf_avatars_cache', $nf_avatars_cache );
}
return '<img alt = "'.$alt.'" src=\''.$g_url.'\' class="avatar avatar-'.$size.'" width="'.$size.'" height="'.$size.'" />';
}
// Create plugin option settings menu
public function add_admin_menu() {
// settings menu page
add_options_page( 'Cached Avatar ', $this->plugin_name, 'manage_options', basename( __FILE__ ), array( $this,'view_options_page' ) );
}
// Create page option
public function view_options_page() {
// update options
if ( isset( $_POST['nf_c_a_submit'] ) ) {
$update_val_options = $_POST['nf_c_a_options'];
foreach ( $update_val_options as $option => $value ) {
$update_val_options[$option] = abs( intval( $value ) );
}
if( $update_val_options['ttl_min'] == 0 && $update_val_options['ttl_hour'] == 0 && $update_val_options['ttl_day'] == 0 ) {
$update_val_options['ttl_day'] = 10;
}
update_option( 'nf_c_a_options', array( $update_val_options ) );
}
$options = get_option( 'nf_c_a_options' );
include( $this->get_template_path() .'/main-options-page.php');
}
private function clear_cache() {
$dir = $this->upload_path.'/gravatar/';
$no_permision_to_delete = false;
// Open directory
if ( is_dir( $dir ) ) {
if ( $opendir = opendir( $dir ) ) {
$count = 0;
while ( ( $file = readdir( $opendir ) ) !== false ) {
if ( filetype( $dir . $file ) == 'file' ) {
if ( #unlink( $dir . $file ) ) {
$count++;
}else {
$no_permision_to_delete = true;
}
}
}
if ( $no_permision_to_delete ) {
NFGC_Messages::add_message( 'error','Unable to clear the cache' );
}else{
update_option('nf_avatars_cache', array() );
NFGC_Messages::add_message( 'info','The cache is cleared!' );
NFGC_Messages::add_message( 'info','Removed '.$count.' files' );
}
closedir( $opendir );
}
}
}
// return count and size
public function get_cache_info() {
$dir = $this->upload_path.'/gravatar/';
$skip = array('.','..');
$unit = array('b', 'kb', 'mb', 'gb', 'tb', 'pb');
if ( is_dir( $dir ) ) {
$file_list = scandir( $dir );
// delete . and ..
foreach ( $skip as $value ) {
unset( $file_list[ array_search( $value, $file_list ) ] );
}
// sum files size
foreach ( $file_list as $file ) {
$size = filesize( $dir . $file );
$all_size = $all_size + $size;
}
}
$readable_form = #round( $all_size / pow( 1024, ( $i = floor( log( $all_size, 1024) ) ) ), 2 ) . ' ' . $unit[$i];
return array( 'amount' => count( $file_list ) , 'used_space' => $readable_form );
}
private function init() {
return false;
wp_enqueue_script( 'nfgc-main-script', plugins_url( '/js/main.js', __FILE__ ), array('jquery') );
wp_enqueue_style( 'nfgc-main-style', plugins_url( '/css/style.css', __FILE__ ) );
}
}// Class
global $nfgc;
$nfgc = new NFGC_Gravatar_Cache();
add_action('wp_enqueue_scripts', function() {
wp_enqueue_script( 'nfgc-main-script', plugins_url( '/js/main.js', __FILE__ ), array('jquery') );
wp_enqueue_style( 'nfgc-main-style', plugins_url( '/css/style.css', __FILE__ ) );
});
`
Try this..
Use file_exists
Returns TRUE if the file or directory specified by filename exists; FALSE otherwise.
if (file_exists($redirect_url)) {
$g_url = $g_url_default;
$g_path = $g_path_default;
if (! is_file($g_path) || (time()-filemtime($g_path)) > $time) {
copy($redirect_url, $g_path);
}
}
http://php.net/manual/en/function.file-exists.php
I'm migrating a whole slew of users between two self-hosted Wordpress sites, and I'm trying to find a way to bring them across without resetting their passwords. The current site has everyone's passwords, naturally, all nicely hashed. Currently the two methods I could see to import these users (wp_insert_user() and wp_create_user()) both require the passwords to be in clear text. Is there something I'm missing, or can this just not be done with current methods?
You have 3 options. Run a custom database query, copy and modify wp_insert_user(), or run wp_insert_user() twice.
Copy and modify wp_insert_user()
Below is a custom wp_insert_user function. All I've done is removed the line that hashes the PW.
function wpse_custom_insert_user( $userdata ) {
global $wpdb;
if ( is_a( $userdata, 'stdClass' ) )
$userdata = get_object_vars( $userdata );
elseif ( is_a( $userdata, 'WP_User' ) )
$userdata = $userdata->to_array();
extract( $userdata, EXTR_SKIP );
// Are we updating or creating?
if ( !empty($ID) ) {
$ID = (int) $ID;
$update = true;
$old_user_data = WP_User::get_data_by( 'id', $ID );
} else {
$update = false;
}
$user_login = sanitize_user($user_login, true);
$user_login = apply_filters('pre_user_login', $user_login);
//Remove any non-printable chars from the login string to see if we have ended up with an empty username
$user_login = trim($user_login);
if ( empty($user_login) )
return new WP_Error('empty_user_login', __('Cannot create a user with an empty login name.') );
if ( !$update && username_exists( $user_login ) )
return new WP_Error( 'existing_user_login', __( 'Sorry, that username already exists!' ) );
if ( empty($user_nicename) )
$user_nicename = sanitize_title( $user_login );
$user_nicename = apply_filters('pre_user_nicename', $user_nicename);
if ( empty($user_url) )
$user_url = '';
$user_url = apply_filters('pre_user_url', $user_url);
if ( empty($user_email) )
$user_email = '';
$user_email = apply_filters('pre_user_email', $user_email);
if ( !$update && ! defined( 'WP_IMPORTING' ) && email_exists($user_email) )
return new WP_Error( 'existing_user_email', __( 'Sorry, that email address is already used!' ) );
if ( empty($nickname) )
$nickname = $user_login;
$nickname = apply_filters('pre_user_nickname', $nickname);
if ( empty($first_name) )
$first_name = '';
$first_name = apply_filters('pre_user_first_name', $first_name);
if ( empty($last_name) )
$last_name = '';
$last_name = apply_filters('pre_user_last_name', $last_name);
if ( empty( $display_name ) ) {
if ( $update )
$display_name = $user_login;
elseif ( $first_name && $last_name )
/* translators: 1: first name, 2: last name */
$display_name = sprintf( _x( '%1$s %2$s', 'Display name based on first name and last name' ), $first_name, $last_name );
elseif ( $first_name )
$display_name = $first_name;
elseif ( $last_name )
$display_name = $last_name;
else
$display_name = $user_login;
}
$display_name = apply_filters( 'pre_user_display_name', $display_name );
if ( empty($description) )
$description = '';
$description = apply_filters('pre_user_description', $description);
if ( empty($rich_editing) )
$rich_editing = 'true';
if ( empty($comment_shortcuts) )
$comment_shortcuts = 'false';
if ( empty($admin_color) )
$admin_color = 'fresh';
$admin_color = preg_replace('|[^a-z0-9 _.\-#]|i', '', $admin_color);
if ( empty($use_ssl) )
$use_ssl = 0;
if ( empty($user_registered) )
$user_registered = gmdate('Y-m-d H:i:s');
if ( empty($show_admin_bar_front) )
$show_admin_bar_front = 'true';
$user_nicename_check = $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->users WHERE user_nicename = %s AND user_login != %s LIMIT 1" , $user_nicename, $user_login));
if ( $user_nicename_check ) {
$suffix = 2;
while ($user_nicename_check) {
$alt_user_nicename = $user_nicename . "-$suffix";
$user_nicename_check = $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->users WHERE user_nicename = %s AND user_login != %s LIMIT 1" , $alt_user_nicename, $user_login));
$suffix++;
}
$user_nicename = $alt_user_nicename;
}
$data = compact( 'user_pass', 'user_email', 'user_url', 'user_nicename', 'display_name', 'user_registered' );
$data = wp_unslash( $data );
if ( $update ) {
$wpdb->update( $wpdb->users, $data, compact( 'ID' ) );
$user_id = (int) $ID;
} else {
$wpdb->insert( $wpdb->users, $data + compact( 'user_login' ) );
$user_id = (int) $wpdb->insert_id;
}
$user = new WP_User( $user_id );
foreach ( _get_additional_user_keys( $user ) as $key ) {
if ( isset( $$key ) )
update_user_meta( $user_id, $key, $$key );
}
if ( isset($role) )
$user->set_role($role);
elseif ( !$update )
$user->set_role(get_option('default_role'));
wp_cache_delete($user_id, 'users');
wp_cache_delete($user_login, 'userlogins');
if ( $update )
do_action('profile_update', $user_id, $old_user_data);
else
do_action('user_register', $user_id);
return $user_id;
}
Running wp_insert_user twice
If you run wp_insert_user() user_pass is expected to be a plain string. If you include an ID parameter however you need to use a hashed password instead.
You could run wp_insert_user() with a random password to insert the user. This will return an ID. You could then run the same function again including the ID and the hashed password.
As I pointed out above this is inefficient and not something I'd suggest but it would be possible. Here's an example:
$hashed_pw = get_hashed_pw(); // Replace this with the correct hashed password.
$user_args = array(
'ALL MY' => 'OTHER ARGS', // Enter all your other arguments for wp_insert_user().
'user_pass' => 'random', // Set this to a random string.
);
$user_id = wp_insert_user( $user_args );
$update_user_args = array(
'ID' => $user_id,
'user_pass' => $hashed_pw,
);
wp_insert_user( $update_user_args );
This is not a complete solution. If you were to use it you'd want to include some error checking, etc. You're much better off with one of the two other solutions posed.
In my theme, there's custom page for the login. Login function at functions.php is like this
function log_in($username, $password) {
$user = parse_user($username);
$username = $username;
$password = $password;
if(isEmptyString($username)) return new WP_Error('username', 'required');
if(isEmptyString($password)) return new WP_Error('password', "required");
if(!wp_check_password( $password, $user->user_pass ) ) return new WP_Error('wrong_password', "wrong");
wp_set_auth_cookie($user->ID, $remember);
wp_login($username, $password);
redirect_profile();
}
function parse_user($info = null, $return = 'object') {
if ( is_null( $info ) ) {
global $current_user;
if ( empty( $current_user->ID ) ) return null;
$info = get_userdata( $current_user->ID );
}
elseif ( empty( $info ) ) {
return null;
}
if( $return == 'ID' ) {
if ( is_object( $info ) ) return $info->ID;
if ( is_numeric( $info ) ) return $info;
}
elseif( $return == 'object' ) {
if ( is_object( $info ) && $info->ID) return $info;
if ( is_object( $info )) return get_userdata( $info->ID );
if ( is_numeric( $info ) ) return get_userdata( $info );
if ( is_string( $info ) ) return get_userdatabylogin( $info );
}
else {
return null;
}
}
I want to add remember me checkbox for user to logged in all the time until they logout. How can i add this ? Please kindly help me out. Thank you.
"remember me" buttons are generally just a simple tweak to the cookie settings internally. Instead of a session cookie that gets deleted when the browser is exitted, a "remember me" login cookie gets some future expiration point (a day, a month, a year, etc...) so it'll persist after the browser's closed.
In pseudo-code, you'd have:
if (form_value('remember_me') == 'yes) {
set_long_term_cookie();
} else {
set_session_cookie();
}
"Add a login form on your WordPress Theme" (including remember me functionality):
http://www.wprecipes.com/add-a-login-form-on-your-wordpress-theme
Also: http://www.problogdesign.com/how-to/how-to-create-a-wordpress-login-form-overlay/
etc...