You are here

bg_image.module in Background Images 6

Same filename and directory in other branches
  1. 7 bg_image.module

Allows for customizable background images per page

File

bg_image.module
View source
<?php

/**
 * @file
 *
 * Allows for customizable background images per page
 */

/*****************************************************************************
* DRUPAL HOOKS
*****************************************************************************/

/**
 * Implements hook_menu().
 */
function bg_image_menu() {
  $items['admin/settings/background-image'] = array(
    'title' => 'Background Image',
    'description' => t('Settings for how to apply the background image to the page'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'bg_image_settings_form',
    ),
    'access arguments' => array(
      'administer background image',
    ),
  );
  $items['bg-image/js'] = array(
    'page callback' => 'bg_image_node_type_ajax_callback',
    'access arguments' => array(
      'access content',
    ),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

/**
 * Implements hook_permission().
 */
function bg_image_perm() {
  return array(
    'administer background image',
  );
}

/**
 * Defines the settings for for bg_image
 */
function bg_image_settings_form(&$form_state) {

  // Init some variables
  $form = array();

  // '#validate' => array('bg_image_settings_form_validate'));
  $node_types = array(
    '' => 'choose...',
  );
  $node_fields = array(
    '' => 'Choose a node type first...',
  );

  // Options for repeating the image
  $repeat_options = bg_image_css_repeat_options();

  // Make an option list of node types
  foreach (node_get_types('types', NULL, TRUE) as $id => $node_type) {
    $node_types[$id] = $node_type->name;
  }

  // If this is a page rebuild for AJAX callback we need
  // create the field list for the specified node type
  // Only fields of the type 'image' will be accepted
  if (isset($form_state['values']['bg_image_node_type'])) {
    $node_fields = bg_image_get_fields_for_node_type($form_state['values']['bg_image_node_type']);
  }
  elseif (variable_get('bg_image_node_type', '')) {
    $node_fields = bg_image_get_fields_for_node_type(variable_get('bg_image_node_type', ''));
  }

  // The fieldset for node settings
  $form['node'] = array(
    '#type' => 'fieldset',
    '#title' => t('Node Settings'),
    '#description' => t('The background images can be added using nodes as the interface to upload and manage the images. In order to use this feature you need to specify the node type and field name here. Some modules may require this to be done before they will work.'),
  );

  // Select a node type
  $form['node']['bg_image_node_type'] = array(
    '#type' => 'select',
    '#title' => t('Node Type'),
    '#description' => t('The node type that holds the image for use with background image.'),
    '#options' => $node_types,
    '#default_value' => variable_get('bg_image_node_type', ''),
    '#required' => TRUE,
    '#ahah' => array(
      'path' => 'bg-image/js',
      'wrapper' => 'bg-image-node-field',
      'method' => 'replace',
      'effect' => 'fade',
    ),
  );

  // The actual field to use as the bg image
  $form['node']['bg_image_node_field'] = array(
    '#type' => 'select',
    '#title' => t('Node field'),
    '#description' => t('The field within the node type specified above to use as the image'),
    '#options' => $node_fields,
    '#default_value' => variable_get('bg_image_node_field', ''),
    '#required' => TRUE,
    '#prefix' => '<div id="bg-image-node-field">',
    '#suffix' => '</div>',
  );

  // The fieldset for exlusions
  $form['exclusions'] = array(
    '#type' => 'fieldset',
    '#title' => t('Global Exclusions'),
    '#description' => t('Choose specific pages/sections to exclude the background image from appearing on. This will apply to all background images'),
  );
  $form['exclusions']['bg_image_exclude_admin'] = array(
    '#type' => 'checkbox',
    '#title' => t('Exclude from Admin Pages'),
    '#description' => t('Background Images will be ignored on admin pages.'),
    '#default_value' => variable_get('bg_image_exclude_admin', 0),
  );
  if (module_exists('imagecache')) {

    // Apply an imagecache preset?
    $form['imagecache_preset'] = array(
      '#type' => 'fieldset',
      '#title' => t('Image Manipulation'),
      '#description' => t('Manipulate the image before outputting as a background image'),
    );
    $imagecache_presets = array(
      '' => '- None -',
    );
    foreach (imagecache_presets() as $preset) {
      $imagecache_presets[$preset['presetname']] = $preset['presetname'];
    }
    $form['imagecache_preset']['bg_imagecache_preset'] = array(
      '#type' => 'select',
      '#title' => t('Imagecache Preset'),
      '#description' => t('Apply an imagecache preset to the image'),
      '#options' => $imagecache_presets,
      '#default_value' => variable_get('bg_imagecache_preset', ''),
    );
  }

  // Fieldset for css settings
  $form['css_settings'] = array(
    '#type' => 'fieldset',
    '#title' => t('Default CSS Settings'),
    '#description' => t('Default CSS settings for outputting the background property. These settings will be concatenated to form a complete css statement that uses the "background" property. For more information on the css background property see http://www.w3schools.com/css/css_background.asp"'),
  );

  // The selector for the background property
  $form['css_settings']['bg_image_selector'] = array(
    '#type' => 'textfield',
    '#title' => t('Selector'),
    '#description' => t('A valid CSS selector that will be used to apply the background image.'),
    '#default_value' => variable_get('bg_image_selector', ''),
  );

  // The selector for the background property
  $form['css_settings']['bg_image_color'] = array(
    '#type' => 'textfield',
    '#title' => t('Color'),
    '#description' => t('The background color formatted as any valid css color format (e.g. hex, rgb, text, hsl) [<a href="http://www.w3schools.com/css/pr_background-color.asp">css property: background-color</a>]'),
    '#default_value' => variable_get('bg_image_color', '#FFFFFF'),
  );

  // The selector for the background property
  $form['css_settings']['bg_image_x'] = array(
    '#type' => 'textfield',
    '#title' => t('Horizontal Alignment'),
    '#description' => t('The horizontal alignment of the background image formatted as any valid css alignment. [<a href="http://www.w3schools.com/css/pr_background-position.asp">css property: background-position</a>]'),
    '#default_value' => variable_get('bg_image_x', 'left'),
  );

  // The selector for the background property
  $form['css_settings']['bg_image_y'] = array(
    '#type' => 'textfield',
    '#title' => t('Vertical Alignment'),
    '#description' => t('The vertical alignment of the background image formatted as any valid css alignment. [<a href="http://www.w3schools.com/css/pr_background-position.asp">css property: background-position</a>]'),
    '#default_value' => variable_get('bg_image_y', 'top'),
  );

  // The selector for the background property
  $form['css_settings']['bg_image_attachment'] = array(
    '#type' => 'radios',
    '#title' => t('Background Attachment'),
    '#description' => t('The attachment setting for the background image. [<a href="http://www.w3schools.com/css/pr_background-attachment.asp">css property: background-attachment</a>]'),
    '#options' => array(
      'scroll' => 'Scroll',
      'fixed' => 'Fixed',
    ),
    '#default_value' => variable_get('bg_image_attachment', 'scroll'),
  );

  // The background-repeat property
  $form['css_settings']['bg_image_repeat'] = array(
    '#type' => 'radios',
    '#title' => t('Background Repeat'),
    '#description' => t('Define the repeat settings for the background image. [<a href="http://www.w3schools.com/css/pr_background-repeat.asp">css property: background-repeat</a>]'),
    '#options' => $repeat_options,
    '#default_value' => variable_get('bg_image_repeat', 'no-repeat'),
  );

  // The background-size property
  $form['css_settings']['bg_image_background_size'] = array(
    '#type' => 'textfield',
    '#title' => t('Background Size'),
    '#description' => t('The size of the background (NOTE: CSS3 only. Useful for responsive designs) [<a href="http://www.w3schools.com/cssref/css3_pr_background-size.asp">css property: background-size</a>]'),
    '#default_value' => variable_get('bg_image_background_size', ''),
  );

  // background-size:cover suppor for IE8
  $form['css_settings']['bg_image_background_size_ie8'] = array(
    '#type' => 'checkbox',
    '#title' => t('Add background-size:cover support for ie8'),
    '#description' => t('The background-size css property is only supported on browsers that support CSS3. However, there is a workaround for IE using Internet Explorer\'s built-in filters (http://msdn.microsoft.com/en-us/library/ms532969%28v=vs.85%29.aspx). Check this box to add the filters to the css. Sometimes it works well, sometimes it doesn\'t. Use at your own risk'),
    '#default_value' => variable_get('bg_image_background_size_ie8', 0),
  );

  // The media query specifics
  $form['css_settings']['bg_image_media_query'] = array(
    '#type' => 'textfield',
    '#title' => t('Media Query'),
    '#description' => t('Apply this background image css using a media query. CSS3 Only. Useful for responsive designs. example: only screen and (min-width:481px) and (max-width:768px) [<a href="http://www.w3.org/TR/css3-mediaqueries/">Read about media queries</a>]'),
    '#default_value' => variable_get('bg_image_media_query', 'all'),
  );
  $form['css_settings']['bg_image_important'] = array(
    '#type' => 'checkbox',
    '#title' => t('Add "!important" to the background property.'),
    '#description' => t('This can be helpful to override any existing background image or color properties added by the theme.'),
    '#default_value' => variable_get('bg_image_important', 1),
  );
  return system_settings_form($form);
}

/**
 * AHAH Callback after Node Type has been chosen.
 */
function bg_image_node_type_ajax_callback() {
  $form_state = array(
    'storage' => NULL,
    'rebuild' => TRUE,
  );
  $form_build_id = $_POST['form_build_id'];
  $form = form_get_cache($form_build_id, $form_state);
  $args = $form['#parameters'];
  $form_id = array_shift($args);
  $form_state['post'] = $form['#post'] = $_POST;
  $form['#programmed'] = $form['#redirect'] = FALSE;

  // Trickery to avoid the required field errors on AHAH replacement
  $form['node']['bg_image_node_type']['#required'] = FALSE;
  $form['node']['bg_image_node_field']['#required'] = FALSE;
  drupal_process_form($form_id, $form, $form_state);
  $form = drupal_rebuild_form($form_id, $form_state, $args, $form_build_id);

  // Render the field element
  $element = $form['node']['bg_image_node_field'];
  unset($element['#prefix'], $element['#suffix']);
  $output = theme('status_messages') . drupal_render($element);

  // Final rendering callback.
  drupal_json(array(
    'status' => TRUE,
    'data' => $output,
  ));
}

/**
 * Returns the fields for a given node type
 * Only image fields will be accepted
 */
function bg_image_get_fields_for_node_type($node_type) {

  // Array to hold our fields
  $fields = array();
  if ($node_type) {

    // Get all the fields for the content type. We'll use this to determine the field type
    $info = content_types($node_type);

    // Loop through the fields of the node type
    foreach ($info['fields'] as $field_name => $field) {

      // Check that it's an image field
      if ($field['module'] == 'filefield' && $field['widget']['module'] == 'imagefield') {

        // Add the item to our option list
        $fields[$field_name] = $field['widget']['label'];
      }
    }
  }

  // If there were no fields, we return a message
  if (!$fields) {
    $fields[''] = 'No image fields attached to this node type';
  }
  return $fields;
}

/*****************************************************************************
* CONTEXT HOOKS
*****************************************************************************/

/**
 * Implements hook_ctools_plugin_api().
 */
function bg_image_ctools_plugin_api($module, $api) {
  if ($module == 'context' && $api == 'plugins') {
    return array(
      'version' => 3,
    );
  }
}

/**
 * Implements hook_context_plugins
 *
 * Defines the plugin handler for conditions and reactions
 */
function bg_image_context_plugins() {
  $plugins = array();
  $plugins['bg_image_context_reaction_bg_image'] = array(
    'handler' => array(
      'path' => drupal_get_path('module', 'bg_image') . '/plugins',
      'file' => 'bg_image_context_reaction_bg_image.inc',
      'class' => 'bg_image_context_reaction_bg_image',
      'parent' => 'context_reaction',
    ),
  );
  return $plugins;
}

/**
 * Implements hook_context_registry
 *
 * Registers a condition or reaction with Context.
 * Once registered, it will also appear in the context ui
 */
function bg_image_context_registry() {
  $registry = array();
  $registry['reactions']['bg_image'] = array(
    'title' => t('Background Image'),
    'description' => t('Set the background image for the site.'),
    'plugin' => 'bg_image_context_reaction_bg_image',
  );
  return $registry;
}

/**
 * Implementation of hook_context_page_reaction().
 *
 * We need to actually call the reaction at some point
 * or nothing will happen.
 */
function bg_image_context_page_reaction() {
  if ($plugin = context_get_plugin('reaction', 'bg_image')) {
    $plugin
      ->execute();
  }
}

/*****************************************************************************
* API FUNCTIONS
*****************************************************************************/

/**
* Adds a background image to the page using the
* css 'background' property.
*
* @param $image_path
*    The path of the image to use.
*
* @param $css_settings
*    An array of css settings to use. Possible values are:
*      - bg_image_selector: The css selector to use
*      - bg_image_color: The background color
*      - bg_image_x: The x offset
*      - bg_image_y: The y offset
*      - bg_image_attachment: The attachment property (scroll or fixed)
*      - bg_image_repeat: The repeat settings
*      - bg_image_background_size: The background size property if necessary
*    Default settings will be used for any values not provided.
*
* @param $imagecache_preset
*   Optionally add an imagecache preset to the image before applying it to the
*   background
*
* @return
*   Returns TRUE if successful or FALSE otherwise
*/
function bg_image_add_background_image($image_path, $css_settings = array(), $imagecache_preset = NULL, $bg_image_id = 'global') {
  $css_filename = 'bg_image_' . $bg_image_id . '.css';

  // Pull the default css setting if not provided.
  $selector = isset($css_settings['bg_image_selector']) ? $css_settings['bg_image_selector'] : variable_get('bg_image_selector', '');
  $bg_color = isset($css_settings['bg_image_color']) ? $css_settings['bg_image_color'] : variable_get('bg_image_color', '#FFFFFF');
  $bg_x = isset($css_settings['bg_image_x']) ? $css_settings['bg_image_x'] : variable_get('bg_image_x', 'left');
  $bg_y = isset($css_settings['bg_image_y']) ? $css_settings['bg_image_y'] : variable_get('bg_image_y', 'top');
  $attachment = isset($css_settings['bg_image_attachment']) ? $css_settings['bg_image_attachment'] : variable_get('bg_image_attachment', 'scroll');
  $repeat = isset($css_settings['bg_image_repeat']) ? $css_settings['bg_image_repeat'] : variable_get('bg_image_repeat', 'no-repeat');
  $important = isset($css_settings['bg_image_important']) ? $css_settings['bg_image_important'] : variable_get('bg_image_important', 1);
  $background_size = isset($css_settings['bg_image_background_size']) ? $css_settings['bg_image_background_size'] : variable_get('bg_image_background_size', '');
  $media_query = isset($css_settings['bg_image_media_query']) ? $css_settings['bg_image_media_query'] : variable_get('bg_image_media_query', 'all');

  // Apply an Imagecache Preset?
  $imagecache_preset = $imagecache_preset ? $imagecache_preset : variable_get('bg_imagecache_preset', '');

  // If important is true, we turn it into a string for css output
  if ($important) {
    $important = '!important';
  }
  else {
    $important = '';
  }

  // Handle the background size property
  $bg_size = '';
  $ie_bg_size = '';
  if ($background_size) {

    // CSS3
    $bg_size = "    background-size: {$background_size} {$important};\n";

    // Let's cover ourselves for other browsers as well...
    $bg_size .= "    -webkit-background-size: {$background_size} {$important};\n";
    $bg_size .= "    -moz-background-size: {$background_size} {$important};\n";
    $bg_size .= "    -o-background-size: {$background_size} {$important};\n";

    // IE filters to apply the cover effect
    if ($background_size == 'cover' && variable_get('bg_image_background_size_ie8', 0)) {
      $bg_size .= '    filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'.' . $image_path . '\', sizingMethod=\'scale\');
      -ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'' . $image_path . '\', sizingMethod=\'scale\')";' . "\n";
    }
  }

  // See if admin pages are excluded from bg images
  $admin = variable_get('bg_image_exclude_admin', 0) ? !_bg_image_path_is_admin($_GET['q']) : TRUE;

  // Check if we need to run this through an imagecache preset
  if ($imagecache_preset && module_exists('imagecache')) {

    // Image cache paths need to be relative to drupal root with no leading slash
    $imagecache_path = trim(parse_url($image_path, PHP_URL_PATH), '/');
    $image_path = imagecache_create_url($imagecache_preset, $imagecache_path);
  }

  // Add the css if we have everything we need.
  if ($selector && $image_path && $admin) {
    $style = "@media {$media_query} {\n";
    $style .= "  {$selector} {\n";
    $style .= "    background-color: {$bg_color} {$important};\n";
    $style .= "    background-image: url('{$image_path}') {$important};\n";
    $style .= "    background-repeat: {$repeat} {$important};\n";
    $style .= "    background-attachment: {$attachment} {$important};\n";
    $style .= "    background-position: {$bg_x} {$bg_y} {$important};\n";
    $style .= $bg_size;
    $style .= "  }\n";
    $style .= "}\n";
    $name = file_save_data($style, $css_filename, FILE_EXISTS_REPLACE);
    drupal_add_css($name);

    // drupal_add_css($style, array('type' => 'inline', 'media' => $media_query, 'group' => CSS_THEME));
    return TRUE;
  }
  else {
    return FALSE;
  }
}

/**
 * Determines the path of an image on the configured image
 * field on a node and returns it.
 *
 * @param $nid
 *   The nid of the node to check for an image
 *
 * @param $build_url
 *   Optional parameter to return the full URL
 *   of the image rather than just the uri
 *
 * @return
 *   The path of the image if the node has it, or FALSE.
 */
function bg_image_get_image_path_from_node($nid, $build_url = TRUE) {
  $fields = content_fields(NULL, $node->type);
  $field_name = variable_get('bg_image_node_field', '');
  $node = node_load($nid);
  $image_path = FALSE;
  if ($node && $field_name) {
    if (isset($fields[$field_name]) && $fields[$field_name]['widget']['module'] == 'imagefield') {
      if ($node->{$field_name}) {
        $image_path = $node->{$field_name}[0]['filepath'];
      }
    }
  }
  if ($image_path && $build_url) {
    $image_path = file_create_url($image_path);
  }
  return $image_path;
}

/**
* Adds a background image to the page using an image from
* a node. The node must have an image (or media) field and
* the field must be configured on the bg_image configuration
* page for this to work.
*
* @param $nid
*    The nid of the node that has the image to use for the
*    background. Use 0 to generate a random image from the
*    configured node type.
*
* @param $css_settings
*    An array of css settings to use. See bg_image_add_background_image()
*    for more detailed description of possible values.
*
* @param $imagecache_preset
*    Optionally add an imagecache preset to the image before applying it to the
*    background
*/
function bg_image_add_background_image_from_node($nid, $css_settings = array(), $imagecache_preset = NULL) {

  // We need to generate a random nid if 0 is passed in
  if ($nid == 0) {
    $type = variable_get('bg_image_node_type', '');
    if ($type) {
      $sql = "SELECT nid FROM {node}\n              WHERE type = '%s'\n              AND status = 1\n              ORDER BY RAND()\n              LIMIT 1";
      $query = db_query($sql, array(
        $type,
      ));
      $nid = db_result($query);
    }
    else {
      return FALSE;
    }
  }
  if (is_numeric($nid)) {

    // Load the node so we can check it's status
    $node = node_load($nid);

    // Check node access permissions
    if (node_access('view', $node)) {

      // Get the path of the image on the node
      $image_path = bg_image_get_image_path_from_node($nid);

      // Add the background image
      return bg_image_add_background_image($image_path, $css_settings, $imagecache_preset, $nid);
    }
  }

  // If all else fails
  return FALSE;
}

/**
 * Check if a node has an image set on the configured field
 *
 * @param $nid
 *    The nid of the node to check
 *
 * @return
 *    If the node has an image set for the field
 *    returns TRUE, otherwise returns FALSE
 */
function bg_image_field_has_image($nid) {
  $node = node_load($nid);
  $field_name = variable_get('bg_image_node_field', '');
  if ($node && $node->{$field_name}) {
    return TRUE;
  }
  else {
    return FALSE;
  }
}

/**
 * Returns an array of nids to node titles for the
 * configured node type. Useful for select lists.
 *
 * @param $include_nid
 *    Include the nid as text after the title. TRUE
 *    or FALSE. e.g.: array(1 => 'node title [nid: 1]')
 */
function bg_image_node_options($include_nid = TRUE, $include_random = TRUE) {
  $node_type = variable_get('bg_image_node_type', '');

  // Our query
  $sql = "SELECT nid, title FROM {node} WHERE type = '%s'";
  $query = db_query($sql, array(
    $node_type,
  ));
  $node_options = array();
  while ($record = db_fetch_object($query)) {
    if ($include_nid) {
      $node_options[$record->nid] = $record->title . ' [nid:' . $record->nid . ']';
    }
    else {
      $node_options[$record->nid] = $record->title;
    }
  }
  if (!$node_options) {
    $node_type_path = str_replace('_', '-', $node_type);
    drupal_set_message("You don't have any {$node_type} nodes created yet. You must <a href=\"/node/add/{$node_type_path}\">create at least one {$node_type} node</a> before you can assign background images to pages.", 'warning');
    return FALSE;
  }
  else {
    if ($include_random) {
      return array(
        0 => '- Random -',
      ) + $node_options;
    }
    else {
      return $node_options;
    }
  }
}

/**
 * Checks if a node (and field) is configured.
 */
function bg_image_node_is_configured() {
  if (variable_get('bg_image_node_type', '') && variable_get('bg_image_node_field', '')) {
    return TRUE;
  }
  else {
    return FALSE;
  }
}

/**
 * Returns an options list of css repeat options
 */
function bg_image_css_repeat_options() {
  return array(
    'no-repeat' => t('No Repeat'),
    'repeat' => t('Tiled (repeat)'),
    'repeat-x' => t('Repeat Horizontally (repeat-x)'),
    'repeat-y' => t('Repeat Vertically (repeat-y)'),
  );
}

/**
 * Returns true if the current page is an 'admin' page
 */
function _bg_image_path_is_admin() {
  if (arg(0) == 'admin') {
    return TRUE;
  }
  else {
    return FALSE;
  }
}

Functions

Namesort descending Description
bg_image_add_background_image Adds a background image to the page using the css 'background' property.
bg_image_add_background_image_from_node Adds a background image to the page using an image from a node. The node must have an image (or media) field and the field must be configured on the bg_image configuration page for this to work.
bg_image_context_page_reaction Implementation of hook_context_page_reaction().
bg_image_context_plugins Implements hook_context_plugins
bg_image_context_registry Implements hook_context_registry
bg_image_css_repeat_options Returns an options list of css repeat options
bg_image_ctools_plugin_api Implements hook_ctools_plugin_api().
bg_image_field_has_image Check if a node has an image set on the configured field
bg_image_get_fields_for_node_type Returns the fields for a given node type Only image fields will be accepted
bg_image_get_image_path_from_node Determines the path of an image on the configured image field on a node and returns it.
bg_image_menu Implements hook_menu().
bg_image_node_is_configured Checks if a node (and field) is configured.
bg_image_node_options Returns an array of nids to node titles for the configured node type. Useful for select lists.
bg_image_node_type_ajax_callback AHAH Callback after Node Type has been chosen.
bg_image_perm Implements hook_permission().
bg_image_settings_form Defines the settings for for bg_image
_bg_image_path_is_admin Returns true if the current page is an 'admin' page