Drupal 7: Lock/Password protect our site from anonymous users and add login/register block

There are a few ways to do this, probably the most common way is to put your site in maintenance mode and edit maintenance-page.tpl.php. This method works well and can produce the desired results, however, it’s not the proper way of doing things. What if you still want to have the use of maintenance mode for it’s intended purposes. Well this could still work, but you’re going to have to fiddle with the permissions each time. Also the maintenance mode message will appear on your site, so that will have to be removed and if you want it back, you’re going to have to edit code.

Here is another way, without having to fiddle around with any backend code.

  • Make sure PHP filter is enabled in the modules
  • Create a new block
  • Enter your template information in there, here is an example based on a bootstrap design

<div class="container">
  <div class="row">
    <div class="panel panel-default">
      <div class="panel-heading">
        <h3 class="panel-title">Access Denied - Please Login or Register</h3>
      </div>
      <div class="panel-body">
        <div class="row">
          <div class="col-sm-6">
            <h3> Login </h3>
            <hr>
            <?php 
              $loginForm = drupal_get_form('user_login');
              print drupal_render($loginForm); 
            ?>
          </div>
          <div class="col-sm-6">
            <h3> Register </h3>
            <hr>
            <?php 
              $registerForm = drupal_get_form('user_register_form');
              print drupal_render($registerForm); 
            ?>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
  • Set the text format to “PHP”
  • Go to Visibility Settings > Pages > Pages on which this PHP code returns TRUE
  • Enter this code:

<?php
  global $user;
  $url = $_SERVER['REQUEST_URI'];
  if ($user->uid || strpos($url,'user')) {
    return false;
  }
  else {
    return true;
  }
?>
  • Save block
  • Place the block into the content region and save the changes.
  • Go to permissions and change the Node permission - View published content for anonymous users. Uncheck the box.

Done.

Drupal and Drush: Import/Export SQL Database with Drush

Moving sites from one server to another can be a tedious task, however with command line and drush we can simplify this task into a few easy steps.

Export the database

# drush cc all && drush cc all
# drush sql-dump > /tmp/website-dump.sql

Clearing the cache first removes unwanted cached tables which make the SQL file quite large and can also cause problems on import with the “MySQL Server Gone Away” errors

Copy the database over to your other server

You can use whatever method you like (FTP, etc) but to keep things on the command line, let’s use secure copy.

# scp /tmp/website-dump.sql dest_username@dest_host:/tmp/website-dump.sql

If the site you wish to import to is on the same server, you can skip the step above

Use drush to import the database

Navigate to your drupal install and run “drush status” to make sure the database connection is there.

# drush sql-drop
# drush sql-cli < /tmp/website-dump.sql

Done.

Responsive Twitter Widget

Grab your twitter widget.

Add this to your CSS file.

.twitter-widget-0 {
  width: 100%;
}

Done.

Drupal 7: Basic Drush Commands

If you have SSH (command line access) to your Drupal website, then drush is a must.  Here are a few of my favourite and most useful Drush commands.

1. Clearing the cache with drush

When developing clearing the cache can save a lot of headaches, however doing it through the user interface takes it’s time and using drush helps to speed up this process.

drush cc all

It is also possible to pick the specific cache you wish to clear but most of the time I am using this command in development and clearing all the caches works perfectly.

2. Downloading and enabling modules with drush

This is one of the best features of drush and probably the most used

drush dl <project_name> -y

drush en <project_name> -y

It is also possible to specify the version you wish to download, for example if you are looking for the development version

drush dl <project_name>-7.x-1.x-dev -y

3. Disabling and uninstalling modules with drush

Another feature which allows quick disabling of modules including their dependencies all in one line

drush dis <project_name> -y

drush pm-uninstall <project_name> -y

Don’t forget you can chain commands together in the normal bash way

drush dis <project_name> && drush pm-uninstall <project_name> && drush updb && drush cc all && rm -rf path/to/project/folder

4. Resetting user passwords with drush

Sometimes you need to reset passwords for specific users or even the admin password, in Drupal 7, passwords are salted and must be created with the password script, where in Drupal 6, the passwords were just a MD5 hash. Thankfully drush has a command to automate the whole process

drush upwd <username> --password

Another useful feature is generating a password reset link

drush uli <username>

5. Setting maintenance mode with drush

The vset command allows you to modify variables in the variable table from the command line, it follows this general rule

drush vset <variable_name> <value>

Which means to change the maintenance_mode variable on, we use this command

drush vset maintenance_mode 1

To change the maintenance_mode variable off, we use this command

drush vset maintenance_mode 0

6. Changing the default theme with drush

Have you ever blown up your site with a bad change but need to get into the interface so you can change something back? Well whatever reason you have where you need to change the default theme, this command can save lives.

drush vset theme_default <theme_name>

The theme must be enabled, but you can do with with the drush en command listed above.

7. List all enabled modules, exclude core with drush

drush pml --status=enabled --type=module
drush pml --status=enabled --type=module --no-core

8. MySQL dump with drush

Perform a mysqldump (or equivalent) of the connected drupal database into a .sql file

drush sql-dump --result-file=/home/user/dump.sql

9. Backup and restore sites with drush

You backup your site into a single archive file, and then restore it with these simple commands

drush archive-dump --destination=/home/user/backup.tar.gz

drush archive-restore /home/user/backup.tar.gz

10. Update drush with drush

A very simple command to get the latest version of drush

drush self-update

For a full list of commands, check out http://drush.ws/

The Mental Benefits of the Foot Massage

I’m not talking about some sort of holistic magic on how massaging a certain part of your foot cures another part of your body.  I can’t attest to that, but what I can say is in this busy world where we are lives are filled with plethora of stimuli, we need some time to disconnect.

You can disconnect but not entirely, enter Pocket, my favourite web clipper for reading web articles later.  The biggest issue most people find with Pocket and other web clippers is that you clip articles and never get a chance to read them. Your reading list piles up and never gets emptied.  Finding that time to just sit and read can be difficult but that is where I have found foot massages.

I’ll let you know that I am currently in Thailand and foot massages are cheap as chips, literally.  A foot massage can run you anywhere between 50 baht to 150 baht (a few dollars) depending on how long and where you go.  That being said foot massages anywhere can really be worth it if you get the value out of it like I do.  I use them to take a break from work, and relax, but I also bring my phone to catch up on my web readings.

A foot massage on it’s own can be very relaxing and feel great, but I get bored sitting there for 30 minutes to and hour so I decided one day to pop out my phone and catch up on my readings.  I’ve never felt such a moment where I was totally removed from the rest of the world and could entirely focus on my reading.  Even when I read on my computer I am distracted and it turns more into a skimming session.

Moral of the story is take advantage of your breaks; relax and get some reading done.  After an hour long foot massage you will be refocus, more relaxed and ready to get on with the rest of your day.  I believe in the biz they call that one a double whammy.

Tutorial: Free Drupal 7 Web Server on Amazon Web Services (AWS) Elastic Compute Cloud (EC2)

Prerequisites

  • Amazon account
  • A terminal – (PuTTY is recommended for Windows users)

Getting Started

Sign into your Amazon account and go to the AWS console page.  Click on “EC2″

ec2_console_click

Security Groups

Next we want to create a new “Security Group” for your future EC2 instance.

ec2_security_group_click

Then click on the “Create Security Group” button.

ec2_create_security_group

In the popup, enter your new group name and description. I’ve chosen the name and description to be “Drupal 7 Web Group”. Then click “Yes, Create”.

ec2_security_group_create

Once the group has been created, we need to allow for HTTP/HTTPS/SSL traffic to be allowed by creating inbound firewall exceptions for this security group. Select the newly created security group, and at the bottom of the page, switch the tab over to “Inbound”.

ec2_security_inbound_click

From the drop down list select “SSH”.

ec2_security_ssh

Click “Add Rule”.

ec2_add_ssh

Repeat these steps for HTTP, HTTPS, and any other protocols you might be using, however SSH and HTTP are required. MYSQL is not required unless you will have other external servers accessing the MySQL server hosted on your new EC2 instance.

ec2_finished_ruled

Now you must apply the changes, for the changes to be saved.

ec2_apply_rule_changes

After the changes have been applied, we need to create a new “Key Pair”, so select “Key Pairs” from the sidebar.

ec2_key_pairs

Choose the button at the top, “Create Key Pair”.

ec2_create_new_key_pair

Enter a new name for the key pair, I chose, “Drupal7WebGroup”.

ec2_drupal7_key_pair

Then choose, “Create”.

ec2_drupal7_key_pair_loading

ec2_drupal7_key_pair_done

The key file (.pem) should automatically be downloaded by your browser. You are going to want to keep this file in a safe place, we will be using it later.

ec2_drupal7_key_pair_downloaded

Creating An EC2 Instance

On the sidebar, choose “Instances”

ec2_instances_click

Then choose the button to “Launch Instance”.

ec2_launch_instance

Stick the with default, “Classic Wizard” and choose “Continue”.

ec2_classic_wizard

Here you have a choice on which Amazon Machine Image (AMI) you wish to use. If you are familiar enough with Linux they choose your favourite flavour, but for the purposes of this tutorial, I am going to choose, “Ubuntu Server 12.10 64-bit”.

ec2_ubuntu

On the next page, we get a choice of hardware. If you just signed up for Amazon Web Services (AWS), you are eligible for a free year of micro hosting on the lowest tier. It’s a great place to start and has enough resources to run a small Drupal 7 without any problems. I recommend the lowest tier if you’re just starting out, you can always upgrade it later with no problems.

ec2_free_micro_instance

You can leave the rest of the settings default, or change them as you see it, then choose “Continue”.

ec2_default_instance_settings

The next page allows for some more configuration, but the default settings will work just fine, choose “Continue”.

ec2_instance_details_default

The next page is an overview of the storage device configuration, nothing to do here but click “Continue”.

ec2_confirmation_page

Now you want to name your instance, for this tutorial, we will name it “Drupal 7 Web Server”, then press “Continue”.

ec2_naming_the_instance

Now we get to apply the key pair we created earlier to this instance. Select the key pair you created earlier, then press “Continue”.

ec2_choosing_the_key_pair

Next we choose our existing security group that we created earlier, then press “Continue”.

ec2_choose_existing_security_group

Our instance is complete, and here is the overview page. Choose “Launch” to launch the instance.

ec2_launch_instance

Assigning an Elastic IP to Your EC2 Instance

On the sidebar, choose “Elastic IPs”.

ec2_elastic_ip_click

Then choose the button at the top to “Allocate New Address”.

ec2_allocate_new_address_button

Choose “EC2″ and click “Yes, Allocate”.

ec2_associate_address

Select the new Elastic IP address from the list, and choose the button at the top, “Associate Address”. Then choose the new web server in the select box, and click, “Yes, Allocate”.

ec2_allocate_new_address_select

Converting Your Private Key (.pem) File to PuTTY’s Private Key (.ppk) File

Now that we have a IP associated with the instance we can connect over SSH, however if we are using PuTTY we need to convert that .pem key file to a .ppk file that works with PuTTY, so let’s open the program PuTTYgen.exe

Choose “Load” and find your .pem file that was saved early when creating key pairs.

puttygen_load

Change the file type at the bottom to “All Files (*.*)” and then find the .pem file you saved earlier. Choose “Open”.

puttygen_import

Now save this file to a safe place by clicking the button, “Save private key”. Ignore the warning about the passphrase.

puttygen_save_ppk

Connecting Over SSH to Your New EC2 Instance with PuTTY

Open PuTTY, and in the Host Name (or IP Address), enter in “ubuntu@ip_address” where the IP address is the elastic IP that we assigned to the instance earlier.

putty_ip_address

Then in the left panel, open “SSH” and select “Auth”. In the “Private key file for authentication” browse for your key and open it.

putty_auth_ppk

Next, go back to the left panel and click “Session” at the top, type a name in the blank field and save your session for later use.

putty_save_session

Now click, “Open”. If everything was done right you should get a pop up that asks you to add the rsa2 key fingerprint. Choose “Yes”.

putty_connect

You are now connected to your server.

Setting up the LAMP Stack (Apache2, PHP5, MySQL5)

Run these commands to get everything set up properly and efficiently

Update the releases

sudo apt-get update

Preform and upgrade on server libraries, Type “Y” at the prompt.

sudo apt-get upgrade
sudo apt-get install lamp-server^ phpmyadmin

Choose “Y” at the prompt to install the packages.

Enter a strong password for the MySQL root user. Twice.

lamp_mysql_password

On the following screen press SPACE, TAB, ENTER.

lamp_apache_setup

For the PHPMYADMIN setup, press , then enter a strong password twice, could be the same as the root password you used before. Twice.

Now we need to enable the Apache modules needed for Drupal.

sudo a2enmod rewrite expires headers

Then restart your apache2 server.

sudo service apache2 restart

Your web server is now configured, install Drupal in /var/www, or else you can create virtual hosts to handle multiple site installations.

Pointing your DNS at your new web server

You need to go to your domain manager and change the A Record to your new server’s Elastic IP address that we set up earlier.

Drupal 7: Node.tpl.php Templating – Rendering Multiple Image Fields

When building a node template in Drupal 7 using the image field may require a little more PHP than rendering a normal field, here are a couple snippits that can be used to properly render each image field where you see fit.

Iterative Approach 1 – Fixed Number of Images

Image field name assumed field_image and there are a possible 6 images to be displayed. Gathering the images into an array to be displayed later. I like to separate this from gathering step from the actual rendering of the images.


<?php
$images = array();
$images[0] = render($content['field_image']['0']);
$images[1] = render($content['field_image']['1']);
$images[2] = render($content['field_image']['2']);
$images[3] = render($content['field_image']['3']);
$images[4] = render($content['field_image']['4']);
$images[5] = render($content['field_image']['5']);
?>

Next you can display the images anywhere you want in the template file by echoing/printing each image if it exists. Something like this, I added in the extra div classes to show how to add new classes around each image.


<?php if (!empty($images[0])) { echo '<div class="active item" data-slide-number="0">'; echo $images[0]; echo '</div>'; } ?>
<?php if (!empty($images[1])) { echo '<div class="item" data-slide-number="1">'; echo $images[1]; echo '</div>'; } ?>
<?php if (!empty($images[2])) { echo '<div class="item" data-slide-number="2">'; echo $images[2]; echo '</div>'; } ?>
<?php if (!empty($images[3])) { echo '<div class="item" data-slide-number="3">'; echo $images[3]; echo '</div>'; } ?>
<?php if (!empty($images[4])) { echo '<div class="item" data-slide-number="4">'; echo $images[4]; echo '</div>'; } ?>
<?php if (!empty($images[5])) { echo '<div class="item" data-slide-number="5">'; echo $images[5]; echo '</div>'; } ?>

The main problem with this approach is it’s slightly less scalable as the next approach, if you have more than six images, you’ll have to add a few more lines of code, repeating the process. Not really conforming with the DRY programming paradigm.

Iterative Approach 2 – Any Number of Images

Image field name assumed field_image


<?php
$images = array();
$i = 0;
foreach ($content['field_image'] as $image) {
  $images[$i] = render($image);
  $i++;
}
?>

Next we can echo/print each image as before, using the same principles as above or echo/print each image individually.


<?php
foreach ($images as $printable) {
  echo $printable;
}
?>

Sven BEARtschi

BEARCHI

I created this bear dressed in a #47 Calgary Flames Sven Baertschi jersey, and it all started on this Reddit thread. Where /u/HKizzle asked for a

…painting of a bear playing hockey and about to take a wrist shot on a pond in the rockies while wearing a Sven Baertshi Flames jersey…

I decided to makes this happen, while I left out some of the finer details, like the Rockies, I believe the essence is still there, and he was quite appreciative, enough to buy me Reddit Gold.

I also tweeted this out to @NHLFlames and @SvenBaertschi to which Sven retweeted it, which helped the tweet take off.

Anyways, just wanted to share this with my fellow Calgary Flames fans, and I hope it gets some more exposure because I would love to see this Sven Bear playing ice hockey all over the place at some point.

Hashtags are useful, get over the stigma

When hashtags are used properly on Twitter, Instragram, Tumblr, and other services they can be powerful.  It can help you gain influence and followers or find other people interested in the same topics as you.  However, there seems to be a social stigma around using hashtags, that I don’t understand.  Being ridiculed by others in your social circles that don’t understand the usefulness of hashtags can be frustrating.   I’m not saying you have to use them but just because your ignorance is in your own way, doesn’t mean you should be voicing your own uninformed opinions.  Such is the way of the Internet I suppose.

Hashtags or generally tagging can not only be beneficial for social services but your own organization tactics in applications like Evernote and Pocket.  Keeping your notes in line using simple tagging techniques has changed my way of thinking about organization.  It’s not longer about a hierarchical structure but free form tagging. I for one accept our new tagging overlords, and you should too.  It’s good for the world.

How To: Fly into Thailand

Here are a few quick notes about getting into Thailand from Canada.  Note this are only my experiences and yours may vary.

Before I left I contacted my locate Thai Consulate and got a triple entry tourist visa.  To do this I filled out their visa form, got a passport photo taken and dated, went to the bank and got a money order for $120 + $7.50 fee, and shipped it to them in an ExpressPost envelope with my valid passport and an extra prepaid return envelope.  I sent it off on Friday, they received it on Monday and I received my visa/passport on Tuesday.  A very quick turn around with no problems.  The placed this very official looking sticker in my passport and that was it. I could now fly into Thailand.

With my particular trip I didn’t know when I was going to return so I only bought a one way ticket.  When I arrived at the Vancouver airport to check in, I was asked if I had any return tickets or proof that I was going to be leaving Thailand in the future. I did not.  Cathay Pacific then told me that I had to purchase another ticket out of the country to conform to Thai immigration laws.  I purchased a random ticket that had the ability to be fully refunded then once I passed immigration I could call and cancel it.  I looked online for information about this, and it appears the airlines do this only to cover their own ass.  Also since I already had my visa this shouldn’t have been necessary.  No harm done, but it does leave a sour taste in your mouth. So just a heads up, if you only have a one-way ticket into Thailand, your airline may force you to buy a return ticket before they allow you to fly.  Even though I was never asked by the customs agent if I had a return.  He just stamped my passport and I was on my way.  All I said to him was “Hello” and “Thank you.”

Good luck!