Scroll to Top Plugin for Koken CMS

I fell in love with the Koken CMS. I discovered it via Reddit, while performing my daily dose of procrastination on /r/web_design and on /r/photography. It’s a beautiful and free CMS designed for photographers, designers, and creative DIYs as they call it. And yeah, the power of this CMS lies in its powerful and elegant management of the media library.

The Koken CMS can be extended using plugins, which use hooks and filters. I tried to search some plugins on the Internet but couldn’t find any besides the GitHub repository for the inbuilt plugins. So, I tried to make my first Koken plugin: The Scroll To Top Plugin.

Installation and Usage:

After downloading the plugin, you will find a folder called rrikesh-scroll-to-top, you should upload this folder to your storage/plugins/ folder in your Koken Installation. You should then proceed to your Koken DashboardSettings → Plugins to activate the plugin.

Koken Plugin List

Koken Plugin List

The plugin is currently disabled. Click on the disabled button to enable the plugin(I don’t really like it that I should click on disabled to enable something). You should then get a message to set up the plugin.

Scroll To Top Plugin enabled

Scroll To Top Plugin enabled

The next step is to click on the setup button. and you’ll land on a page to configure that plugin.

Scroll To Top Plugin -  Settings Page

Scroll To Top Plugin – Settings Page

Write the text you want to appear and hit Save plugin settings. You’re done. Go to your website and scroll down a bit, you should see a Scroll To Top button appearing at the bottom right of your screen. Note that the button will appear only when you have scrolled down.

Scroll To Top button found at the bottom right of the screen.

Scroll To Top button found at the bottom right of the screen.

Applying custom styles to the button

If you look back to the settings page of the plugin, you’ll notice another field called Custom CSS. You can add styles in that field if you want a different style applied on the button. For example, let’s add the following in the Custom CSS field:

background: none repeat scroll 0 0 #d4ceff;
border: 1px solid #b0abd2;
bottom: 10px;
padding: 10px;
position: fixed;
right: 10px;
z-index: 100;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;

Save the settings and reload your page, the Scroll To Top button will now become:

Customised Scroll To Top button

Customised Scroll To Top button

For those wanting to learn how to write plugins, I’ll write a post explaining the codes of the Scroll To Top plugin.

WordPress Lesser Known Function: zeroise()

The WordPress function zeroise() is a very simple and handy function for lazy people, like me. It is also a  self-explaining function with just one line of code with it:

function zeroise($number, $threshold) {
return sprintf('%0'.$threshold.'s', $number);
}

The function returns a number, adding leading zeros in front of it when necessary. I’ve spotted the function in wp-includes/formatting.php some time back and never found the opportunity to use it. Today I got had to code something that will generate an ascending  serial number like 0001, 0002, 0003, etc and zeroise() came to help :)

Reference:
zeroise() on WordPress Codex

How to know when your website has been indexed?

It happens to everyone. We want to put some website or new articles online, and we check regularly when our favorite search engine indexes our pages. But Googling each hour to see if your new content has been indexed is sometimes frustrating. It takes time to index articles on a fresh blog. Since it’s my first blog post here, and I’ll have to set up the notification for this blog, let me share that recipe to you.

Let Google alert you when it indexes your content

Google has a not-so-used service called Google Alerts. Basically, Google Alerts sends you notifications by email whenever a specific event occurs. For our case, we want an alert whenever Google indexes pages from our websites or blogs. If you’re familiar with Google Search you’ll know the usage of site:example.com to get search results only from example.com. So if you set site:yourwebsite.com to alert you, each time your article will be indexed you’ll get an email. So no stressing around checking it yourself.

Setting up the alert

The Google Alerts Screen

Setting up the alert is straight forward. you just add your query which should be site:yourwebsite.com and select how you will be notified. then hit the ‘Create Alert’ button and you’re done.

Happy Blogging!

How to get EXIF data from images using jQuery

While surfing around, I found a great, yet simple to use plugin from Jacob Seidelin. This plugin allows you to get the exif data of images which are on the same domain as your web page.

The plugin usage is very simple too. You will need to add exif=”true” to your <img> tags and of course add both jQuery library and the plugin file. You can find a demo here.

The image tag:


<img src="img1.jpg" id="img1" exif="true" />

Display camera model:


$('img').bind('click', function(){
console.log( $(this).exif('Model') );

//returns the camera model
 });

Display camera make:


$('img').bind('click', function(){
console.log( $(this).exif('Make') );

//returns the camera Make
});

Display all data:


$('img').bind('click', function(){
console.log( $(this).exifPretty() );

//returns all exif data
});

Here’s what I obtained using the exifPretty() function on the image in the demo:


Make : Canon
Model : Canon EOS DIGITAL REBEL XT
Orientation : 1
XResolution : 240
YResolution : 240
ResolutionUnit : 2
Software : Adobe Photoshop CS5 Windows
DateTime : 2012:10:18 21:13:11
Artist : unknown
ExifIFDPointer : 240
ExposureTime : 0.0005
FNumber : 6.3
ExposureProgram : Aperture priority
ISOSpeedRatings : 400
ExifVersion : 0221
DateTimeOriginal : 2012:09:20 13:20:49
DateTimeDigitized : 2012:09:20 13:20:49
ShutterSpeedValue : 10.965784
ApertureValue : 5.310704
ExposureBias : 0
MaxApertureValue : 4.96875
MeteringMode : Pattern
Flash : Flash did not fire, compulsory flash mode
FocalLength : 200
ColorSpace : 65535
PixelXDimension : 200
PixelYDimension : 133
FocalPlaneXResolution : 3954.233409610984
FocalPlaneYResolution : 3958.762886597938
FocalPlaneResolutionUnit : 2
CustomRendered : Normal process
ExposureMode : 0
WhiteBalance : Auto white balance
SceneCaptureType : Standard

You can use any of the labels as argument of the exif() function. For example exif(‘ColorSpace’), exif(‘ExposureTime’), etc…

Click here for a demo!

How to create an administrator account on WordPress using MySQL

Today I had to work on a WordPress website without having an administrator account. I had access to FTP and the WordPress database. I had two options to get in:

1. Change the current administrator password and use his account.

2. Create an account for myself

Changing WordPress administrator password using MySQL

The first choice would have been the quickest. Yet, I would have had to store the current admin password and revert it back to its original value when the job is done. Meanwhile the administrator should have been notified so that he does not freak out because his password wouldn’t be accepted. Anyway, it would have been a single line of SQL:

UPDATE wp_users SET user_pass = md5('new password') WHERE id = '1';

Assumptions:
1. The table prefix is wp_
2. The ID of the current administrator in the table wp_users is 1

For the lazy, you could use phpmyadmin’s tool to edit a row in the table.

Creating an administrator account using MySQL
This gets a bit tricky. You will have to edit two tables to add yourself as a user.

Step 1
Run the query to create a new user:
INSERT INTO wp_users (user_login, user_pass, user_nicename, user_email, user_registered, user_status, display_name)
VALUES
('username', MD5('password'), 'nicename', 'email@example.com', '2012-08-23 00:00:00', '0', 'displayname')

Now if you try to log in, you’ll get stuck with the “You do not have sufficient permissions to access this page.” error. You should also noth the user id that was generated when the row was created.

Step 2
Get some capabilities so that you can access the WordPress dashboard. The first part is to get the capabilities of a current administrator. The following query should do the job:
SELECT *
FROM `wp_usermeta`
WHERE meta_key = 'wp_capabilities'
AND meta_value LIKE '%administrator%'

If you have a fresh install, the meta_value obtained will be something like:

a:1:{s:13:”administrator”;s:1:”1″;}

Whatever it is, just copy it and be ready to use it. You should also note that the user_id obtained will match that of an administrator in the wp_users table.

Step 3

Assign those capabilities to the new user you created. You will need the user id obtained in Step 1 and the meta_value obtained in step 2
INSERT INTO wp_usermeta
(user_id, meta_key, meta_value)
VALUES
('id-from-step-1', 'wp_capabilities', 'a:1:{s:13:"administrator";s:1:"1";}');
INSERT INTO wp_usermeta
(user_id, meta_key, meta_value)
VALUES
('id-from-step-1', 'wp_user_level', '10');

Run these two queries and your account should be available!

How to measure execution time in PHP

Often we need to calculate how much time a script takes to execute, especially when dealing with loops. The microtime() function offered by PHP is suitable for this purpose.

 $start_time = microtime(true);
 //do your stuff here
 $stop_time = microtime(true);
 echo 'time taken: ' . number_format( ($stop_time-$start_time), 2 );

Reference:
microtime() – PHP Manual
number_format() – PHP Manual

htaccess snippets for wordpress

Disable Directory listing

I don’t always like when people see what files are present in my folders or subfolders. Apart from usual images, stylesheets and javascript, I sometimes store some pdf or zip file for my clients. I need to make sure only someone with the actual link can download the file. If there’s only the contents of one folder to hide, I may feel lazy and dump an empty index.php file in it. Anyone trying to browse the folder will get that index.php file to load in their browser.

Note that Apache looks for some predefined filenames whenever you want to browse a folder. For example, it will look for default.html, index.html and then index.php.

But when there are lots of folders in the directory, I use .htaccess to disable folder listing.

Options -Indexes

This is my most commonly used line in my .htaccess file to restrict people from seeing the contents of a folder. An error 403 – Access Forbidden is obtained if someone tries to browse the folder.

IndexIgnore *.pdf *.zip
IndexIgnore *

I use IndexIgnore sometimes whenever I want to hide a specific filetype. IndexIgnore * will hide all files present, but I find it pointless (unless you want to make someone think your directory is empty), I’d use Options -Indexes instead.

Hiding files with .htaccess

To hide zip and pdf files, I use IndexIgnore *.pdf *.zip which hides those files while other file types are shown. Here’s an example below:

DISPLAY COMING SOON PAGE

How do you advertise your new website to people before you finish your website? It might take a few days to finish your new website and test if everything is alright. Or put your website offline for some hours while you update your CMS and test new features?

Meanwhile, you can have a Coming Soon or a Maintenance page that your visitors can see. For example, you can have a page that collects their email address and share links to your social networks so that your visitors can know when the website is up. Another little htaccess snippet is used to implement this. You need to replace the values of xxx.yyy.zzz.aaa by your ip address and also replace coming-soon.php by the page you want the visitors to see.

RewriteEngine on
 RewriteCond %{REQUEST_URI} !/coming-soon.php$
 RewriteCond %{REMOTE_ADDR} !^xxx\.yyy\.zzz\.aaa
 RewriteRule $ /coming-soon.php [R=302,L]

A 302 redirect is used to prevent search engines from indexing your coming-soon page instead of your real pages.

ALLOWING ONLY DEFINED IP ADDRESSES TO ACCESS WP-ADMIN
Want only bunch of users to access your wp-admin? This is possible via htaccess.

AuthUserFile /dev/null
 AuthGroupFile /dev/null
 AuthName "Secured wp-admin Folder"
 AuthType Basic

 order allow, deny
 deny from all
 allow from xxx.yyy.zzz.aaa

But I don’t use this trick because my IP address isn’t static. A more flexible solution is to password-protect my wp-admin folder, as explained in the next section.

PASSWORD PROTECTING WP-ADMIN FOLDER

Password protection is more versatile than limiting the access to only selected IP addresses. However, you shouldn’t consider this method as extremely secure. Your username and password are sent in plain text and can be sniffed by anyone on your network.

AuthUserFile full/path/to/.htpasswd

AuthName "Password-protected wp-admin folder"

AuthType Basic

require valid-user 

The next step is to create an .htpasswd file. If you’ve got an installation of XAMPP, LAMPP, MAMP or whatever substitute, you should have a little program that will help you to create that file.

For example, on Windows. the file htpasswd.exe is located in the apache\bin folder.

  1. Go on the command prompt, and browse to the apache\bin directory.
  2. Then type htpasswd -c .htpasswd your-usernameand hit enter.
  3.  Enter your password, confirn the password. You’re done. Look for the .htpasswd file in that apache\bindirectory.
  4.  Move this file somewhere on your server and add its full path to the AuthUserFile line in your .htaccess file.

You’re done!

WordPress Lesser Known Function: antispambot()

We all know that there are bots/spiders out there that are scraping the web for email addresses. These email addresses obtained are then used as the recipient for spam. And, we don’t like spam, right?

What to do?

There are usually two techniques to counter spam. The first one is to use an image with your email address on that, so that only humans can see the address. The problem with this method is that your visitors can’t simply use that email address. They must manually copy it before using. But since most humans are lazy, this method fails.

A better approach is to encode the email address in such a way that it no more looks like an email address in your source code. Characters from your email address can be replaced by their corresponding HTML ENTITIES. This encoding can be either done using PHP or Javascript.

Doing it with WordPress

WordPress has a built-in function to do this conversion and can be used very easily. The WordPress function antispambot() does that job! You just need to pass your email address as argument and you’re done. And the function does not encode your email the same way each time, I passed the email address rrikesh@example.com as parameter of the function and ran it a few times. Here are the results:

rri%6b%65s%68%40exa%6d%70le.%63om
rrik%65sh@%65%78ampl%65.com
rri%6be%73%68@exam%70le%2e%63om
r%72%69k%65s%68@ex%61%6dple%2e%63%6f%6d
rr%69%6be%73%68@%65%78%61%6dple.%63%6fm
rrikesh@e%78%61mp%6ce.com
rri%6b%65sh@ex%61mple.%63o%6d
%72rike%73h@%65%78ample%2e%63%6fm
r%72%69%6b%65s%68@exam%70l%65%2e%63om

Note that these HTML entities are visible only in the source code, on your website, the email address will appear unencoded.

Using antispambot() in WordPress posts

Whenever you need to display your email address in your theme files, just adding the PHP snippet antispambot(‘my@email.address’) is good. But what if you need to add this address to your posts? You can’t add PHP in that, so let’s make a shortcode for displaying the email address!

Add these to your functions.php file, and change the email address to yours.

function print_my_email_address() {
return antispambot("rrikesh@example.com");
}
add_shortcode( 'print_email', 'print_my_email_address'); 

Now, you can add the shortcode [print_email] to your posts and get your email address printed out with some HTML entities randomly added.

Adding other email addresses to your posts

To be honest, you’re quite stuck with the above shortcode. There’s no flexibility to add another email address. So, let’s modify the above print_my_email_address() function so that it accepts an email address.

function print_my_email_address($email_address) {
extract(shortcode_atts(array
           ('address' => 'rrikesh@example.com'),$email_address));
 return antispambot($address);
}
add_shortcode( 'print_email', 'print_my_email_address'); 

Now we can get more freedom to use other email addresses in our WordPress posts. For example using the shortcode [print_email] will return the default email address rrikesh@example.com and using the shortcode [print_email address="my@new.address] will display my@new.address as email address.

What if you don’t have WordPress?

This function is defined in wp-includes/formatting.php and it’s a very small function. You can literally take that function and place it in your own PHP project. Of course, don’t forget to thank those guys who are working hard to provide us with such a beautiful CMS :)

Reference:
antispambot() on WordPress Codex