Wednesday, 4 July 2007

Creating a Drupal module

First, went to the module developer's guide page and did the tutorial for Drupal 5.x. The block module in the tutorial, when completed, is full of code that integrates the module into the Drupal CMS. We don't need much of that code for now.

We want a quick and dirty email notifier module. First we create the info file that contains information which the CMS will display. The module's name is Messenger so the file will be
; $Id$
name = Messenger
description = "Sends out an email whenever new content has been created."

Then we have the module file, messenger.module. We add the hook_help and hook_perm functions from the tutorial. Through the Hooks API, we use the hook_nodeapi function which will run itself whenever there is node activity. This function is where we put in the mail command:
function messenger_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL)
case 'insert':
$query = "SELECT mail FROM users ".
"WHERE name = 'admin'";
$queryResult = db_query($query);

$user = db_fetch_object($queryResult);

$to = $user->mail;
$subject = "New content available!";
$body = "Someone's been adding new content! To ensure it's nothing illegal, please go check it out.";
$from = "";
$headers = array();

$mail_success = drupal_mail('messenger', $to, $subject, $body, $from);
drupal_set_message(t('There has been an error.\\nTo: '.$to.'\/nSubject: '.$subject.'\rBody: '.$body.'\nFrom: '.$from.'\nHeaders: '.$headers));
drupal_set_message(t('A mail has been sent to the admin. Prepare yourself! :)'));
drupal_set_message(t('Yay, you just inserted something! :)'));

One thing to check is whether sendmail is available on the Ubuntu system. If sendmail is not working then the module will not work.

The module is functional now. Further improvements can be done; sending the mail to more than one admin or even to users, restricting the notification to just pages or blog entries and making it configurable through the CMS.

1 comment:

Macrosoft said...

Thanks for sharing drupal module codes.

Drupal Development Company