aboutsummaryrefslogtreecommitdiff
path: root/mass_image_import.module
blob: ae4c844d986ef1301d15dbe657c8d72d34915144 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
<?php
// $Id$

/**
 * @file
 * Mass image import module.
 *
 * This module implements a bulk image import operation and uses
 * code from image_import module.
 */

/**
 * Implementation of hook_menu().
 */
function mass_image_import_menu() {
  $items['admin/content/mass_image_import'] = array(
    'title'            => t('Mass image import'),
    'description'      => t('Import tons of images at once.'),
    'page callback'    => 'mass_image_import',
    'access arguments' => array('administer content'),
    'type'             => MENU_NORMAL_ITEM,
  );

  return $items;
}

/**
 * Include image_import helper functions.
 */
require_once drupal_get_path('module', 'image_import') .'/image_import.pages.inc';

/**
 * Menu callback.
 */
function mass_image_import() {
  $output  = t('Mass image import.');
  $output .= drupal_get_form('mass_image_import_form');
  return $output;
}

/**
 * Mass import form.
 */
function mass_image_import_form(&$form_state) {
  $form['submit'] = array(
    '#type'  => 'submit',
    '#value' => t('Import images'),
  );
  return $form;
}

/**
 * Handle post-validation form-submission.
 */
function mass_image_import_form_submit($form, &$form_state) {
  // Setup batch configuration
  $batch = array(
    'title'            => t('Importing images'),
    'operations'       => array(array('mass_image_import_batch', array())),
    'finished'         => 'mass_image_import_batch_finished',
    'file'             => drupal_get_path('module', 'bcc') . '/bcc.import.inc',
  );

  // Run batch for operations
  batch_set($batch);
  batch_process();
}

/**
 * Batch operation callback for image import.
 */
function mass_image_import_batch(&$context) {
  if (empty($context['sandbox'])) {
    // Log
    watchdog('image', 'Starting mass image import.');

    $files                          = mass_image_import_get_files();
    $context['sandbox']['images']   = $files;
    $context['sandbox']['progress'] = 0;
    $context['sandbox']['max']      = count($files);
  }

  $limit = variable_get('image_import_page_size', 50);

  for ($n = 0; $n <= $limit; $n++) {
    if ($context['sandbox']['progress'] >= $context['sandbox']['max']) {
      $context['finished'] = 1;
      break;
    }

    $context['finished']  = $context['sandbox']['progress'] / $context['sandbox']['max'];
    $image                = $context['sandbox']['images'][$context['sandbox']['progress']];
    $context['results'][] = $image->filename;
    $context['message']   = t('Importing @file...',
        array(
          '@file' => $image->filename,
          ));

    mass_image_import_file($image);
    $context['sandbox']['progress']++;
  }
}

/**
 * Make a list of image files.
 *
 * @return
 *   List of available images for import.
 */
function mass_image_import_get_files() {
  $dirpath = variable_get('image_import_path', '');
  if (!file_check_directory($dirpath)) {
    drupal_set_message(
      t("You need to configure the import directory on the image import module's <a href='!admin-settings-import'>settings page</a>.",
      array('!admin-settings-import' => url('admin/settings/image/image_import'))), 'error');
    return;
  }

  // Get file names
  $files = file_scan_directory($dirpath, '.*');
  if (!$files) {
    return;
  }

  // Sort
  ksort($files);

  // Convert to indexed array
  foreach ($files as $file) {
    $images[] = $file;
  }

  return $images;
}

/**
 * Import a single file.
 *
 * @param $file
 *   Image object to import.
 *
 * @todo
 *   Switch between image_create_node_from and mass_image_import_create_node_from.
 */
function mass_image_import_file($file) {
  $dirpath  = variable_get('image_import_path', '');
  $origname = $file->basename;

  // Assembly import data
  $file_metadata_modules = module_implements('file_metadata');

  $problems = image_import_validate_file($file);
  // Allow other modules to supply metadata about the images being imported.
  // hook_file_metadata() may populate the $file properties 'title' and
  // 'description'.
  foreach ($file_metadata_modules as $module) {
    $function = $module . '_file_metadata';
    $function($file);
  }

  // Build form
  if ($filepath = file_check_location($dirpath .'/'. $origname, $dirpath)) {
    $args = array(
      'node_type'  => 'image',
      'title'      => isset($file->title) ? $file->title : basename($file->name),
      'body'       => isset($file->body)  ? $file->body  : basename($file->name),
      'taxonomy'   => isset($form_state['values']['taxonomy']) ? $form_state['values']['taxonomy'] : array(),
      'filepath'   => $filepath,
      'origname'   => $origname,
    );
  }

  // Create the node object.
  //if ($node = image_create_node_from($args['filepath'], $args['title'], $args['body'], $args['taxonomy'])) {
  if ($node = mass_image_import_create_node_from($args['filepath'], $args['title'], $args['body'], $args['taxonomy'])) {
    // Remove the original image now that the import has completed.
    file_delete($args['filepath']);
  }
  else {
    watchdog('image_import', 'There was an error that prevented %filename from being imported.',
      array('%filename' => $args['filepath']), WATCHDOG_ERROR);
  }
}

/**
 * Callback for image import.
 */
function mass_image_import_batch_finished($success, $results, $operations) {
  if ($success) {
    if (count($results) > 0) {
      $message = format_plural(count($results), t('One image processed.'), t('@count images processed.'));
    }
    else {
      $message = t('No images to import.');
    }
  }
  else {
    $message = t('Finished with an error.'); 
  }

  // Log
  watchdog('image', 'Finished mass image import.');
  drupal_set_message($message);
}

/**
 * Create an image entry. Contains some code from image_create_node_from().
 *
 * @see
 *   http://drupal.org/node/330421#comment-2806336
 *
 * @todo
 *   Mime, content type, field name, taxonomy, etc.
 */
function mass_image_import_create_node_from($filepath, $title, $body, $taxonomy) {

  $type  = 'foto';
  $field = 'foto';
  $uid   = 1;

  // Make sure we can copy the file into our temp directory.
  $original_path = $filepath;
  if (!file_copy($filepath, _image_filename($filepath, IMAGE_ORIGINAL, TRUE))) {
    return FALSE;
  }

  // File data.
  $file            = new stdClass();
  $file->filename  = basename($filepath);
  $file->filepath  = $filepath;
  $file->filemime  = file_get_mimetype($filepath);
  $file->filesize  = filesize($filepath);
  $file->uid       = $uid;
  $file->timestamp = time();
  drupal_write_record('files', $file);

  // Create the node.
  $node        = new StdClass();
  $node->type  = $type;

  // Add image field.
  $files                                  = array();
  $files[0]                               = (array) $file;
  $files[0]['status']                     = 0;

  // Node form.
  $form_state                             = array();
  $form_state['values']['type']           = $type;
  $form_state['values']['title']          = $title;
  $form_state['values']['body']           = $body;
  $form_state['values']['op']             = t('Save');
  $form_state['values']['field_'. $field] = $files;  

  // Submit.
  module_load_include('inc', 'node', 'node.pages');
  drupal_execute($type .'_node_form', $form_state, $node);
  return $node;
}