Using Drupal Features In B-Translator

Reading time ~8 minutes

Using Drupal Features In B-Translator

Using Drupal Features In B-Translator

Features are very useful for building Drupal profiles (re-usable applications). They provide a way to capture and save in code the customizations that are done to a Drupal site/application. I will describe how I use them in B-Translator.

1 Benefits of using features

Some of the main benefits of using features are these:

  1. They help the development and maintenance of the application. Customization/configuration changes can be tracked and versioned (for example in git) just like the code of the application.
  2. They help the installation of a new instance of the application. Customizations can be replayed (applied) easily on a new installation of the application, without having to repeat them manually.
  3. They make the application structured (as opposed to monolithic). For example drupalchat is offered as a feature and can be installed very easily by installing the feature. But sites that do not want to use it just don't install that feature.

For more details about features (and their features) you can read these blogs:

2 Creating features

Features can be created and managed through UI. However I find the UI for creating features not suitable (tedious, sluggish, unreliable), at least when creating features for a Drupal profile. Fortunately they can also be fully managed from the command line (with drush):

drush help --filter=features

First of all, we can get a list of all the so called features components:

drush @dev help features-components
drush @dev features-components '%:%' > features-components.txt

These are all the possible chunks of configuration that can be saved in a feature. All we have to do is to search and select the ones that are relevant for the feature that we want to build and then create a feature with these components. This will automatically generate the code (Drupal API) that is necessary to apply these configurations.

For example, these are the components that I have selected for the layout feature (which is supposed to re-construct automatically the layout and look of a freshly installed B-Translator site):

variable:theme_bootstrap1_settings
variable:theme_default
box:headerbox
context:admin
context:content
context:frontpage
context:page
context:sitewide
context:translations
views_view:front_page
variable:site_frontpage
menu_links:main-menu:<front>
menu_links:main-menu:node/9
menu_links:main-menu:translations
menu_links:main-menu:node/1
menu_links:main-menu:contact
menu_custom:navig-menu
menu_links:navig-menu:translations
menu_links:navig-menu:node/9
menu_links:navig-menu:translations/search
menu_links:navig-menu:node/1
menu_links:navig-menu:contact

These include the theme, blocks layout, the front page view, and the menus.

Now I can create a feature that includes these components with a command like this:

drush @dev features-export \
--destination=profiles/btranslator/modules/features \
btranslator_layout $(cat layout_components)

It creates a feature on the directory: /var/www/btranslator_dev/profiles/btranslator/modules/features/btranslator_layout/

Other features that I have created are: btranslator_disqus, btranslator_invite, btranslator_sharethis, btranslator_captcha, btranslator_drupalchat, btranslator_janrain, btranslator_simplenews, btranslator_mass_contact, btranslator_googleanalytics, etc. In order to recreate them easily, the script create-features.sh can be used. It will create a feature for each list of components that is on the directory components/.

The file create-features.sh has a content like this:

#!/bin/bash
### Create all the features.
### However some features need manual customization
### after being created (for example btranslator_layout).
</p>

<p>
drush="drush &#x2013;yes @dev"
destination="profiles/btranslator/modules/features"
</p>

<p>
function create_feature
{
    components=$1
    feature_name="btranslator_$(basename $components)"
</p>


<p>
xargs &#x2013;delimiter=$'' &#x2013;arg-file=$components \
    $drush features-export &#x2013;destination=$destination $feature_name
  }
</p>

<p>
### go to the directory of the script
cd $(dirname $0)
</p>

<p>
### clear cache etc.
$drush cc all
rm -f components/*~
</p>

<p>
### create a feature for each file in 'components/'
for components in $(ls components/*)
do
    echo "===&gt; $components"
    create_feature $components
done

3 Customizing features manually

A feature is basically just a Drupal module (although it is generated automatically by the command features-export). So, we can further customize it manually if needed. And sometimes there is the need for manual customization because the automatic generation cannot get always everything right. In the case of the layout feature I added the file btranslator_layout.install, which uses hook_enable() to make further customizations after the feature is installed.

&lt;?php
</p>

<p>
/**
</p>
<ul class="org-ul">
<li>Implements hook_enable().
</li>
</ul>
<p>
 */
function btranslator_layout_enable() {
  _btranslator_layout_create_aliases();
  _btranslator_layout_add_login_link();
  _btranslator_layout_block_settings();
}
</p>


<p>
function _btranslator_layout_create_aliases() {
  $aliases = array(
    'udhezuesi' =&gt; 'Udhëzuesi i Përkthyesit',
    'about' =&gt; 'About',
  );
</p>

<p>
  foreach ($aliases as $alias <code>&gt; $title) {
      $query = "SELECT nid FROM {node} WHERE title</code>'$title' AND status=1";
    $nid = db_query($query)-&gt;fetchField();
    if ($nid == FALSE)  continue;
    $source = "node/$nid";
    db_query("DELETE FROM {url_alias} WHERE source='$source' AND alias='$alias'");
    $args = array('source' =&gt; $source, 'alias' =&gt; $alias);
    path_save($args);
  }
}
</p>

<p>
function _btranslator_layout_add_login_link() {
  $query = "DELETE FROM {menu_links}
            WHERE menu_name='user-menu'
              AND link_path='user/login'
              AND link_title='Login' AND plid='0' ";
  db_query($query);
</p>

<p>
  $login = array(
    'menu_name' =&gt; 'user-menu',
    'link_path' =&gt; 'user/login',
    'link_title' =&gt; 'Login',
    'plid' =&gt; '0',
    'router_path' =&gt; 'user/login',
  );
  menu_link_save($login);
}
</p>

<p>
function _btranslator_layout_block_settings() {
  // set the title of the menu block as Navigation
  db_query("UPDATE {block} SET title='Navigation'
            WHERE theme='bootstrap1' AND delta='navig-menu'");
</p>

<p>
// remove the title of the block user-menu
db_query("UPDATE {block} SET title='&lt;none&gt;'
          WHERE theme='bootstrap1' AND delta='user-menu'");
</p>

<p>
  <i>/ disable all the blocks for theme bootstrap1
  /</i> their place is managed by module context
  db_query("UPDATE {block} SET status = '0' WHERE theme = 'bootstrap1'");
}

It creates aliases, which cannot be handled properly by the features. It creates a Login menu link, which is not handled propperly by the features (although in general menu links can be handled quite well by the features). It also sets the correct settings for the blocks in a simple way, although there are other ways to handle them by the features.

4 Making features configurable

Some of the features are required and will be automatically installed when the (btranslator) profile is installed, and some others are optional and can be installed later by the site administrator, if they wish. Most of these features are closely related to some contrib modules and basically just save default/reasonable values for the configuration settings of the module.

Some of these modules are just wrappers to external API services, like disqus, sharethis, janrain, recaptcha, googleanalytics, etc. Usually they need some API keys or any other private attributes that are different from site to site. We cannot save these private attributes on the feature, because they are specific for each different site. But we would like to offer the administrator/maintainer of the (B-Translator) application an easy way to manage them, without having to search up and down among a huge number of configuration options available to the Drupal admin. In order to do this, I have customized the automatically generated features, taking advantage of the fact that they are just Drupal modules, and anything that works for Drupal modules works for them too.

For example, for the feature btranslator_googleanalytics, I have added this line on btranslator_googleanalytics.module:

include_once 'btranslator_googleanalytics.admin.inc';

I have also created the file btranslator_googleanalytics.admin.inc with a content like this:

&lt;?php
/**
</p>
<ul class="org-ul">
<li>@file
</li>
<li>Configuration of googleanalytics.
</li>
</ul>
<p>
*/
</p>

<p>
/**
</p>
<ul class="org-ul">
<li>Implements hook_menu().
</li>
</ul>
<p>
 */
function btranslator_googleanalytics_menu() {
  $items = array();
  $items['admin/config/btranslator/googleanalytics'] = array(
    'title'            =&gt; 'GoogleAnalytics',
    'description'      =&gt; 'Private GoogleAnalytics settings.',
    'page callback'    =&gt; 'drupal_get_form',
    'page arguments'   =&gt; array('btranslator_googleanalytics_config'),
    'access arguments' =&gt; array('btranslator-admin'),
  );
</p>

<p>
  return $items;
}
</p>

<p>
/**
</p>
<ul class="org-ul">
<li>Custom settings for GoogleAnalytics.
</li>
<li></li>
<li>@return
</li>
<li>An array containing form items to place on the module settings page.
</li>
</ul>
<p>
 */
function btranslator_googleanalytics_config() {
  $form = array();
</p>

<p>
$form['googleanalytics_account'] = array(
  '#title' =&gt; t('Web Property ID'),
  '#type' =&gt; 'textfield',
  '#default_value' =&gt; variable_get('googleanalytics_account', 'UA-'),
  '#size' =&gt; 15,
  '#maxlength' =&gt; 20,
  '#required' =&gt; TRUE,
  '#description' =&gt; t('This ID is unique to each site you want to track
                       separately, and is in the form of UA-xxxxxxx-yy.
                       To get a Web Property ID, &lt;a href="@analytics"&gt;
                       register your site with Google Analytics&lt;/a&gt;,
                       or if you already have registered your site,
                       go to your Google Analytics Settings page
                       to see the ID next to every site profile.
                       &lt;a href="@webpropertyid"&gt;Find more information
                       in the documentation&lt;/a&gt;.',
                       array('@analytics' =&gt; 'http://www.google.com/analytics/',
                             '@webpropertyid' =&gt; url('https://developers.google.com/analytics/resources/concepts/gaConceptsAccounts',
                                                     array('fragment' =&gt; 'webProperty')))),
);
</p>

<p>
  return system_settings_form($form);
}

It creates a configuration page for GoogleAnalytics under the section of B-Translator configurations. This admin/config page allows the site administrator to set quickly and easily the account ID of GoogleAnalytics. All this is just normal Drupal stuff, which can be done for any Drupal module. Nothing specially related to features. For my convenience, I have copied the definition of the form field from the googleanalytics Drupal module itself (from the file googleanalytics.abmin.inc).

5 Saving and restoring private variables

If we cannot and should not keep private settings/attributes in features, then there should be some other easy way for the site administrators to backup and restore them, without making them public and available to everyone. This can be done by the script save-private-vars.sh. It takes a list of variables from private-vars.txt and creates the file restore-private-vars.php which keeps the values of these variables and can restore them. It works like this:

features/save-private-vars.sh @dev
drush @dev php-script restore-private-vars.php

The file private-vars.txt looks like this:

disqus_domain
disqus_userapikey
disqus_publickey
disqus_secretkey
sharethis_publisherID
sharethis_twitter_handle
sharethis_twitter_suffix
rpx_apikey
simplenews_from_address
simplenews_test_address
mass_contact_default_sender_email
mass_contact_default_sender_name
recaptcha_private_key
recaptcha_public_key
googleanalytics_account

The script save-private-vars.sh has a content like this:

#!/bin/bash
### Save sensitive/private variables that should not be made public.
</p>

<p>
echo "Usage: $0 [@drush_alias]"
</p>

<p>
drush_alias=$1
drush="drush $drush_alias"
</p>

<p>
cat &lt;&lt;EOF &gt; restore-private-vars.php
&lt;?php
/**
</p>
<ul class="org-ul">
<li>Backup of sensitive/private variables, that are specific
</li>
<li>only for this instance of B-Translator. This file should
</li>
<li>never be made public.
</li>
</ul>
<p>
*/
</p>

<p>
// define variables
EOF
</p>

<p>
while read var_name
do
    $drush vget "$var_name" &#x2013;exact &#x2013;pipe &gt;&gt; restore-private-vars.php
done &lt; $(dirname $0)/private-vars.txt
</p>

<p>
cat <a id="EOF" name="EOF"></a> restore-private-vars.php
</p>

<p>
// set variables
foreach (\$variables as \$var_name =&gt; \$var_value) {
  variable_set(\$var_name, \$var_value);
}
EOF
</p>

<p>
echo "
Restore variables with the command:
$drush php-script restore-private-vars.php
"

It can be useful as well to keep different sets of private variables for the live, test and dev sites.

Date: 2013-07-09

Author: Dashamir Hoxha

Created: 2019-01-24 Thu 05:13

Emacs 25.1.1 (Org mode 8.2.10)

Validate

OpenPGP Web Key Directory

OpenPGP Web Key DirectoryOpenPGP Web Key DirectoryTable of Contents1. Introduction2. How WKD works3. Building a WKD3.1. Create the direct...… Continue reading

SMTP Server with LDAP Authentication

Published on April 17, 2021

Using WireGuard VPN

Published on November 09, 2020