Wordpress plugin WP_error - wordpress

I installed ISMS Plugin into my wordpress in order to try out the SMS service through Wordpress. However an error appeared when I click on the iSMS setting on the plugin menu.
Here is the error:
**
Fatal error: Cannot use object of type WP_Error as array in C:\wamp\www\wordpress\wp-content\plugins\isms\isms-model.php on line 17**
and here's the code for line 17:
$result = $response[body];
here is the full code for isms-model.php
<?php
class Mobiweb_ISMS_Model {
// iSMS API
protected static $api_balance = 'https://www.isms.com.my/isms_balance.php';
protected static $api_send = 'https://www.isms.com.my/isms_send.php';
public static function get_balance() {
$username = get_option('setting_username');
$password = get_option('setting_password');
$link = self::$api_balance.'?';
$link .= "un=".urlencode($username);
$link .= "&pwd=".urlencode($password);
$response = wp_remote_get($link);
$result = $response[body];
$balance = (float)$result;
if ($balance < 0) return substr($result, 8);
else return $result;
}
public static function send_isms($destination, $message, $messageType, $senderID = '') {
$username = get_option('setting_username');
$password = get_option('setting_password');
$link = self::$api_send.'?';
$link .= "un=".urlencode($username);
$link .= "&pwd=".urlencode($password);
$link .= "&dstno=".urlencode($destination);
$link .= "&msg=".urlencode($message);
$link .= "&type=".urlencode($messageType);
$link .= "&sendid=".urlencode($senderID);
$response = wp_remote_get($link);
try {
$result = $response[body];
$resultValue = (float)$result;
if ($resultValue < 0) {
return array(
'code'=>$resultValue,
'message'=>substr($result, 8)
);
} else {
return array(
'code'=>'2000',
'message'=>$result
);
}
} catch (Exception $e) {
$message = $e->getMessage();
return array(
'code'=>'-9999',
'message'=>$message
);
}
}
}
?>
What should I do to fix it? Any advise?

This plugin is badly written.
wp_remote_get() returns a WP_Error object when there's an error. Therefore, at least for debugging it and seeing what the error is, I would suggest you change it from:
$response = wp_remote_get($link);
$result = $response[body];
to
$response = wp_remote_get($link);
if (is_wp_error($response)) {
die($response->get_error_message());
}
$result = $response['body'];

Related

How do I output content at the right point from a WordPress plugin?

I'm creating a WordPress plugin for a specific site, which needs to read a feed from another site and display the contents (nicely parsed). The problem I'm having is that I can't figure out how to display the resulting HTML.
I have the following:
Main file (feed-import.php):
/*
Plugin Name: etc
*/
class FeedImport {
private $feedData = "";
private $jsonData;
public function __construct(){
// hook shortcode
add_shortcode('myshortcodename' , array(&$this , 'shortcodeExecute'));
}
// Read shortcode params
public function shortcodeExecute($atts , $content = ""){
if(!class_exists('ParseJSON')) {
require_once plugin_dir_path( __FILE__ ) . 'class-parse-json.php';
}
// Get feed data
$response = wp_remote_get( 'https://feedurl.com' );
if(isset($response['body']) && !empty($response['body'])) {
$this->feedData = $response['body'];
}
// Decode feed data
$this->jsonData = json_decode($this->feedData);
// Parse feed data
$parseJSONObject = new ParseJSON($this->jsonData);
$output = $parseJSONObject->buildHTML();
}
function getOutput() {
return $this->output;
}
}
$feedImport = new FeedImport();
function add_the_feed ( $content ) {
if ( is_page() ) {
return $content . '<p>html content goes here.</p>';
}
}
add_filter( 'the_content', 'add_the_feed');
class-parse-json.php:
class ParseJSON {
private $jsondata = "";
public function __construct($jsonData) {
$this->jsondata = $jsonData;
}
public function buildHTML(){
$html = "<div>";
foreach($this->jsondata as $key => $value) {
$html .= "<div>";
$html .= " <a href='" . $value->html_url . "'>";
$html .= $value->name;
$html .= "</a>";
$html .= " </div>";
}
$html .= "</div>";
return $html;
}
}
(I've left out details of error checking etc for clarity).
This works fine - it adds the text 'html content goes here.' at the end of each page. What I can't figure out is how to replace 'html content goes here' with the actual html content - ie the value of output.
I tried changing add_the_feed to:
function add_the_feed ( $content ) {
if ( is_page() ) {
return $content . $feedImport->getOutput();
}
}
but then I get the error:
Notice: Undefined variable: feedImport
How do I achieve this?
This is a variable scope issue. The add_the_feed() function does not have access to the $feedImport variable. There are two ways to fix this:
Include $feedImport = new FeedImport() in your function.
Use a singleton and create a static instance method (outlined below)
class FeedImport {
/* New Lines */
protected static $_instance = NULL;
public static function instance() {
if ( is_null( self::$_instance ) ) {
self::$_instance = new self();
}
return self::$_instance;
}
/* End New Lines */
public function __construct() {
}
// Read shortcode params
public static function shortcodeExecute($atts = '' , $content = '' ){
if(!class_exists('ParseJSON')) {
require_once plugin_dir_path( __FILE__ ) . 'class-parse-json.php';
}
// Get feed data
$response = wp_remote_get( 'https://feedurl.com' );
if(isset($response['body']) && !empty($response['body'])) {
$feedData = $response['body'];
}
// Decode feed data
$jsonData = json_decode($feedData);
// Parse feed data
$parseJSONObject = new ParseJSON($jsonData);
// Return the data in the shortcode.
return $parseJSONObject->buildHTML();
}
}
// put the short code out of the Class
add_shortcode('myshortcodename' , array( 'FeedImport', 'shortcodeExecute'));

Delete user programmatically in wordpress

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']);

Print data from database to a particular block content

I need to print a simple data from database to a particular block, I have used the code given below and got the text out put but it is not located in the block specified(hello_world).
function hello_world_block_view($delta = '') {
$block = array();
if ($delta == 'hello_world') {
$sql = "SELECT Test_name FROM Test_table";
$result = db_query($sql);
$record = $result->fetch();
foreach ($record as $records) {
echo $records;
}
$block['subject'] = t('Hello world Subject');
$block['content'] = t('Need to print database content');
}
return $block;
}
You need to connect variable $records with $block['content']. So it can looks like:
function hello_world_block_view($delta = '') {
$block = array();
if ($delta == 'hello_world') {
$output = '';
$sql = "SELECT Test_name FROM Test_table";
$result = db_query($sql);
$record = $result->fetch();
foreach ($record as $records) {
$output .= $records;
}
$block['subject'] = t('Hello world Subject');
$block['content'] = $output;
}
return $block;
}

Opencart session info in Wordpress

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

Using the $object in Actions.I've created a module but parameter _action($object) is not work

Using the $object in Actions.
$object: Many actions act on one of Drupal’s built-in objects: nodes, users, taxonomy terms, and so on. When an action is executed by trigger.module, the object that is currently being acted upon is passed along to the action in the $object parameter. For example, if an action is set to execute when a new node is created, the $object parameter will contain the node object.
$object haven't value.i will get node's title and use in code.
function beep_action($object, $context) {
global $user;
//$q_mailfrom = db_query("SELECT mail FROM {users} WHERE uid = '%d'", 1);
// $f_mailfrom = db_fetch_object($q_mailfrom);
$q_mailuser = db_query("SELECT uid, mail FROM {users}");
// $a_mailto=array();
// $i=0;
while($f_mailuser = db_fetch_object($q_mailuser)){
if($f_mailuser->uid==1){
$mailfrom = $f_mailuser->mail;
}
$q_mailer = db_query("SELECT news,proudcts,privilagecard,occassioncard,others FROM {beep} WHERE uid = '%d'", $f_mailuser->uid);
$f_mailer = db_fetch_object($q_mailer);
if($f_mailer->news==1 OR $f_mailer->proudcts==1 OR $f_mailer->privilagecard==1 OR $f_mailer->occassioncard==1 OR $f_mailer->others==1 ){
if($f_mailer->news==1){
$mailto = $f_mailuser->mail;
$subject = "... Group";
$message = "<h2>... Group Latest News </h2>".$object->nid."<br/>Test";
drupal_mail('beep', 'reply', $mailto, language_default(),
array('body' => $message, 'subject' => $subject), $mailfrom, TRUE);
}
// $a_mailto[$i]= $f_mailto->mail;
// $i++;
}
}
}
I see what you want
function MYMODULE_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL){
switch($op){
case 'insert':
if($node->type == 'mytype'){
beep_action($node);
}
break;
}
}
Show call function. What you post in $object ?
And read drupal code stantarts.
function beep_action($object, $context) {
_vdump($object);
global $user;
$default_from = variable_get('site_mail', ini_get('sendmail_from'));
$query = "SELECT user.uid, user.mail FROM {users} user WHERE status <> %d";
$result = db_query($query, 0);
$subject = t("Azaran Mehr Group");
while ($row = db_fetch_object($result)) {
$query = "SELECT beep.news, beep.proudcts, beep.privilagecard, beep.occassioncard, beep.others FROM {beep} beep WHERE uid = %d"; // Do not use ' on integer values
$f_mailer = db_fetch_object(db_query($query, $row->uid));
if ($f_mailer->news == 1 && ($f_mailer->proudcts == 1 || $f_mailer->privilagecard == 1 || $f_mailer->occassioncard == 1 || $f_mailer->others == 1)) {
$message = '<h2>'. t('Azaran Mehr Group Latest News - !nid', array('!nid' => $object->nid)) .'</h2><br/>Test';
drupal_mail('beep', 'reply', $row->mail, language_default(),
array('body' => $message, 'subject' => $subject), $default_from, TRUE);
}
}
}
function _vdump($var, $keys = FALSE) {
if($keys){
drupal_set_message('<pre>' . print_r(array_keys($var), 1) . '</pre>');
}
else {
drupal_set_message('<pre>' . print_r($var, 1) . '</pre>');
}
}

Resources