Drupal

Drupal is an awesome Great Content management system if your webserver has enough resources and you have the technical expertise. It is very customizable and many addons have been written for it. Here you will find tips and thoughts gathered from my experience using drupal.Previous tips were lost in a hard drive crash, bear with us as the content of this site is being rewritten. Tons of new tips coming up... follow @theseobell [sb_child_list]

Interesting Block Snippets

You can for each item click the 'show if following page returns true'. to decide where blocks get displayed

display bock to a particular id

<?php

  global $user;
  if($user->uid == 1 ) {
    return true;
  }
  else
  {
    return false;
  }

display block only to particular node

<?php

$match=FALSE;
$types=array('story' =>1);
if(arg(0)=='node' && is_numeric(arg_(1))) {
  $nid=arg(1);
  $node=node_load(array('nid' => $nid));
  $type=node->type;
  if(isset($types([$type])) {
    $match=true;
  }
}
return $match;
?>

display a block throughout al the forums

<?php
   if(arg(0) == 'forum') {
       return true;
   }
   if(arg(0) == 'node' && ctype_digit(arg(1))) {
      $node =node_loag(arg(1));
      if($node->type == 'blog') {
         return true;
      }
   }
   return false;
?>

 

Basic phptemplate theme creation process

<p>themes are defined by the following steps</p><ul style="margin-left: 40px; "><li>creating a theme directory such as <strong>mytheme/</strong></li><li>adding a theme.info to the theme directory&nbsp;<strong>mytheme/mytheme.info</strong></li><li>adding files you want to override:<ul><li><strong>page.tpl.php</strong> - template for the whole page</li><li><strong>block.tpl.php</strong> - template used to display all blocks</li><li><strong>comment.tpl.php</strong> - template used to display comments</li><li><strong>node.tpl.php</strong> - template used to display each node</li></ul></li><li>in addition, you can add a node number to each of these template name to specify a specific node name.<ul><li><strong>page--1.tpl.php</strong> - will change the page template only for page 1</li><li><strong>comment--1.tpl.php </strong>- will change the template for the first comment</li></ul></li></ul>

Interesting snippets

You can for each item click the 'show if following page returns true'. to decide where blocks get displayed

display bock to a particular id

<?php

  global $user;
  if($user->uid == 1 ) {
    return true;
  }
  else
  {
    return false;
  }

display block only to particular node

<?php

$match=FALSE;
$types=array('story' =>1);
if(arg(0)=='node' && is_numeric(arg_(1))) {
  $nid=arg(1);
  $node=node_load(array('nid' => $nid));
  $type=node->type;
  if(isset($types([$type])) {
    $match=true;
  }
}
return $match;
?>

display a block throughout al the forums

<?php
   if(arg(0) == 'forum') {
       return true;
   }
   if(arg(0) == 'node' && ctype_digit(arg(1))) {
      $node =node_loag(arg(1));
      if($node->type == 'blog') {
         return true;
      }
   }
   return false;
?>

 

Interesting links

  • This is a pastebin like place where I put stuff I find useful

 

Refreshing a div from with fade in:

Code: [Select]<script type="text/javascript">
$(document).ready(function() {
$("#responsecontainer").fadeOut("fast").load("getrows.php").fadeIn("slow");
var refreshId = setInterval(function() {
$("#responsecontainer").fadeOut("fast").load('getrows.php').fadeIn("slow");
}, 5000);
$.ajaxSetup({ cache: false });

[Code]...

  • snippet 2:

Posting to a form from php

  • posting to a form from php http://www.html-form-guide.com/php-form/php-form-submit.html
  • I also have this code i used before successfully:
  • //$output2=HTTP_Post("http://www.server2.com/script2.php",$_POST);
     
          function HTTP_Post($URL,$data, $referrer="") {
    $request="";
    $result="";
            // parsing the given URL
            $URL_Info=parse_url($URL);
     
            // Building referrer
            if($referrer=="") // if not given use this script as referrer
              $referrer=$_SERVER["SCRIPT_URI"];
     
            // making string from $data 
            foreach($data as $key=>$value)
            {
     $values[]="$key=".urlencode($value);
    //   print "$key :: $valuen";
            }
    $data_string=implode("&",$values);
          
            // Find out which port is needed - if not given use standard (=80)
            if(!isset($URL_Info["port"]))
              $URL_Info["port"]=80;
      
            // building POST-request:
            $request.="POST ".$URL_Info["path"]." HTTP/1.1rn";
            $request.="Host: ".$URL_Info["host"]."rn";
            $request.="Referer: $referrerrn";
    $request.="Accept-language: enrnCookie: ". "ASPSESSIONIDQATBADCS=HINAJNDBFJMLOJFHPLHPCDOE"."rn" .
       "User-Agent: Mozilla 4.0rn" . 
             "Content-type: application/x-www-form-urlencodedrn" . 
             "Content-length: ".strlen($data_string)."rn";
            $request.="Connection: closern";
            $request.="rn";
            $request.=$data_string."rn";
     
     
            $fp = fsockopen($URL_Info["host"],$URL_Info["port"]);
            fputs($fp, $request);
            while(!feof($fp)) {
                $result .= fgets($fp, 128);
            }
            fclose($fp);
     
            return $result;
          }

 

Drush

About Drush

Drush is an awesome command line interface for Drupal

If you have multiple sites (and even in cases of single site use) and you are not using Drush, you are missing out

Installing Drush:

 
  • First we need to download drush through pecl:
pear channel-discover pear.drush.org
pear install drush/drush
 
now, you can check drush is installed by typing "drush from command line"
  • In centos, default php settings are too restrictive so we need to make a drush.ini that allowes exec:
_ mkdir /etc/drush
_ cp /usr/share/pear/drush/examples/example.drush.ini /etc/drush/drush.ini
 
when done, uncomment the disable_function="" line
 

Useful commands

et voilà, you are ready to boost your productivity using drupal by an order of magnitude. Here are some of the commands I use
  • #drush self-update - check for drush updates 
  • #drush updatedb - applies any db update like update.php
  • #drush core-status - info about current site like db connections etc (if in directory) or default site if none specified #drush
  • pm-updatecode - update all core modules
  • #drush cache-clear - clear the cache, optional what to clear (all,drush,theme-registry,menu,css-js,block,module-list,theme-list,registry)
  • Setting useful variables:
    • drush vset site_offline [state] - put site in maintainance mode (1) or back online (0)
    • drush vset theme garland - good way to reset theme if current one has problems (you obviously can set another one instead of garland)
    • drush vset clean url 1 - enable clean urls
  • drush dl [module name] -download a module
  • drush en [module name] -enable a module (with optional -y to auto confirm)
  • drush pm-update - check which modules need updating
  • drush up [module_name] - update a module

default theme.info

each theme has a theme.info file specify theme files and settings

  • version parameter is used to describe theme version
  • core parameter is used to describe core requirement like 6.x for drupal 6 themes

; $Id: mytheme.info, v 1 date
; comments start if a semi column, previous comment was source contro comment

name = My theme name
description = what gets shown to users selecting themes. like 'custom them for example.com'
version = 7.x

default page.tpl.php

here is a sample page.tpl.php. note if the template does not exist, a default template is used. Comments are also optional but included here for code clarity

<head>
  <title>
  <?php   print $head_title; //print the page title  ?>
  </title>
  <?php print head; //print header ?>
  <?php print $styles; //print relevant styles ?>
  <?php print $scripts; //print page scripts ?>
</head>

 <?php if($site_slogan); ?>
    <div id='site-slogan'><?php print $site_slogan; ?></div>
 </div>

<?php endif; ?>

 

 

Drupal tips

Here are a few things that I have learned over time

  • Only enable needed modules - tons of modules are available and although it can be fun to enable everything for experimentation, the more modules are enabled, the slower Drupal will run and the more ressources it will need. Further, the more modules are enabled, the more potential security holes exist. Also, more modules means more user confusion, especially if the final admin is not very technically oriented
  • Make sure Drupal is updated - as mentioned in the previous point, security holes appear and you do not want your installation to be hacked (drush can help, see post on drush)
  • Use Multi-Site feature over multiple installs - There are cases where maintaining multiple installs is necessary, such as multiple servers. However, if possible, group all sites under one install. It makes backup easier, and updates faster and simpler.
  • Ensure a good default site exists - On multiple sites it may be tempting to put all the sites in site.com named folders but you never know when someone will come through a different path (such as accessing the ip address). It is important to have a valid default folder (maybe the most used site)
  • If privileges not needed, disable it for day to day accounts - admin account can do a lot of damage (either accidentally or through hack). Create users with only needed privileges and use them. 
  • enable social media interaction - allowing people to share pages is awesome and bound to bring traffic
  • Removing modules - if you are about to uninstall a module, disable it first, uninstall from menu then clear cache. Otherwise trouble may crop up.
  • Use sqlite to develop locally - Assuming that it is a small site that will have mainly read operations, use SQLite: enabling the site is as simple as copying the site folder to the target host. However, test first that  the   correct SQLite version is installed (Centos 5.5 for example doesn't by default)
  • Use Admin menu module - it can make administration much more smooth.
  • Enable anti-spam measure - Some spammers have automated tools to interact with Drupal. By enabling anti-spam modules on forms such as recapcha, you decrease (though unfortunately not remove) spam attempts.

Drupal Install Checklist

This is not meant to be a full fledged install tutorial... There exists plenty of good install tutorials are available... This is more a checklist of the 10 things I do when drupal is installed (I wish drupal would do that by default). Note that drush commands are included... so technically, it is possible to daisy chain most of these commands in a bash script file... making enabling modules on a new install a breeze.

  • Setup a database/ database user - mysql is the most common setup. You could use sqlite but some distribs like centos 5 out of the box have a version of sqlite that is too old
  • Fix permissions - When you install drupal you need to tweak permissions. ie: Give web user the right to write in the files directory  and settings.php during install (then set it to read only)
  • Install Drush - see related article on drush for details and a list of useful commands. This article assumes drush is installed with commands to setup things from the command prompt. You can obviously download the modules manually and install/enable them manually
  • Clean URLs - Make sure that clean urls are enabled (needs mod_rewrite on apache, rewrite module on iis). With drush, "drush vset clean_url 1" (if you need to disable them, use 0) but you can enable it from the configuration menu in admin
  • Wysiwyg module - I am not really sure why it does not come by default but, here it goes:
    • download and install the wysiwyg modul either manually or with:
      • drush install wysiwyg
      • drush en -y wysiwyg
    • download a wysiwyg html plugin (I use ckeditor), and put it in sites/libraries/[module] (for example sites/libraries/ckeditor)
    • Enable the wysiwyg module in content types
  • Adsense module - if the site is public, it is always nice to enable the adsense module
    • download and install adsense module
      • drush install adsense
      • drush en - y adsense
    • Configure adsense in Configuration > Webservices > Adsense
  • enable the book module - this is useful if like on webdevpower, you want to have hierarchical pages to sort content
  • Analytics module - very useful to get statistics (though technically you have many options included drupal's own statistics.
    • drush install google_analytics
    • drush en -y google_analytics
  • Enable path auto module - automatic aliases for urls... very useful for SEO. Note we download the token module too needed by pathauto
    • drush dl token
    • drush en -y token
    • drush dl pathauto
    • drush en -y pathauto
  • Create a cron job - this updates search and other functions that are not run automatically
    • First find out the url for cron... for drupal 6, it used to be just http://yoursite.com/cron.php but since drupal 7, to prevent abuse, the url has been protected.
      Get the url from the admin menu -> reports -> status report
    • create a cronjob crontab -e from shell
      0 * * * * wget -O - -q -t 1 http://site.com/[cronurl obtained in previous step]
  • User registration approve only - Unless the site is open to the public, set the user registration mode to approve (or closed if you know that no one will be added), that will prevent spammers from coming in but still allow people in.
  • edit content filters - in my taste the default filtered html is a bit restrictive, I add a few tags
  • edit content types - CCK allows really neat customization of content types. Why not add custom fields (if appropriate) 
  • Install drupal meta tags module - good for SEO
  • Change the default theme - even if you are to build a theme later, at least change the logo and default colors (default theme supports recoloring)
  • Create a non admin user - It is always good to post as someone other than admin user. Not foolproof security but one more step
  • Descriptive 1st post - Put a quick first post that is descriptive, especially if the site is on the internet - preferably with interesting keywords for search engines to start indexing you.

 

Obviously, many more steps are needed from there but this is a good way to get a decent head start.