/[drupal]/contributions/modules/flashnode/flashnode.import.inc
ViewVC logotype

Contents of /contributions/modules/flashnode/flashnode.import.inc

Parent Directory Parent Directory | Revision Log Revision Log | View Revision Graph Revision Graph


Revision 1.7 - (show annotations) (download) (as text)
Thu Mar 6 21:25:06 2008 UTC (20 months, 3 weeks ago) by stuartgreenfield
Branch: MAIN
CVS Tags: DRUPAL-6--2-2, DRUPAL-6--2-1, DRUPAL-6--2-0, DRUPAL-6--3-0, DRUPAL-6--3-1, DRUPAL-6--1-1, HEAD
Branch point for: DRUPAL-6--2, DRUPAL-6--3
Changes since 1.6: +8 -5 lines
File MIME type: text/x-php
#228731 - under some versions of PHP5 the import function failed as a trailing slash was appended to the file path when calling realpath(). This formed bad paths which broke the import routine. This is now fixed. Thanks to wildwildwaist (drupal.org/user/251357) for reporting and helping with the debugging of this one.
1 <?php
2 // $Id: flashnode.import.inc,v 1.6 2008/02/26 22:45:39 stuartgreenfield Exp $
3
4
5 /**
6 * Generate Flash import form
7 * The returned form varies depending on the state. It presents either a list of files
8 * available for import, or a confirmation form if some files have been selected for import
9 */
10 function flashnode_import($form_state) {
11
12 // If form was submitted and some files were checked, then return confirmation form
13 if ($form_state['submitted'] && array_filter($form_state['values']['files'])) {
14 return flashnode_import_confirm($form_state, array_filter($form_state['values']['files']));
15 }
16
17 // Otherwise retrieve the form showing a list of available files to import
18 $form['flashnode_import'] = flashnode_import_form();
19
20 // Return the form
21 return $form;
22 }
23
24
25 /**
26 * Form definition function to show list of files available for import
27 */
28 function flashnode_import_form() {
29
30 $form['help'] = array(
31 '#value' => t('
32 <p>This feature can be used to import files directly and create Flash nodes from them. This can be useful for importing batches of files that have been uploaded to the server, or to import files that are too large to be uploaded via the node creation form. Note that files that are imported do not respect file size limitations that would apply to files uploaded via the node form. Nodes that are created by this import function will @published.</p>
33 <p>The import function will scan the %directory directory and sub-directories to locate files for import.</p>',
34 array(
35 '%directory' => base_path().file_create_path(variable_get('flashnode_default_path', FLASHNODE_DEFAULT_PATH)),
36 '@published' => variable_get('flashnode_default_import_status', FLASHNODE_DEFAULT_IMPORT_STATUS) ? t('be published') : t('not be published'),
37 )),
38 );
39
40 // Get the list of files that aren't in the database
41 $filesnotindb = _flashnode_filesnotindb();
42
43 // Output count of files not in the database
44 if ($filesnotindb) {
45 $form['count'] = array(
46 '#value' => format_plural(count($filesnotindb), '1 file found.', '@count files found.') . t(' Select the file(s) you want to import, then click \'Import checked files\'.'),
47 );
48 }
49 else {
50 $form['count'] = array(
51 '#value' => t('No files were found for import.'),
52 );
53 }
54
55 // Process each result in turn and build check box list
56 $files=array();
57
58 foreach ($filesnotindb as $file) {
59
60 $files[$file] = '';
61
62 // Can't use file_create_url as the links fail if the site uses private transfers so force a public url instead
63 $form['file'][$file] = array('#value' => l(str_replace(file_create_path(variable_get('flashnode_default_path', FLASHNODE_DEFAULT_PATH)).'/', '', $file), $GLOBALS['base_url'] .'/'. $file));
64 }
65
66 // Add list of files to checkboxes
67 $form['files'] = array('#type' => 'checkboxes', '#options' => $files);
68
69 // Submit button to process form
70 $form['submit'] = array(
71 '#type' => 'submit',
72 '#value' => t('Import checked files'),
73 );
74
75 // Specify theme for form
76 $form['#theme'] = 'flashnode_import_form';
77
78 return $form;
79
80 }
81
82
83 /**
84 * Return an array of files that are not currently in the {files} table
85 */
86 function _flashnode_filesnotindb() {
87
88 // Prepare array to hold results
89 $filesnotindb = array();
90
91 // Get all the files out the {files} table and store as qualified path
92 $result = db_query('SELECT filepath FROM {files} ORDER BY filepath ASC');
93 $filesindb = array();
94 while ($file = db_fetch_object($result)) {
95 $filesindb[] = file_create_path($file->filepath);
96 }
97
98 // Get all the files out of the directory structure
99 $filesonserver = _flashnode_directorytoarray(realpath(file_create_path(variable_get('flashnode_default_path', FLASHNODE_DEFAULT_PATH))), TRUE);
100
101 // Sort the rows to make it easier to compare to file listing in FTP
102 asort($filesonserver);
103
104 // Get the root path - will need this later
105 $root = realpath('.');
106
107 // Process each result in turn
108 foreach ($filesonserver as $file) {
109
110 // Strip out the root path to leave just a drupal path
111 $file = preg_replace('@'.preg_quote($root).'.@', '', $file);
112
113 // Correct for Windows using \ in place of /
114 $file = str_replace("\\", "/", $file);
115
116 // Check it isn't a directory - not interested
117 if (!file_check_directory($file)) {
118
119 // Check to see if file is NOT in the database
120 if (!in_array($file, $filesindb) ) {
121
122 // If we get here we have a file that isn't in the database
123 $filesnotindb[] = $file;
124 }
125 }
126 }
127
128 return $filesnotindb;
129 }
130
131
132 /**
133 * Helper function - recurse directories and files in to an array
134 * http://snippets.dzone.com/posts/show/155
135 */
136 function _flashnode_directorytoarray($directory, $recursive) {
137 $array_items = array();
138 if ($handle = opendir($directory)) {
139 while (false !== ($file = readdir($handle))) {
140 if ($file != "." && $file != "..") {
141 if (is_dir($directory. "/" . $file)) {
142 if ($recursive) {
143 $array_items = array_merge($array_items, _flashnode_directorytoarray($directory. "/" . $file, $recursive));
144 }
145 $file = $directory . "/" . $file;
146 $array_items[] = preg_replace("/\/\//si", "/", $file);
147 }
148 else {
149 $file = $directory . "/" . $file;
150 $array_items[] = preg_replace("/\/\//si", "/", $file);
151 }
152 }
153 }
154 closedir($handle);
155 }
156 return $array_items;
157 }
158
159
160 /**
161 * Theme flashnode_import_form
162 */
163 function theme_flashnode_import_form($form) {
164
165 // Render help message
166 $output .= drupal_render($form['help']);
167
168 // Render count
169 $output .= drupal_render($form['count']);
170
171 // If there are files found
172 if (isset($form['file']) && is_array($form['file'])) {
173
174 // Construct table of files
175 $header = array(
176 theme('table_select_header_cell'),
177 t('File')
178 );
179
180 foreach (element_children($form['file']) as $key) {
181 $row = array();
182 $row[] = drupal_render($form['files'][$key]);
183 $row[] = drupal_render($form['file'][$key]);
184 $rows[] = $row;
185 }
186
187 // Render themed table
188 $output .= theme('table', $header, $rows);
189
190 // Render actions
191 $output .= drupal_render($form['submit']);
192
193 }
194
195 // Return output
196 return $output;
197 }
198
199
200 /**
201 * Submit handler for flashnode_import_form - simply populates data before redisplaying form
202 */
203 function flashnode_import_submit($form, &$form_state) {
204 // Force rebuild to populate form data
205 $form_state['rebuild'] = TRUE;
206 }
207
208
209 /**
210 * Confirmation form for user to confirm import of selected items
211 */
212 function flashnode_import_confirm(&$form_state, $files = array()) {
213
214 $form['files'] = array('#prefix' => '<ul>', '#suffix' => '</ul>', '#tree' => TRUE);
215
216 // array_filter in the call returned only elements with TRUE values
217 foreach ($files as $file) {
218 $form['files'][$file] = array('#type' => 'hidden', '#value' => $file, '#prefix' => '<li>', '#suffix' => check_plain(str_replace(file_create_path(variable_get('flashnode_default_path', FLASHNODE_DEFAULT_PATH)).'/', '', $file)) ."</li>\n");
219 }
220 $form['operation'] = array('#type' => 'hidden', '#value' => 'import');
221 $form['#submit'][] = 'flashnode_import_confirm_submit';
222
223 return confirm_form(
224 $form,
225 t('Are you sure you want to import these items?'),
226 'admin/content/flashnode',
227 '',
228 t('Import'),
229 t('Cancel')
230 );
231 }
232
233
234 /**
235 * Submit handler for import confirmation
236 * This function does the actual import of each selected file
237 */
238 function flashnode_import_confirm_submit($form, &$form_state) {
239
240 if ($form_state['values']['confirm']) {
241 foreach ($form_state['values']['files'] as $file) {
242 flashnode_import_file($file);
243 }
244 }
245 $form_state['redirect'] = 'admin/content/node';
246 return;
247 }
248
249
250 /**
251 * Import function called by flashnode_import_confirm_submit
252 * It is called once for each file that is to be imported
253 * $file_to_import is a Drupal path to a file for import
254 */
255 function flashnode_import_file($file_to_import) {
256
257 // Need to access the user object
258 global $user;
259
260 // Initialise a node and file object
261 $node = new stdClass();
262 $file = new stdClass();
263
264 // Populate basic data in to the node
265 $node->title = check_plain(basename($file_to_import));
266 $node->uid = $user->uid;
267 $node->type = 'flashnode';
268
269 // Get default node options for flashnode
270 $node_options = variable_get('node_options_flashnode', array('status', 'promote'));
271
272 // Process the array to add items to node
273 foreach (array('promote', 'sticky', 'revision') as $key) {
274 $node->$key = in_array($key, $node_options);
275 }
276
277 // Apply comment setting - use value 2 as default. Could refer to a constant but
278 // if comment module not enabled then COMMENT_NODE_READ_WRITE is not defined
279 $node->comment = variable_get('comment_flashnode', 2);
280
281 // Assign publish status (over-ride node defaults with import default)
282 $node->status = variable_get('flashnode_default_import_status', FLASHNODE_DEFAULT_IMPORT_STATUS);
283
284 // Try to get the file settings for this file, using image_get_info
285 $info = image_get_info(realpath($file_to_import));
286 $node->flashnode['height'] = $info['height'];
287 $node->flashnode['width'] = $info['width'];
288 $file->filemime = $info['mime_type'];
289
290 // Set other flash node defaults
291 $node->flashnode['display'] = variable_get('flashnode_default_display', FLASHNODE_TEASER_AND_BODY);
292 $node->flashnode['substitution'] = '!default';
293 $node->flashnode['base'] = variable_get('flashnode_default_base', base_path().file_directory_path());
294
295 // Set a flag to tell flashnode_insert we are adding files via import - currently suppresses file validation
296 $node->flashnode['import'] = TRUE;
297
298 // Prepare the file object
299 $file->uid = $user->uid;
300 $file->filename = basename($file_to_import);
301 $file->filepath = $file_to_import;
302 $file->status = FILE_STATUS_PERMANENT;
303 $file->timestamp = time();
304 $file->filesize = filesize(realpath($file_to_import));
305
306 // If we didn't get mime type from earlier attempt we will need to try and guess it from the extension
307 if (!$file->filemime) {
308 if (preg_match('@swf|flv|mp3$@i', $file->filename, $matches)) {
309 switch (strtolower($matches[0])) {
310 case 'mp3':
311 $file->filemime = 'audio/mpeg';
312 break;
313 case 'flv':
314 default:
315 $file->filemime = 'application/octet-stream';
316 }
317 }
318 }
319
320 // Write file to the database
321 drupal_write_record('files', $file);
322
323 // Add fid to the flashnode object
324 $node->flashnode['fid'] = db_last_insert_id('files', 'fid');
325
326 // Save the node
327 node_save($node);
328
329 // Show a status message
330 // If successful, show message and write an entry to the watchdog
331 // If unsuccessful only show on the screen
332
333 // Reduce $file_to_import to simple name
334 $file_to_import = str_replace(file_create_path(variable_get('flashnode_default_path', FLASHNODE_DEFAULT_PATH)).'/', '', $file_to_import);
335
336 // Show appropriate message - $node->nid only exists if node_save succeeded
337 if ($node->nid) {
338 drupal_set_message('Imported '.$file_to_import);
339 $watchdog_args = array('@type' => $node->type, '%title' => $node->title);
340 $node_link = l(t('view'), 'node/'. $node->nid);
341 watchdog('content', '@type: imported %title.', $watchdog_args, WATCHDOG_NOTICE, $node_link);
342 }
343 else {
344 drupal_set_message('Failed to import '.$file_to_import, 'warning');
345 }
346
347 return;
348
349 }

  ViewVC Help
Powered by ViewVC 1.1.2