Categories
jQuery wordpress

Using AJAX in WordPress

In the constructor of your PHP class add the following

		add_action('wp_ajax_send_email_test',array($this,'send_email_test'));
		add_action('wp_ajax_nopriv_send_email_test',array($this,'send_email_test'));

In your enqueue function add the localize script function so you have a variable to use in the js file to call admin-ajax.php

		wp_enqueue_script('traffic-report', '/js/myjsfile.js', array('jquery'), '3.0');
		wp_localize_script('traffic-report', 'script_vars',array( 'AJAXurl' => admin_url( 'admin-ajax.php' ) ) );

Then add the callback functions to the same class

function send_email_test()
{
	//here do whatever you need to do with the data posted from the ajax call
	echo "ok";//anything that gets echo'd will resturn as the result in the javascript ajax function
	wp_die();
}

Then in your js file add the following, assuming you have an element with an ID of #send_mail_test which you click on to call the AJAX request.

	$(document).on("click","#send_email_test",function(e)
	{
		e.preventDefault();
		$.ajax(
		{
			url: script_vars.AJAXurl,
			method: "POST",
			data: {
				'action': 'send_email_test',//PHP function name to call
				'device': iDevice //Data to send to ajax function
			},
			success: function (result)
			{
				if (result)
				{
					console.log(result);
				}
				else
					console.log("result is empty");
			}
		});
	})
Categories
php wordpress

Creating a WordPress Class with Backend and Frontend functionality

Firstly, a bare bones PHP class. Add this in it’s own file, eg mynewclass.php, and include it in functions.php

<?php
class MyNewClassName
{
	public function __construct()
	{

	}
}
$mynewclass=new MyNewClassName();
?>

Now a slightly more sophisticated one to add an admin menu item and page, with page tabs.

<?php
class MyNewClassName
{
	protected $admin_page_url;
	public function __construct()
	{
		$this->admin_page_url="my-new-class";
		add_action("admin_menu",array($this,"my_new_class_admin_menu"));
	}
	function my_new_class_admin_menu()
	{
		add_menu_page("My New Class","My New Class","manage_options",$this->admin_page_url,array($this,"my_new_class_page_contents"),"dashicons-schedule",3);
	}
	function my_new_class_page_contents()
	{
		$default_tab = 'general';
		$tab = isset($_GET['tab']) ? $_GET['tab'] : $default_tab;
		echo "<div class='wrap'>";
		echo "<h1>".esc_html( get_admin_page_title())."</h1>";
		echo '<nav class="nav-tab-wrapper">';
		?>
			<a href="?page=<?php echo $this->admin_page_url;?>&tab=general" class="nav-tab <?php if($tab==='general'):?>nav-tab-active<?php endif; ?>">General</a>
		<?php
   		echo '</nav>';
   		echo '<div class="tab-content">';
   		switch($tab) :
   			case 'general':
   				echo $this->general_tab();
   			break;
	    	default:

   			break;
   		endswitch;
   		echo '</div>';
	}
	function general_tab()
	{
		echo "<div>";
		echo "<p>hello world!</p>";
		echo "</div>";
	}
}
$mynewclass=new MyNewClassName();
?>
Categories
Uncategorized

Ubuntu 22.04 Fix Broken Pipe on apt-get

apt-get -o DPkg::Options::="--force-overwrite" install <package name>

This will force an overwrite.
Categories
Linux localhost Node

Ubuntu 20.04 Node Server on localhost with SSL

To get SSL on your localhost for testing purposes you will need a SSL key and certificate generated. I do the following in a certs directory to call up later in the node server app.

openssl genrsa -des3 -out rootCA.key 2048
openssl req -x509 -new -nodes -key rootCA.key -sha256 -days 1024 -out rootCA.pem

Import the rootCA.pem file into your browser under the ‘Authority‘ tab.

Then create server.cnf as follows

[req]
default_bits = 2048
prompt = no
default_md = sha256
distinguished_name = dn

[dn]
C=US
ST=RandomState
L=RandomCity
O=RandomOrganization
OU=RandomOrganizationUnit
emailAddress=hello@example.com
CN = localhost

… and v3.ext as follows

authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
subjectAltName = @alt_names

[alt_names]
DNS.1 = localhost

Using the above config files you can create the server key and certificate with the following

openssl req -new -sha256 -nodes -out server.csr -newkey rsa:2048 -keyout server.key -config <( cat server.csr.cnf )

openssl x509 -req -in server.csr -CA rootCA.pem -CAkey rootCA.key -CAcreateserial -out server.crt -days 500 -sha256 -extfile v3.ext

Now you can start the server with npm start or node server.js, with server.js as follows (basic example)

const express = require('express')
const app = express()
const https = require('https')
const fs = require('fs')
const port = 3000

app.get('/', (req, res) => {
  res.send('WORKING!')
})

const httpsOptions = {
  key: fs.readFileSync('./certs/server.key'),
  cert: fs.readFileSync('./certs/server.csr')
}
const server = https.createServer(httpsOptions, app).listen(port, () => {
  console.log('server running at ' + port)
})

Open your browser and go to https://localhost:3000 and all should be good.

Categories
Linux Node npm

Installing Node on Ubuntu 20.04

Step 1 Do the usual first, i.e.

sudo apt update

and

sudo apt upgrade

Step 2 Make sure npm is up to date as well

npm cache clean -f
npm install -g n #if not already installed
sudo n stable

It might take some doing to achieve the above, as I had a few issues to deal with ion Ubuntu 20..04 Firstly I had to update npm and node :

curl -fsSL https://deb.nodesource.com/setup_16.x | sudo -E bash -
sudo apt-get install -y nodejs

Then I had to change the permissions on the node modules directory

sudo chown -R $USER /usr/local/lib/node_modules

Only then could I get sudo npm install -g to work as intended.

Categories
MySql wordpress

SQL to extract order report

SELECT pm.meta_value AS city,p.ID as order_id,p.post_excerpt as
customer_note,p.post_date as order_date,pm2.meta_value as
suburb,pm3.meta_value as customer_id,
pm4.meta_value as sender_email,
pm5.meta_value as sender_firstname,
pm6.meta_value as sender_lastname
FROM wp_posts p
LEFT JOIN wp_postmeta pm ON p.ID = pm.post_id
LEFT JOIN wp_postmeta pm2 ON p.ID = pm2.post_id
LEFT JOIN wp_postmeta pm3 ON p.ID = pm3.post_id
LEFT JOIN wp_postmeta pm4 ON p.ID = pm4.post_id
LEFT JOIN wp_postmeta pm5 ON p.ID = pm5.post_id
LEFT JOIN wp_postmeta pm6 ON p.ID = pm6.post_id
WHERE p.post_type='shop_order'
AND p.post_status='wc-completed'
AND pm.meta_key='_shipping_address_2' AND pm.meta_value='Durban'
AND pm2.meta_key='_shipping_city'
AND pm3.meta_key='_customer_user'
AND pm4.meta_key='_billing_email'
AND pm5.meta_key='_billing_first_name'
AND pm6.meta_key='_billing_last_name'
ORDER BY p.post_date DESC

This SQL string will extract multiple meta values from an order.

Categories
Linux

Ubuntu 18.04 Disable Auto Time Updates

Firstly disable automatic times

timedatectl set-ntp off

Then simple set the time manualy, or the time itself will still automatically update.

sudo date --set "21 Dec 2020 14:42:00"

To re-enable automatic date/time updates use

timedatectl set-ntp on

To check the status use

timedatectl status

You should see something like below. the three ‘no’ mean it’s disabled.

Local time: Mon 2020-12-21 15:00:02 SAST
Universal time: Mon 2020-12-21 13:00:02 UTC
RTC time: Mon 2020-12-21 12:56:50
Time zone: Africa/Johannesburg (SAST, +0200)
System clock synchronized: no
systemd-timesyncd.service active: no
RTC in local TZ: no
Categories
Linux

Cleaning Ubuntu boot partition

Often the Ubuntu upgrades will fail fue to a no space error. The only solution is to remove old kernels manually.

The first step is to show which kernel you are currently running, as you do not want to delete this one.

sudo su
uname -r

So change to the boot directory for simplicity and list all existing kernels on the system.

cd /boot
ls -al

Then you can remove the older kernels…

apt remove linux-image-4.15.0-99-genericapt remove linux-image-4.15.0-99-generic

… and clean up.

apt --purge autoremove

You can retry the upgrade

apt full upgrade

Categories
php Plugin wordpress

WP REST with JWT

Using the WordPress REST API with JWT authentication

Step 1. Install this plugin => https://wordpress.org/plugins/advanced-access-manager/. The free version will suffice. This goes on the site you will be xtracting data from. The REST API must be enabled in the WordPress settings.

Step 2. Configure the plugin and on it’s Settings tab add the Secret as per this page => https://aamplugin.com/article/how-to-authenticate-wordpress-user-with-jwt-token

On the Page pulling the data from the above server, use the following PHP code :

function getToken()
{
	$token="";
	$html="<div>";
	
	$postRequest = array(
		'username' => 'ANY_ADMIN_USERNAME',
		'password' => 'THE_PASSWORD_FOR_SAID_USER'
	);
	$h=http_build_query($postRequest);
	$ch = curl_init("https://YOUR_SERVER_NAME.COM/wp-json/aam/v1/authenticate");
	curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS,$h);
	curl_setopt($ch, CURLOPT_FAILONERROR, true);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_VERBOSE, true);
	
    $server_output = curl_exec ($ch);
	$info = curl_getinfo($ch);
	//$html="<pre>".print_r($info,true)."</pre>";
	//echo $html;
    if ($server_output === false)
	{
        die('Error getting JWT token on WordPress for API integration.');
    }
    $server_output = json_decode($server_output);

    if ($server_output === null && json_last_error() !== JSON_ERROR_NONE)
	{
        die('Invalid response getting JWT token on WordPress for API integration.');
    }
    if (!empty($server_output->token))
	{
        $token = $server_output->token; # Token is here
        curl_close ($ch);
        return $token;
    }
	else
	{
        die('Invalid response getting JWT token on WordPress for API integration.');
    }
    return false;
}

The when you need the token, call it like such :

$mytoken=getToken();

And that’s about it…..

Categories
Linux wordpress

WordPress Security

This applies to self-managed Apache2 servers. Shared servers require different permissions, for example wp-config : set that file’s permissions to 440 or 400.

Site Lockdown

File permissions to lock down website, from the websites home folder. Do this from the root directory for example and you will break your server.


chown root:root  -R * 
find . -type d -exec chmod 755 {} \;
find . -type f -exec chmod 644 {} \;

Change the folder ownership of the site to root

chown root:root -R * 

Change to wp-content/uploads (to allow uploads)

chown www-data:www-data -R * 

To edit any files via ftp change that ownership to the ftpuser:wwwdata

chown username:www-data -R * 

If you get asked for ftp details when trying to upgrade wordpress, or any plugins or themes, you need to add the following to wp-config.php

define('FS_METHOD','direct');

Refer to https://wordpress.org/support/article/hardening-wordpress/ for more details, especially those regarding MySql.

On the server install

Denyhosts

Disable root login

Install rkhunter (root kit hunter) to check for vulnerabilities.

sudo apt-get install rkhunter

Perform check with

sudo rkhunter --check --skip-keypress

or on first run

sudo rkhunter --checkall --skip-keypress

And keep it updated with

sudo rkhunter --update

For Ubuntu server you may have to “fix” /etc/rkhunter.conf

UPDATE_MIRRORS=0 to UPDATE_MIRRORS=1
MIRRORS_MODE=1 to MIRRORS_MODE=0
WEB_CMD="/bin/false" to WEB_CMD=""