Thursday, December 18, 2014

Drupal plugin

Drupal is a PHP content-management framework for web development. The popularity of drupal is evident in the vast community and contributed modules. The popularity comes from the ease of customization and simplicity of design. In this article the plugins of drupal aka the `modules` are analyzed. This is a continuous effort to investigate plugins in different projects.

Drupal modules are grouped into a folder/directory named after that module. The directory contains the following files,

  • .info file. The content of the .info file enable us to know about the module without loading it or installing it. These informations are kept in key-value pairs. They contain the name, description, version, package and testing information etc.
  • .module file. This is a PHP script containing primarily the hooks that needs to be loaded when the page is hit. To write a drupal module one must write the .module file and write at least one hook function.
  • .install file. This file is used only for installation and uninstallation. They may create database or do other tasks that are done at the time of installations. It contain the _install and _uninstall hooks.
  • .inc files. These files are loaded on demand. They are PHP sources containing instructions which is not needed in every page hit.

There are other files for testing and for command line operations. But those are not covered here. The cardinal part of the module is in the .module file. It contains function definitions. The function names are identified by the hooks using the PHP reflection feature. For example, a module can add menu by writing the following functions.

function mymodule_menu() {
    $items['abc/def'] = array(
        'page callback' => 'mymodule_abc_view',
    return $items;
function mymodule_abc_view() {
    return "Here is the abc content";

The above code is for module named mymodule. So the menu hook is the function named mymodule_menu. It is derived by prefixing the module name before _menu. And the return value of the hook is the array containing the menu items and the functions to be called on the menu hit. The ‘abc/def’ is the menu path identifying a page. It appears on the address bar of the browser.

All the _menu hooks can be called and executed by module_invoke_all function. It is possible to call user defined hooks to be populated by other modules.

function module_invoke_all($hook) {
  $args = func_get_args();
  // Remove $hook from the arguments.
  $return = array();
  foreach (module_implements($hook) as $module) {
    $function = $module . '_' . $hook;
    if (function_exists($function)) {
      $result = call_user_func_array($function, $args);
      if (isset($result) && is_array($result)) {
        $return = array_merge_recursive($return, $result);
      elseif (isset($result)) {
        $return[] = $result;

  return $return;

In the code above the function name is created by code $function = $module . '_' . $hook;. So it is conjunction of the module name and the hook name. The function above is responsible to call all the hooks of the loaded modules.

Now let us investigate the blog module.

The purpose of this module

The file contains the description of the module. It enables blogging for drupal users.

Loading and unloading

The blog.install contains blog_install and blog_uninstall functions which are the _install and _uninstall hooks.

The blog_install() alters the blog node and adds body field for it. The node is the parent object and it has it’s own defined way to save, load and render data. The blog is kind of subclass of the node. Anyway the abstraction of node is not covered here.

The blog_uninstall() just deletes unnecessary variable.

Note that the blog_install() function is called while installing and blog_uninstall() is called while uninstalling. But they are not called in each page hit. While in each page hit the blog.module file is parsed but none of them are executed.

Extension points

The blog_menu function defined in blog.module file is the _menu hook. Here _menu is the extension point. This hook is called when the module is enabled for use. Once called the total menu tree is built and kept in the database. It is not executed in per page hit.

 * Implements hook_menu().
function blog_menu() {
  $items['blog'] = array(
    'title' => 'Blogs',
    'page callback' => 'blog_page_last',
    'access arguments' => array('access content'),
    'type' => MENU_SUGGESTED_ITEM,
    'file' => '',
  $items['blog/%user_uid_optional'] = array(
    'title' => 'My blog',
    'page callback' => 'blog_page_user',
    'page arguments' => array(1),
    'access callback' => 'blog_page_user_access',
    'access arguments' => array(1),
    'file' => '',
  $items['blog/%user/feed'] = array(
    'title' => 'Blogs',
    'page callback' => 'blog_feed_user',
    'page arguments' => array(1),
    'access callback' => 'blog_page_user_access',
    'access arguments' => array(1),
    'type' => MENU_CALLBACK,
    'file' => '',
  $items['blog/feed'] = array(
    'title' => 'Blogs',
    'page callback' => 'blog_feed_last',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
    'file' => '',

  return $items;

Note that the menu has it’s own plugin-system and the extension-points. The blog, blog/%user_uid_optional, blog/%user/feed and blog/feed are the extension-points aka paths of menu-plugin-system. And blog_page_last, blog_page_user, blog_feed_user and blog_feed_last are the hooks registered in those extension-points respectively. This is an added twist in drupal architecture. It decouples the menu-extension-points from the core extension-points. This makes it flexible and separable.

And with added benefits these menu related hooks and callbacks are defined in separate file named to make the blog.module slimmer. The file is loaded when the related pages are loaded. Thus it reduces the processing time too.


Drupal project is based on functional programming in PHP. It still affords complex architecture and development needs. The reflection property of PHP function makes the hooking effortless. The analytic minds are tuned to find dumb instruments in the code. Drupal is very compulsive in that sense.

Saturday, November 22, 2014

Avoid distractions, practice internet fasting

Civilization is built in free time

Technology is the capstone of human civilization. At the advent of civilization we learned to use fire. We learned to cook. And cooking made the nutritions available to our body in less time and effort. This gave us time to think about other things, like art, culture and technology. We can now save a lot of our time using the technology. We can shop online, we can go places in cars or by trains. These all save our time and give us more time to think about us and to think about other ideas.

Now distractions are eating our time

On the other hand humans build habits, they are prone to classical conditioning. Today we are doped with the connecting technology. In the same way the over-nutrition caused us to become overweight and predisposed to some diseases; the overuse of social networking sites and internet made us occupied with social thoughts. We certainly lost our ability to wait and the ability to pursue a goal for a long time. Our personal tasks are overshadowed by the thoughts of society, politics and news-channels. The internet has made it easy to create and publish more information. Our desire for more online information caused information anxiety. And provided that anxiety we used up a lot of time gathering those informations. This resulted in reduced productive time and increased procrastinations.

Time is short and attention is limited resource

Life is short. This makes our attention limited. So we need to choose what we care most. We need to have a plan. And we need a sense of control. There are people who use the laws of economy to understand attention. And they call it attention economy. I find it very interesting.

Know thyself

In the earlier blog I talked about self profiling. We can use that profiling to measure the outcome of a month. In this way we can find what we are lacking and what we are overusing.

Formulating the solution

As I figured out that I spend a lot of time online, I formulated a simple solution. Too many of things are bad. Like in old days saints abstained themselves from food, we need to practice austerity using internet. It is like internet-fasting. We need to practice a ‘no-internet-day’ to edify our ability to think of ourselves.

Tuesday, October 21, 2014

Plugin and object oriented programming

Object oriented programming has the features like class, object, abstraction, encapsulation, polymorphism, inheritance. Interestingly plugin has some of those features. This is a continuous effort to investigate plugins.


A plugin is simply a singleton object. It can be initiated and destroyed. And the registered extensions are it’s fields in analogy to an object.


Plugin can use any named extensions even they are not registered by any actions. In this way they are less specific and abstract. For example, an application lets plugin to do certain things before exit. And it executes the actions under the onQuit extension point. Initially it can be empty.

On some point of execution a new plugin may be loaded that registers action to onQuit. Suppose the action is just to print Good Bye on the screen. So before the application exists it executes the action registered at onQuit and eventually it says Good Bye to the user.


Encapsulation makes your code more flexible, because the developer is not concerned about who is using the inner code. And the inner code can be changed anytime without modifying the other plugins. It is like advertising less makes things flexible(less is beautiful). Plugin just hides its internal code blocks as they are not registered to any extension point.


Plugin has the basic feature of overriding. It lets a code block to register to an extension point. In this way it overrides the behavior of that extension point.

Suppose in the earlier example, we load a new plugin which overrides the onQuit with action to print See You. In that case the application may execute both the actions before exit resulting it to say Good Bye See You .


Polymorphism is the idea of abstraction. It is the idea that the behavior of the code may be changed. And Plugin has this idea too. Different plugins make the application behave in different way. In the earlier example of inheritance, the behavior is changed from doing nothing to saying Good Bye and to saying Good Bye See You before exit.

Advantages of plugins over object oriented design

  • Object oriented programming is sometimes a mess. Plugins are good point of decoupling. The figure below shows the idea.



Monday, October 20, 2014

Ejabberd plugin

Ejabberd is very popular scalable XMPP server. This server is an instant messaging or chatting server. It is written in erlang. It implements it’s features in forms of modules. These modules can be seen as plugins. Here is how it works. This is our continuous effort to investigate plugins in different projects.

Here the mod_last is taken as example. Most of the modules here in ejabberd are small and less than 500 lines. Here is a small window of the output of find -iname "mod_*.erl" | xargs wc in linux shell. The values in left column are the number of lines.

    198     825    8244 ./src/mod_echo.erl
    173     566    5827 ./src/mod_proxy65_sm.erl
    682    1991   22312 ./src/mod_register.erl
    351    1082   11792 ./src/mod_last.erl
   1463    4336   48959 ./src/mod_shared_roster.erl
   1347    3897   45857 ./src/mod_irc.erl
    270    1087   10304 ./src/mod_carboncopy.erl
    109     380    3650 ./src/mod_time.erl
     97     330    3437 ./src/mod_service_log.erl

It is interesting that mod_last contains only 351 lines of code including the code comments. So this file will be easy to follow.

The purpose of this module

This module keeps a record of the time when a person is last seen online.

Loading and unloading

The modules here are loadable. They have a start and stop functions to initiate and deinitialize them. The start function takes two arguments and stop takes one argument.

Extension points

The start function here registers hook for following events.

  • unset_presence_hook
    The on_presence_update function is called when user is logged out of server. It just stores the time entry in the database.
    ejabberd_hooks:add(unset_presence_hook, Host, ?MODULE,
                       on_presence_update, 50).
on_presence_update(User, Server, _Resource, Status) ->
    TimeStamp = now_to_seconds(now()),
    store_last_info(User, Server, TimeStamp, Status).
  • remove_user
    When the user is removed permanently from server he is deleted from last_activity database.
    ejabberd_hooks:add(remove_user, Host, ?MODULE,
                       remove_user, 50),

There are other hooks that answer the user activity information and do other things.


This is very interesting to see how small the code is. And it is very precise too. Programmers will love to write modules here. It can be given 500 points for the mechanism (there will be more points coming for other projects). Thanks to erlang, nice language.

Thursday, September 18, 2014


Plugins are features added out of box. It is not needed to know all the internals of an application to write a new plugin. And the application does not need to know about the feature internals. The new plugin feature is called the extension to the existing software. To make the total thing work, the extensions are registered to an extension point.

There are two things that incorporate plugin.

  • Loadable separate code.
  • Features/extensions that are registered at some extension point.

Example of a plugin

Suppose there is a need for feature to share a webpage content as emails. The feature is to send email with less interaction from the user. The user does not need to open a web application interface in the browser to send email. The feature can be implemented by a email plugin of the browser. The email plugin may insert a ‘send page’ button through registering in menu-item-extension point. And when the user clicks the ‘send page’ button from the browser-menu it opens up few text-boxes. Eventually the user types the address and subject and presses the send button to send the email.

Here is a component diagram to demonstrate the idea,

This is an email sending feature that is implemented by email plugin. And the plugin registers in menu-item-extension point. The plugin know very little about the core features or other plugins. And the core application does not know the internals of the plugin at all.

Actually this type of plugin exists for firefox browser. For firefox the plugins are called addons. And there is an addon named send page. The code is available here.

<menupopup id="menu_FilePopup">
  <menuitem id="menu_sendpagebyemail" label="Send page by email..." key="spbe_sendPageKey" 
    oncommand="spbe_showDialog();" insertbefore="menu_sendLink" accesskey="e"/>

The xul code above registers a menu-entry labeled ‘Send page by email…’ in popup menu.

Finally the addon is provided in distributable package which firefox can load easily on demand.

The plugin system makes it possible to implement the beautiful correlation above.

Modules and plugins

Plugins and modules come hand in hand. Both modules and plugins are pieces of code. Both of them emphasize on separation of concern. In a module certain things are grouped together for development-ease or other purposes. But in a plugin they incorporate a feature and the basic idea is separation from the core features.

Sometimes module loaders facilitate a way to load plugins. In this case modules are also special type of plugins. They are loaded in the invisible extension point of the application binary.


Developing parts as plugins is a useful approach. It comes with some benefits.

Make little things work quickly and easily

Plugins are written to give some specific features. And their concerns are limited. So is the development time. This time-tuning is important because of human bias of instant gratification.

Additionally the separated code can be tested and debugged in absence of other features(of which it is not dependent). Thus separation helps development,debugging and testing units. For example, if it is needed to think of a feature to write a browser plugin to send email, then it is not needed to worry about other browser plugins like video player or something. In this way it is possible to be more focused and productive.

Plugins improve motivation

Plugins makes it possible to write a small separate segment of a big task. So it gives the satisfaction of achievement. Though it is a portion of big task, still it motivates to finish the unit. It helps the unit-bias of human psychology to finish an unit task.

Plugins and extension point mechanism makes things simple

Extending a big application is big cognitive load. To know all the internals is mandatory. Otherwise it can lead to bugs. And there is need to know the big APIs too. But in plugin the scope is small. It is not necessary to worry about the whole application but only the plugin-api. For example, to write an email sending feature for existing browser which has plugin support, it needs very little for the integration,

  • To know the plugin API. (To know the skeleton plugin that does nothing.)
  • To know how to add an extension.

Additionally, there are other things like showing an edit box and sending an email, but they have nothing to do with the core application.

OK, this is all about plugins now. In future, there will be discussions on how people facilitate plugins in their applications.

Wednesday, September 17, 2014

The extended mind

The brain and body is limited

Human has a limited brain and body. Though there are different thoughts and ideas that come into mind but pursuing them all is impossible. And even it is very difficult to reach a limited list of goals. One of the cause is the limited capability to remember all the tasks needed to be performed.

The brain is just like a computer

To a computer scientist the brain is comparable to a computer. And it has memory just like the computers. The memory can fall into two catagories,
- Short term memory or working memory(WM) in psychology is something more aligned to the RAM of the computer.
- Long term memory in psychology is like the hard disk.

On execution, thoughts and work processes are loaded in working memory to let it shuffle and get things done. For example, suppose a person is opening a lock with his key. At first, he thinks about the key in his pocket and grabs that in one hand, while he saves the goal(to open the lock) in the WM(working memory). And then he inserts the key into the lock to open it. This is easy.

Multitasking and context-switching problem

But the brain is not as good as the computer when it has to perform two cognitive tasks together. Suppose a person is thinking to open the lock and he has grasped the key in his hand. He has the goal to open the lock in his WM. At that very moment, someone calls him on the cell phone. The WM is full of the urgency of incoming call. As WM is limited, the thoughts to open the lock may be erased by the new information. He may mistakenly grab the key and put that in the ear. This may happen. Doing more than one cognitive task at a time may mess things up.

It is possible to extend the mind

For human it is hard to multitask. So the right thing is to do things one by one. If he has different things to do then it is helpful to maintain a list. A to-do-list. It is a small paper that holds your memory for future execution. In this way human can extend his mind.

People have used this idea of extended mind for long time. One of such extension is the written books. The books are the concepts of mind that are put into papers for recalling or for transmitting to people. Or the extended mind can be any written paper. Suppose someone wants to sum two big numbers (eg, 23874283 + 238479283742 = ? ). It may not be possible to do that using the WM only. But it is possible to do that easily using pencil and paper(like in the young days).

So it is a very old idea. Humans are curious about the inner working of themselves. To know the limitations is one way to know that. And to know the work-around is the novelty.

Monday, August 25, 2014

Profile thyself!

This is an idea to profile yourself. The idea is derived from three core thoughts ,

  • Know thyself.
  • We are what we repeatedly do.
  • You can only trust the numbers.

The three thoughts are connected. You see, you first understand you need to know yourself . Now who are you ? you are what you repeatedly do . And the way to know what you do repeatedly and how well you do that you need to count them. Finally you are inclined to profile yourself.

And there is a saying(not proved though) that doing something more than 10,000 hours may make you expert. I just want to know how many hours I do one such thing. So I profiled myself. Here is a page full of report.

There are other people trying this too,