I'm using FOSUserBundle in my application. I would like to do two things via HTTP services:
Check password. The service could look like this (the password wouldn't be encrypted):
public function checkPasswordValidity($userId, $password) {
$user = $this->getDoctrine()
->getRepository('MyCompany\UserBundle\Entity\User')
->find($userId);
if (specialFunction($user , $password))
echo 'Valid Password';
else
echo 'Invalid Password';
}
Create a new user via another HTTP service. The parameters would be the username and the password.
Check password:
$encoder_service = $this->get('security.encoder_factory');
$encoder = $encoder_service->getEncoder($user);
$encoded_pass = $encoder->encodePassword($password, $user->getSalt());
//then compare $user->getPassword() and $encoded_pass
Create a new user:
$userManager = $this->get('fos_user.user_manager');
$user = $userManager->createUser();
$user->setUsername($login);
$user->setPlainPassword($pass);
...
$userManager->updateUser($user);
For me works:
$encoder_service = $this->get('security.encoder_factory');
$encoder = $encoder_service->getEncoder($user);
if ($encoder->isPasswordValid($user->getPassword(), $password, $user->getSalt()) {}
I did not test second question, but I think it is answered already.
Manually add new user :
Login to phpmyadmin , access fos_user_user table , click insert > fill fields , username , email,roles etc.
Generate salt and password using this php script:
<?php
$salt = base_convert(sha1(uniqid(mt_rand(), true)), 16, 36);
echo "Salt used: " . $salt ."<br/>";
echo "<br/>";
$password = 'adminpasswordhere';
$salted = $password.'{'.$salt.'}';
$digest = hash('sha512', $salted, true);
for ($i=1; $i<5000; $i++) {
$digest = hash('sha512', $digest.$salted, true);
}
$encodedPassword = base64_encode($digest);
echo "Password used: " . $password ."<br/>";
echo "<br/>";
echo "Encrypted Password: " . $encodedPassword ."<br/>";
?>
Enjoy !
Related
I am using wp_mail function to send email, but I receive email only when the dashboard is loggedin in a new tab on same browser, if the wp dashboard is closed i dont receive email. can some body help.
please find the code i am using.
add_action( 'wp_ajax_send_message', 'do_send_message' );
function do_send_message() {
if ( isset($_POST['name']) && isset($_POST['email']) &&isset($_POST['message']) &&isset($_POST['phone']) &&isset($_POST['enquiry'])) {
$name = $_POST['name']; $email = $_POST['email']; $message = $_POST['message']; $phone = $_POST['phone']; $subject = $_POST['enquiry'];
$to = "xyz#domain.com";
$body = "\n\nName: $name \n\nphone: $phone \n\nEmail: $email \n\nMessage: $message";
$success = wp_mail($to,$subject,$body);
if ($success) return true;
}
}
In Wordpress, How can I delete a user pro grammatically if I have a user ID?
I am using below code.
$user_id = 4;
$roles = array();
$user = get_userdata($user_id);
$capabilities = $user->{$wpdb->prefix . 'capabilities'};
if (!isset($wp_roles))
$wp_roles = new WP_Roles();
foreach ($wp_roles->role_names as $role => $name) :
if (array_key_exists($role, $capabilities))
$roles[] = $role;
endforeach;
if (!in_array("administrator", $roles)) {
if (wp_delete_user($user_id)) {
echo 'User deleted' . $user_id;
echo '<br>';
}
}
It is not working for me. Please help me where am I wrong?
Try this
$user_id = 1;
$user_info = get_userdata( $user_id );
$this_user_roles = $user_info->roles;
//For wp_delete_user() function
require_once(ABSPATH.'wp-admin/includes/user.php' );
if( in_array( "administrator", $this_user_roles) ) {
echo "This user is admin, cannot be deleted";
} else {
if( wp_delete_user( $user_id ) ){
echo "Success user deleted :)";
} else {
echo "There is a problem while deleting the user.";
}
}
I have found the solution to resolve my issue.I have just added a line in code.
Now updated code as given below.
require_once(ABSPATH.'wp-admin/includes/user.php' );
$user_id = 4;
$roles = array();
$user = get_userdata($user_id);
$capabilities = $user->{$wpdb->prefix . 'capabilities'};
if (!isset($wp_roles))
$wp_roles = new WP_Roles();
foreach ($wp_roles->role_names as $role => $name) :
if (array_key_exists($role, $capabilities))
$roles[] = $role;
endforeach;
if (!in_array("administrator", $roles)) {
if (wp_delete_user($user_id)) {
echo 'User deleted' . $user_id;
echo '<br>';
}
}
It is now working for me.
You could try the following
global $wpdb;
$ids = $wpdb->get_col('SELECT `user_id` FROM `' . $wpdb->prefix . 'usermeta` WHERE `meta_key` = \'wp_user_level\' AND `meta_value` < 8;');
if (count($ids) > 0)
{
foreach ($ids as $id)
{
if (wp_delete_user($id))
{
echo 'User deleted' . $id;
echo '<br>';
}
}
}
Use this table as reference for user levels
For WordPress multisite, you can remove a user quite simply from the SQL command line.
In the example below, the user_id is 838 and the site # is 20:
delete from wp_usermeta where user_id = 838 and meta_key in ('wp_20_capabilities', 'wp_20_user_level');
That's it!
This is what I use to delete user along with the metadata.
global $wpdb;
$user_id = "123"; // User id is 123
// Delete User metadata
$wpdb->delete($wpdb->usermeta, ['user_id' => $user_id], ['%d']);
// Delete User
$wpdb->delete($wpdb->users, ['ID' => $user_id], ['%d']);
So i am using a custom Login form with php using Sessions i would like to know how i can implement this into wordpress.
I have changed the database object to wpdb method successfully however i am now wondering how to implement the session on wordpress?
Is there a specific way or can i just create a session variable and check for that variable isset on the redirect page?
This is my current php login code without wpdb keep in mind i wont be using the classes:
$database = new MySQL();
$session = new Session($database);
$msg = '';
$msgl = '';
$msgemail = '';
$message = '';
if (isset($_POST['login']) && $session->isLogged == false) {
$email = $database->escapeString($_POST['user_email']);
$pass = sha1($database->escapeString($_POST['user_pass']));
$result = $database->executeQuery("SELECT user_id, user_type from `user-tbl` WHERE `billing_email`='$email' AND `account_password`='$pass'");
if ($database->numRows($result) == 1) {
$row = $database->fetchResult($result);
$_SESSION['account_id'] = $row['user_id'];
$_SESSION['account_type'] = $row['user_type'];
$_SESSION['security'] = hash('md5', $_SERVER['HTTP_USER_AGENT']);
if (isset($_POST['store'])) {
$_SESSION['store'] = 1;
$session->storeCookie();
} else {
$_SESSION['store'] = 0;
}
$location = 'Location: ';
if ($row['user_type'] == "customer") {
$location .= '/account.php';
} elseif ($row['user_type'] == "admin") {
$location .= '/admin/account.php';
} elseif ($row['user_type'] == "employee") {
$location .= '/employee/account.php';
}
header($location, true);
} else {
$msg = "Please Enter Correct E-mail OR Password.";
}
}
Thanks for your input!
I have a site that is using both WordPress and Opencart. The main site is built off of WP and then there is an OC site in a sub-directory.
I would like to bring the session data from OC into the wordpress site so I can have the Wishlist, Shopping Cart, Checkout, Login status and My Account info throughout the site.
Does anyone know what code I can add to WP to bring in this info?
Thanks again in advance,
Matt
There are already many articles regarding module development and export and session building in OpenCart.
Given your existing pages:
yoursite.com/wordpress
yoursite.com/wordpress/page.php (i.e. your page outside the shop),
yoursite.com/products/catalog/controller/common/header.php -and-
yoursite/products/catalog/view/theme/default/template/common/header.tpl
1. Create file headerXYZ.php using the following code and save it to the root directory of your main site (or other location of your choosing outside your OC shop).
<?php
// Config
require_once('shop/config.php');
// VirtualQMOD
require_once('shop/vqmod/vqmod.php');
$vqmod = new VQMod();
// VQMODDED Startup
require_once($vqmod->modCheck(DIR_SYSTEM . 'startup.php'));
// Application Classes
require_once($vqmod->modCheck(DIR_SYSTEM . 'library/customer.php'));
require_once($vqmod->modCheck(DIR_SYSTEM . 'library/affiliate.php'));
require_once($vqmod->modCheck(DIR_SYSTEM . 'library/currency.php'));
require_once($vqmod->modCheck(DIR_SYSTEM . 'library/tax.php'));
require_once($vqmod->modCheck(DIR_SYSTEM . 'library/weight.php'));
require_once($vqmod->modCheck(DIR_SYSTEM . 'library/length.php'));
require_once($vqmod->modCheck(DIR_SYSTEM . 'library/cart.php'));
$myVar = array();
$myVar = array();
// Registry
$registry = new Registry();
// Loader
$loader = new Loader($registry);
$registry->set('load', $loader);
// Config
$config = new Config();
$registry->set('config', $config);
// Database
$db = new DB(DB_DRIVER, DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
$registry->set('db', $db);
// Url
$url = new Url($config->get('config_url'), $config->get('config_use_ssl') ? $config->get('config_ssl') :
$config->get('config_url'));
$registry->set('url', $url);
// Log
$log = new Log($config->get('config_error_filename'));
$registry->set('log', $log);
function error_handler($errno, $errstr, $errfile, $errline) {
global $log, $config;
switch ($errno) {
case E_NOTICE:
case E_USER_NOTICE:
$error = 'Notice';
break;
case E_WARNING:
case E_USER_WARNING:
$error = 'Warning';
break;
case E_ERROR:
case E_USER_ERROR:
$error = 'Fatal Error';
break;
default:
$error = 'Unknown';
break;
}
if ($config->get('config_error_display')) {
echo '<b>' . $error . '</b>: ' . $errstr . ' in <b>' . $errfile . '</b> on line <b>' . $errline . '</b>';
}
if ($config->get('config_error_log')) {
$log->write('PHP ' . $error . ': ' . $errstr . ' in ' . $errfile . ' on line ' . $errline);
}
return true;
}
// Error Handler
set_error_handler('error_handler');
// Request
$request = new Request();
$registry->set('request', $request);
// Response
$response = new Response();
$response->addHeader('Content-Type: text/html; charset=utf-8');
$response->setCompression($config->get('config_compression'));
$registry->set('response', $response);
// Cache
$cache = new Cache();
$registry->set('cache', $cache);
// Session
$session = new Session();
$registry->set('session', $session);
// Language Detection
$languages = array();
$query = $db->query("SELECT * FROM " . DB_PREFIX . "language");
foreach ($query->rows as $result) {
$languages[$result['code']] = $result;
}
$detect = '';
if (isset($request->server['HTTP_ACCEPT_LANGUAGE']) && ($request->server['HTTP_ACCEPT_LANGUAGE'])) {
$browser_languages = explode(',', $request->server['HTTP_ACCEPT_LANGUAGE']);
foreach ($browser_languages as $browser_language) {
foreach ($languages as $key => $value) {
if ($value['status']) {
$locale = explode(',', $value['locale']);
if (in_array($browser_language, $locale)) {
$detect = $key;
}
}
}
}
}
if (isset($request->get['language']) && array_key_exists($request->get['language'], $languages) &&
$languages[$request->get['language']]['status']) {
$code = $request->get['language'];
} elseif (isset($session->data['language']) && array_key_exists($session->data['language'], $languages)) {
$code = $session->data['language'];
} elseif (isset($request->cookie['language']) && array_key_exists($request->cookie['language'], $languages)) {
$code = $request->cookie['language'];
} elseif ($detect) {
$code = $detect;
} else {
$code = $config->get('config_language');
}
if (!isset($session->data['language']) || $session->data['language'] != $code) {
$session->data['language'] = $code;
}
if (!isset($request->cookie['language']) || $request->cookie['language'] != $code) {
setcookie('language', $code, time() + 60 * 60 * 24 * 30, '/', $request->server['HTTP_HOST']);
}
$config->set('config_language_id', $languages[$code]['language_id']);
$config->set('config_language', $languages[$code]['code']);
// Language
$language = new Language($languages[$code]['directory']);
$language->load($languages[$code]['filename']);
$registry->set('language', $language);
// Document
$document = new Document();
$registry->set('document', $document);
// Customer
$registry->set('customer', new Customer($registry));
// Affiliate
$affiliate = new Affiliate($registry);
$registry->set('affiliate', $affiliate);
if (isset($request->get['tracking']) && !isset($request->cookie['tracking'])) {
setcookie('tracking', $request->get['tracking'], time() + 3600 * 24 * 1000, '/');
}
// Currency
$registry->set('currency', new Currency($registry));
// Tax
$tax = new Tax($registry);
$registry->set('tax', $tax);
// Weight
$registry->set('weight', new Weight($registry));
// Length
$registry->set('length', new Length($registry));
// Cart
$registry->set('cart', new Cart($registry));
// Front Controller
$controller = new Front($registry);
// Maintenance Mode
$controller->addPreAction(new Action('common/maintenance'));
// SEO URL's
$controller->addPreAction(new Action('common/seo_url'));
// Router
if (isset($request->get['route'])) {
$action = new Action($request->get['route']);
} else {
$action = new Action('common/home');
}
// Dispatch
$controller->dispatch($action, new Action('error/not_found'));
2. Now, include headerXYZ.php in page.php i.e. Place the statement below on line 1 at the very top of page.php
<?php require_once ('headerXYZ.php');?>
3. Finally, right after the opening body tag of your external page.php page add the following list of statements
<?php
require_once('shop/catalog/model/total/sub_total.php');
require_once('shop/catalog/language/english/total/sub_total.php');
require_once('shop/catalog/model/total/reward.php');
require_once('shop/catalog/model/total/shipping.php');
require_once('shop/catalog/model/total/coupon.php');
require_once('shop/catalog/model/total/tax.php');
require_once('shop/catalog/model/total/credit.php');
require_once('shop/catalog/language/english/total/credit.php');
require_once('shop/catalog/model/total/voucher.php');
require_once('shop/catalog/model/total/total.php');
require_once('shop/catalog/language/english/total/total.php');
foreach($myVar as $key=>$value)
{
$$key = $value;
}
require_once('shop/catalog/controller/common/header.php');
require_once('shop/catalog/view/theme/default/template/common/header.tpl');
?>
That's it... You're done! You should now have a fully functional header (with working cart, login, etc.) in your page located outside of your Opencart shop.
SIDE NOTE: You could also just plug the entire code (including the content of headerXYZ.php and the 13 require_once statements) directly into the your external page.
I was looking for something similar, what I did was to write same html/css for footer and header in both systems, after that, I wrote an additional Wordpress plugin to show user and cart info when user is logged in opencart.
https://github.com/saRca/op2wp
I need to get the newsletter subscription thing working. The logic i am using is when the user submits his email, i check if there is already a user registered to the site with the email. If yes, i check if he is subscribed to newsletter and do the appropriate subscription. If the email is not in the registered user list, then i have a newsletter table for anonymous users. I check here if he is subscribed or not and do the necessary action.
Here is my controller action code:
/**
* #Route("/newsletter/", name="site_newsletter")
* #return array
*/
public function newsletterSubscriptionAction(httpRequest $request)
{
$email = $request->request->get('email');
try {
$email = $request->request->get('email');
$em = $this->getDoctrine()->getEntityManager();
$query = $em->createQuery(
'SELECT u FROM MyBundle:User u WHERE u.email = :email'
)->setParameter('email', $email);
$user = $query->getSingleResult();
if(!is_object($user)){ //this means anonymous user not registered to site
$em = $this->getDoctrine()->getEntityManager();
$query = $em->createQuery(
'SELECT n FROM MyBundle:Newsletter n WHERE n.email = :email AND n.isSubscribed = 1'
)->setParameter('email', $email);
$record = $query->getSingleResult();
if($record){
$msg = "You are already subscribed!";
}else{
$newsletter = new Newsletter();
$newsletter->setEmail($email);
$newsletter->setIsSubscribed(true);
$em = $this->getDoctrine()->getEntityManager();
$em->persist($newsletter);
$em->flush();
$msg = "You have been subscribed to our newsletter! Thank You.";
}
}else{
if($user->getNewsletterSubscription()){
$msg = "You are already subscribed!";
}else{
$user->setNewsletterSubscription(1);
$em = $this->getDoctrine()->getEntityManager();
$em->flush();
$msg = "You have been subscribed to our newsletter! Thank You.";
}
}
}
catch (\Exception $e) {
$msg = 'Some problem occured. Please try again later';
}
if ($this->getRequest()->isXmlHttpRequest()) {
return new \Symfony\Component\HttpFoundation\Response($msg);
return array('msg' => $msg);
}
}
I am using ajax to call this controller action. This isn't working. The data m getting back to the ajax is redirected login page.
I am using FOSUSerBundle by the way to manage users. Is this causing any issue? Whats the best way to implement it?
Thanks in advance!
It sounds like you need to give anon users permission to use your subscription route.
In your security.yml file, add something like:
security:
access_control:
- { path: ^/subscribe, roles: IS_AUTHENTICATED_ANONYMOUSLY }