Drupal 6 Programmatically Create image_gallery Images in PHP

Or since image_gallery items are just images with a taxonomy tag in a vocabulary called Image Galleries, a subtitle could be Programmatically Create Images and Tag with image_gallery. In this tutorial we are going to create a small module which contains the code to create the images and has a button on a form to effect the creation. I will foreground the actual copying code so you can cut and paste it into your own module development.

As usual, we need a .info file and a .module file for the module. I will call the module CIGI (Create image_gallery images). Create the necessary directory and files, and create a subdirectory for the images.

laptop4:/> cd srv/www/htdocs/badzilla/sites/all/modules
laptop4:/srv/www/htdocs/badzilla/sites/all/modules> mkdir cigi
laptop4:/srv/www/htdocs/badzilla/sites/all/modules> touch cigi/cigi.info
laptop4:/srv/www/htdocs/badzilla/sites/all/modules> touch cigi/cigi.module
laptop4:/srv/www/htdocs/badzilla/sites/all/modules> mkdir cigi/images

Then copy some test images into the cigi/images directory and check they are there.
laptop4:/srv/www/htdocs/badzilla/sites/all/modules> ls  cigi/images
BreakInCircle.jpg  DarkLight.jpg  GlassCage.jpg  MaskOfDusk.jpg  WhisperingSmith.jpg

TaxonomyThese are movie posters so I will put them into a gallery called Hammer Productions. Create an image gallery firstly called Posters, then a child tag of Movie Posters then a further child tag of Hammer Productions. This can of course be done with some PHP code but here I have simply used the Drupal administration system.

The entire code for the module is reproduced below.
cigi.info
name = "Create Image Gallery Images"
description = "Simple module to add images to an image gallery programmatically"
dependencies[] = "image"
dependencies[] = "image_gallery"
core = 6.x
php = 5.2

cigi.module
<?php
/**
*    MODULE: CIGI - Create Image Gallery Images programmatically in PHP
*    Copyright (C) 2009 <a href="http://www.badzilla.co.uk
*
*" title="http://www.badzilla.co.uk
*
*">http://www.badzilla.co.uk
*
*</a>    FILE:    cigi.module
*    VERSION: 0.1.0
*    AUTHOR:  Badzilla
*    DATE:    February 2010
*
*    This program is released under the GPL license
*
*
*    This program is distributed in the hope that it will be useful,
*    but WITHOUT ANY WARRANTY; without even the implied warranty of
*    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
*
*/


/**
* Implements hook_menu().
*/
function cigi_menu() {

   
$items = array();

   
$items['cigi'] = array(
       
"title"                 => "Create image_gallery Images",
       
"access arguments"      => array("update profile"),
       
"page callback"         => "drupal_get_form",
       
"page arguments"        => array('cigi_submit'),
       
"access arguments"      => array('add images'),
       
"type"                  => MENU_NORMAL_ITEM,
        );

    return
$items;

}



function
cigi_submit() {

    if (isset(
$_POST['submit']))
       
cigi_copy();

   
$form['cigi'] = array(
       
'#type' => 'fieldset',
       
'#title' => t('Add Images to image_gallery'),
       
'#prefix' => '<div class="container-inline">',
       
'#suffix' => '</div>',
    );

   
$form['cigi']['submit'] = array(
       
'#type' => 'submit',
       
'#name' => 'submit',
       
'#value' => t('Add Now'),
    );

    return
$form;
}



/**
* Implements hook_access()
*/
function cigi_access($op, $node, $account) {
    switch (
$op) {
        case
'add':
            return
user_access('add image', $account);
    }
}


/**
* The actual business logic
*/
function cigi_copy() {

   
// Taxonomy for the images
   
$tname = 'Hammer Productions';

   
// directory
   
$dir = drupal_get_path('module', 'cigi') . "/images";

   
// get the vocabulary vid for the image_gallery
   
$vocabs = taxonomy_get_vocabularies();
    foreach(
$vocabs as $v)
        if (
$v->name == "Image Galleries")
           
$vid = $v->vid;

   
// if there is no image_gallery vocabulary, return
   
if (!isset($vid))
        return;

   
// check the taxonomy tree to confirm the given taxonomy is a child of an image_gallery
   
$tree = taxonomy_get_tree($vid);
    foreach(
$tree as $branch)
        if (
$branch->name == $tname)
           
$tid = $branch->tid;

   
// if the term is not in the image_gallery, return
   
if (!isset($tid))
        return;

   
// get a list of images
   
$images = file_scan_directory($dir, '\.jpg$',  array('.', '..', 'CVS'), 0, FALSE, 'basename');
    foreach(
$images as $file) {
       
$base = RemoveExtension($file->basename);     
       
image_create_node_from($file->filename, $base, $base, array($tid));
       
drupal_set_message("Added {$file->basename} into $tname image gallery");
    }

}



/**
* Remove the file extension on the filename for the title and body
*/
function RemoveExtension($filename) {

    return
substr($filename, 0, strrpos($filename, '.'));  
}
?>

ModuleFinal GalleryThe main part of the code (i.e. the code not supporting the framework of a module) is in the function cigi_copy(). Particular attention should be paid to a call to image_create_node_from() which is an undocumented API call found in image.module. It does the main legwork of creating the image nodes, and has a nice final parameter of an array of taxonomy ids which effectively means there are no additional taxonomy API calls required to update the term_node table. But note well - this function does bite! It removes the original images from the source directory - so save them first if you need them retained.