/[drupal]/contributions/modules/flickrup/flickrup.module
ViewVC logotype

Contents of /contributions/modules/flickrup/flickrup.module

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


Revision 1.3 - (show annotations) (download) (as text)
Thu Jul 31 14:03:38 2008 UTC (15 months, 3 weeks ago) by diggersf
Branch: MAIN
CVS Tags: HEAD
Changes since 1.2: +0 -5 lines
File MIME type: text/x-php
Removed call to undefined function.
1 <?php
2 /**
3 * @file
4 * Flickr Uploading module
5 *
6 * Notes:
7 * - Requires phpFlickr package, http://phpflickr.com/. Using v2.1.0
8 * - To get the Flickr auth token, you can use http://phpflickr.com/tools/auth/
9 * and follow the steps there (you'll need a key with 'write' permissions).
10 *
11 * Developed by Jose A. Reyero
12 * Development Seed, http://www.developmentseed.org
13 **/
14
15 /**
16 * Implementation of hook_help()
17 */
18 function flickrup_help($section) {
19 switch ($section) {
20 case 'admin/help#flickrup':
21 $output = '<p>'.t('Flickr Upload module features:').'</p><ul>';
22 $output .= '<li>'.t('Allows uploading images to Flickr from your site.').'</li>';
23 $output .= '<li>'.t('Images can be linked to nodes using per content type settings.').'</li>';
24 $ouptut .= '<li>'.t('Tags can be configured globally or using node parameters.').'</li>';
25 $output .= '</ul>';
26 $output .= '<p>'.t('The images are uploaded first to the web server, then from there to your Flickr account. This may have some important performance impact on the web server, so please review carefully the module settings for production servers.').'</p>';
27 $output .= '<p><small>'.t('This module uses <a href="http://phpflickr.com/">phpFlickr</a> to interact with the Flickr API.').'</small></p>';
28 return $output;
29 case 'admin/settings/flickrup':
30 $output = '<p>'.t('In adition to your normal flickr settings this module needs a Flickr authentication token with write permissions for your account. If you don\'t know how to get one, <a href="http://phpflickr.com/tools/auth/" >follow the steps here</a>.').'</p>';
31 return $output;
32 }
33
34 }
35
36 /**
37 * Implementation of hook_menu().
38 */
39 function flickrup_menu($may_cache) {
40 global $user;
41
42 $items = array();
43 if ($may_cache) {
44 $items[] = array(
45 'path' => 'admin/settings/flickrup', 'title' => t('Flickr Uploading'),
46 'callback' => 'drupal_get_form',
47 'callback arguments' => array('flickrup_admin_settings'),
48 'access' => user_access('administer site configuration'),
49 'type' => MENU_NORMAL_ITEM,
50 'description' => t('Change settings for the flickr upload module.')
51 );
52 $items[] = array(
53 'path' => 'flickrup/js',
54 'callback' => 'flickrup_js',
55 'access' => user_access('upload photos to all nodes') || user_access('upload photos to own nodes'),
56 'type' => MENU_CALLBACK,
57 );
58
59 // Testing
60 /*
61 $items[] = array(
62 'path' => 'flickr/upload',
63 'title' => t('Upload to Flickr'),
64 'callback' => 'flickrup_page_upload',
65 'access' => user_access('upload photos to nodes'),
66 );
67 */
68 } else {
69 // Upload to nodes
70 if (arg(0) == 'node' && is_numeric(arg(1)) && ($node = node_load(arg(1))) && variable_get('flickr_upload_type_'.$node->type, 0)) {
71 $items[] = array('path' => 'node/'. arg(1) .'/flickr', 'title' => t('Upload photos'),
72 'callback' => 'flickrup_page_node_upload',
73 'callback arguments' => array($node),
74 'access' => user_access('upload photos to all nodes') || ($node->uid == $user->uid && user_access('upload photos to own nodes')),
75 'weight' => 4,
76 'type' => MENU_LOCAL_TASK
77 );
78 if (variable_get('flickr_node_view', 'tab') == 'tab') {
79 $items[] = array('path' => 'node/'. arg(1) .'/photos', 'title' => t('Photos'),
80 'callback' => 'flickrup_page_node_view',
81 'callback arguments' => array($node),
82 'access' => user_access('access content'),
83 'weight' => 2,
84 'type' => MENU_LOCAL_TASK
85 );
86 }
87 }
88 }
89 return $items;
90 }
91
92 /**
93 * Menu/form callback. Settings form
94 */
95 function flickrup_admin_settings() {
96 $form['flickr_api_token'] = array(
97 '#type' => 'textfield',
98 '#title' => t('API Auth token'),
99 '#required' => TRUE,
100 '#default_value' => variable_get('flickr_api_token', ''),
101 '#description' => t('API Auth Token from Flickr with \'write\' permission'),
102 );
103 $form['flickr_global_tag'] = array(
104 '#type' => 'textfield',
105 '#title' => t('Global Flickr tags'),
106 '#required' => TRUE,
107 '#default_value' => variable_get('flickr_global_tag', ''),
108 '#description' => t('Enter space separated global tags to apply to all the uploads from this site.'),
109 );
110 $form['flickrup_remove'] = array(
111 '#type' => 'checkbox',
112 '#title' => t('Delete photos from Flickr when they are removed from a node'),
113 '#default_value' => variable_get('flickrup_remove', ''),
114 );
115
116 // Upload options
117 $form['upload'] = array('#type' => 'fieldset', '#title' => t('Upload options'));
118 $form['upload']['flickr_upload_fields'] = array(
119 '#type' => 'textfield',
120 '#title' => t('Number of upload fields'),
121 '#default_value' => variable_get('flickr_upload_fields', 1),
122 '#description' => t('Enter the number of image fields for the upload form. Be warned that this may have an important impact on server performance. The minimum number is 1'),
123 );
124 $form['upload']['flickr_upload_public'] = array(
125 '#type' => 'radios',
126 '#title' => t('Upload mode'),
127 '#options' => array(t('Private'), t('Public')),
128 '#default_value' => variable_get('flickr_upload_public', 1),
129 '#description' => t('Select whether you want your uploaded images to be private or public'),
130 );
131 $form['upload']['flickr_upload_async'] = array(
132 '#type' => 'checkbox',
133 '#title' => t('Asynchronous uploading'),
134 '#default_value' => variable_get('flickr_upload_async', 0),
135 '#description' => t('Enable asynchronous uploading to Flickr to speed up the page request. This should be faster but we won\'t be able to control whether the Flickr upload has worked or not.'),
136 );
137 $form['upload']['flickr_upload_delete'] = array(
138 '#type' => 'checkbox',
139 '#title' => t('Delete images from server'),
140 '#default_value' => variable_get('flickr_upload_delete', 0),
141 '#description' => t('Delete images from the web server after uploading them to Flickr. This is currently not compatible with asynchronous uploading.'),
142 );
143 // Check whether the picture directory exists:
144 $picture_path = file_create_path(variable_get('flickr_picture_path', 'flickr'));
145 file_check_directory($picture_path, 1, 'flickr_picture_path');
146
147 // Image file settings
148 $form['pictures'] = array('#type' => 'fieldset', '#title' => t('Pictures'));
149 $form['pictures']['flickr_picture_path'] = array('#type' => 'textfield', '#title' => t('Picture image path'), '#default_value' => variable_get('flickr_picture_path', 'flickr'), '#size' => 30, '#maxlength' => 255, '#description' => t('Subdirectory in the directory %dir where pictures will be stored.', array('%dir' => file_directory_path() .'/')));
150 $form['pictures']['flickr_picture_dimensions'] = array('#type' => 'textfield', '#title' => t('Picture maximum dimensions'), '#default_value' => variable_get('flickr_picture_dimensions', '800x600'), '#size' => 15, '#maxlength' => 10, '#description' => t('Maximum dimensions for pictures, in pixels.'));
151 $form['pictures']['flickr_picture_file_size'] = array('#type' => 'textfield', '#title' => t('Picture maximum file size'), '#default_value' => variable_get('flickr_picture_file_size', '1000'), '#size' => 15, '#maxlength' => 10, '#description' => t('Maximum file size for pictures, in kB.'));
152
153 $form['flickr_node_view'] = array(
154 '#type' => 'radios',
155 '#title' => t('Show images for nodes'),
156 '#options' => array(
157 'none' => t('Do not show'),
158 'body' => t('Show in the node body'),
159 'tab' => t('Show in a different tab')
160 ),
161 '#default_value' => variable_get('flickr_node_view', 'tab'),
162 '#description' => t('Select whether you want to display images with the content they were uploaded for.'),
163 );
164 return system_settings_form($form);
165 }
166 /**
167 * Implementation of hook_perms()
168 */
169 function flickrup_perm() {
170 return array('upload photos to all nodes', 'upload photos to own nodes');
171 }
172
173 /**
174 * Implementation of hook_form_alter()
175 */
176 function flickrup_form_alter($form_id, &$form) {
177 if (isset($form['type'])) {
178 if ($form['type']['#value'] .'_node_form' == $form_id) {
179 $type = content_types($form['type']['#value']);
180 foreach ($type['fields'] as $name => $field) {
181 if ($field['type'] == 'flickrfield' && $field['widget']['type'] == 'flickrup') {
182 drupal_add_js('misc/progress.js');
183 drupal_add_js('misc/upload.js');
184 $form['#attributes']['enctype'] = 'multipart/form-data';
185 }
186 }
187 }
188 }
189
190 if ($form_id == 'node_type_form' && isset($form['identity']['type'])) {
191 $type = $form['#node_type']->type;
192
193 $description = '<p>' . t('Some variables you can use in your tags are:').'</p>';
194 foreach (flickrup_node_variables('list', $type) as $key => $name) {
195 $items[] = '<strong>'.$key.'</strong> - '.$name;
196 }
197 $description .= theme('item_list', $items);
198 $form['workflow']['flickr'] = array(
199 '#type' => 'fieldset',
200 '#title' => t('Flickr settings'),
201 '#description' => $description,
202 );
203 $form['workflow']['flickr']['flickr_upload_type'] = array(
204 '#type' => 'radios',
205 '#title' => t('Enable Flickr upload'),
206 '#default_value' => variable_get('flickr_upload_type_'.$type, 0),
207 '#options' => array(t('Disabled'), t('Enabled')),
208 '#description' => t('Upload photos to Flickr for this content.'),
209 );
210 $form['workflow']['flickr']['flickr_upload_tag'] = array(
211 '#type' => 'textfield',
212 '#title' => t('Automatic Upload tags'),
213 '#default_value' => variable_get('flickr_upload_tag_'.$type, ''),
214 '#description' => t('Tags for this content type separated by spaces') ,
215 );
216 $form['workflow']['flickr']['flickr_display_tag'] = array(
217 '#type' => 'textfield',
218 '#title' => t('Tags for display'),
219 '#default_value' => variable_get('flickr_display_tag_'.$type, variable_get('flickr_upload_tag_'.$type, '')),
220 '#description' => t('Tags that will be used for node display. They will default to upload tags.') ,
221 );
222 }
223 }
224
225 /**
226 * Node variables
227 */
228
229 function flickrup_node_variables($op, $param) {
230 switch ($op) {
231 case 'list': // Param is node type
232 $variables = array(
233 '[nid]' => t('The id number of the node.'),
234 '[type]' => t('The node type (e.g., "page", "story", etc.).'),
235 '[yyyy]' => t('The year the node was created.'),
236 );
237 break;
238 case 'values': // Param is node object
239 $variables = array(
240 '[nid]' => $param->nid,
241 '[type]' => $param->type,
242 '[yyyy]' => date('Y', $param->created),
243 );
244
245 }
246 // Integration with location variables
247 if (module_exists('location') ) {
248 $variables += flickrup_node_variables_location($op, $param);
249 }
250 return $variables;
251 }
252
253 function flickrup_node_variables_location($op, $param) {
254 $variables = array();
255 switch ($op) {
256 case 'list':
257 if (variable_get('location_maxnum_'. $param, 0)) {
258 $variables += array(
259 '[city]' => t('City name'),
260 '[state]' => t('State or province name'),
261 '[country]' => t('Country name'),
262 );
263 }
264 break;
265 case 'values':
266 // Empty values to be overriden
267 $variables['[city]'] = '';
268 $variables['[country]'] = '';
269 $variables['[state]'] = '';
270
271 if ($param->location) {
272 $location = $param->location;
273 //var_dump($location);
274 if (!empty($location['city'])) {
275 $variables['[city]'] = flickrup_cleanstring($location['city']);
276 }
277 if (!empty($location['country'])) {
278 $countries = _location_get_iso3166_list();
279 $variables['[country]'] = flickrup_cleanstring(t($countries[$location['country']]));
280 }
281 if (!empty($location['province'])) {
282 $variables['[state]'] = flickrup_cleanstring($location['province']);
283 }
284 }
285 }
286 return $variables;
287 }
288
289 /**
290 * Implementation of hook_nodeapi().
291 *
292 * Show flickr images for this content
293 */
294 function flickrup_nodeapi(&$node, $op, $teaser = NULL, $page = NULL) {
295 switch ($op) {
296 case 'view';
297 if (variable_get('flickr_upload_type_'.$node->type, 0) && variable_get('flickr_node_view', 'tab') == 'body') {
298 $node->content['photos'] = array(
299 '#value' => theme('flickrup_node_photos', $node),
300 '#weight' => 100,
301 );
302 }
303 break;
304 }
305 }
306
307 /**
308 * Quick node pictures presentation using the node tags
309 */
310 function theme_flickrup_node_photos($node, $width = 480, $height = 480) {
311 $output = '';
312 if ($tags = flickrup_node_tags($node, TRUE)) {
313 $tagstring = implode('%2C', $tags);
314 $src = "http://www.flickr.com/slideShow/index.gne?user_id=&set_id=&tags=$tagstring&tag_mode=all&text=";
315 $output .= "<iframe align=center src=\"$src\" frameBorder=0 width=$width scrolling=no height=$height></iframe>\n";
316 }
317 return $output;
318 }
319 /**
320 * Menu callback. Upload photos to node
321 */
322 function flickrup_page_node_upload($node) {
323 drupal_set_title(t('Upload photos for %title', array('%title' => $node->title)));
324 $output = '';
325 // Get tags for this node type
326 $tags = flickrup_node_tags($node);
327
328 // Set default parameters
329 $params['title'] = $node->title;
330 $params['fixed_tags'] = implode(' ', $tags);
331 $output .= drupal_get_form('flickrup_upload_form', $params);
332 return $output;
333 }
334
335 /**
336 * Menu callback. View pictures for a node
337 */
338 function flickrup_page_node_view($node) {
339 drupal_set_title(t('Photos for %title', array('%title' => $node->title)));
340 $output = '';
341 $output .= theme('flickrup_node_photos', $node);
342
343 return $output;
344 }
345 /**
346 *
347 * Menu callback: upload page and form
348 *
349 * Arguments will be a list of tags
350 */
351 function flickrup_page_upload($op = '') {
352 $output = '';
353 // Get tags
354 $tags = func_get_args();
355 array_shift($tags);
356
357 switch ($op) {
358 case 'done':
359 $output .= flickrup_page_upload_done($tags);
360 break;
361 case 'tags':
362 default;
363 $output .= drupal_get_form('flickrup_upload_form', $tags);
364 break;
365 }
366 return $output;
367 }
368
369 function flickrup_page_upload_done($tags) {
370 $output = '';
371 $output .= 'Not implemented';
372 return $output;
373 }
374
375 /**
376 * Upload form
377 */
378 function flickrup_upload_form($params = array()) {
379 $form['#attributes']['enctype'] = 'multipart/form-data';
380 $form['title'] = array(
381 '#type' => 'textfield',
382 '#title' => t('Title'),
383 '#default_value' => empty($params['title']) ? '' : $params['title'],
384 );
385
386 if (!empty($params['fixed_tags'])) {
387 $form['fixed_tags'] = array(
388 '#type' => 'value',
389 '#value' => $params['fixed_tags'],
390 );
391 $form['info_tags'] = array(
392 '#type' => 'item',
393 '#title' => t('Predefined tags'),
394 '#value' => $params['fixed_tags'],
395 );
396 }
397
398 $form['custom_tags'] = array(
399 '#type' => 'textfield',
400 '#title' => t('Custom tags'),
401 '#description' => t('Flickr tags separated by spaces. You can add your own tags here.'),
402 );
403
404 $form['images'] = array(
405 '#type' => 'fieldset',
406 '#title' => t('Upload pictures'),
407 '#description' => t('Maximum dimensions are %dimensions and the maximum size is %size kB.', array('%dimensions' => variable_get('flickr_picture_dimensions', '800x600'), '%size' => variable_get('flickr_picture_file_size', '1000')))
408 );
409 for($i=1; $i<= variable_get('flickr_upload_fields', 1); $i++) {
410 $field = 'upload'.$i;
411 // There may be uploaded images waiting in the session object. These will override
412 // the upload fields using hook_after build
413 $form['images'][$field] = array(
414 '#title' => t('Image %number', array('%number' => $i)),
415 '#type' => 'file',
416 '#size' => 48,
417 );
418 }
419 // Add preloaded images after the form has been built and validated
420 //$form['#after_build'][] = 'flickrup_upload_form_previews';
421 // We use form theming for that
422
423 $form['submit'] = array(
424 '#type' => 'submit',
425 '#value' => t('Upload'),
426 );
427 $form['reset'] = array(
428 '#type' => 'submit',
429 '#value' => t('Reset'),
430 );
431 return $form;
432 }
433
434 /**
435 * Display image previews.
436 *
437 * I didn't find a better place to do this, as images are added in session on
438 * form validation, after the form has been built, including after_build
439 */
440 function theme_flickrup_upload_form($form) {
441 if (!empty($_SESSION['flickr_upload'])) {
442 foreach ($_SESSION['flickr_upload'] as $field => $file) {
443 // Cached image, just display
444 $form['images'][$field]['#type'] = 'item';
445 $form['images'][$field]['#value'] = theme('flickrup_image_preview', $file);
446 }
447 } else {
448 unset ($form['reset']);
449 }
450
451 return drupal_render($form);
452 }
453 /**
454 * Preview image
455 */
456 function theme_flickrup_image_preview($file, $width = 200, $height = 200) {
457 $output = '<div class="flickr-image-preview" >';
458 if ($info = image_get_info($file->filepath)) {
459 // don't scale up
460 if ($width >= $info['width'] && $height >= $info['height']) {
461 return FALSE;
462 }
463
464 $aspect = $info['height'] / $info['width'];
465 if ($aspect < $height / $width) {
466 $width = (int)min($width, $info['width']);
467 $height = (int)round($width * $aspect);
468 }
469 else {
470 $height = (int)min($height, $info['height']);
471 $width = (int)round($height / $aspect);
472 }
473 $src = file_create_url($file->filepath);
474 $output .= "<img src=\"$src\" width=$width height =$height />";
475
476 } else {
477 $output .= t('No image preview');
478 }
479 $output .= '</div>';
480 return $output;
481 }
482 /**
483 * Form callback. Validation
484 */
485 function flickrup_upload_form_validate($form_id, $values) {
486 global $form_values;
487
488 // Check for uploaded images.
489 $upload = FALSE;
490
491 // Set previously uploaded files into form values
492 if (!empty($_SESSION['flickr_upload'])) {
493 $upload = TRUE;
494 $form_values['files'] = $_SESSION['flickr_upload'];
495 }
496
497 for($i=1; $i<= variable_get('flickr_upload_fields', 1); $i++) {
498 $field = 'upload'.$i;
499 if ($file = file_check_upload($field)) {
500 $upload = TRUE;
501 flickrup_validate_picture($file, $field);
502 }
503 }
504
505 // Debug. Fire validation error
506 // form_set_error('images', 'Testing validation error');
507
508 // Final validation for files. If there are errors but also uploaded files,
509 // they will be kept in the session object.
510 if (!$upload) {
511 form_set_error('images', t('No files to upload'));
512 }
513 }
514
515 function flickrup_validate_picture($file, $field = 'upload') {
516 global $form_values;
517
518 // To check errors separately for each file
519 $error = FALSE;
520
521 // Check that uploaded file is an image, with a maximum file size
522 // and maximum height/width.
523 $info = image_get_info($file->filepath);
524 //dsm($file);
525 //dsm($info);
526 list($maxwidth, $maxheight) = explode('x', variable_get('flickr_picture_dimensions', '800x600'));
527
528 if (!$info || !$info['extension']) {
529 $error = TRUE;
530 form_set_error($field, t('The uploaded file was not an image.'));
531 }
532 else if (image_get_toolkit()) {
533 image_scale($file->filepath, $file->filepath, $maxwidth, $maxheight);
534 }
535 else if (filesize($file->filepath) > (variable_get('user_picture_file_size', '1000') * 1000)) {
536 $error = TRUE;
537 form_set_error($field, t('The uploaded image is too large; the maximum file size is %size kB.', array('%size' => variable_get('user_picture_file_size', '30'))));
538 }
539 else if ($info['width'] > $maxwidth || $info['height'] > $maxheight) {
540 $error = TRUE;
541 form_set_error($field, t('The uploaded image is too large; the maximum dimensions are %dimensions pixels.', array('%dimensions' => variable_get('user_picture_dimensions', '85x85'))));
542 }
543
544 if (!$error) {
545 if ($file = file_save_upload($file, variable_get('flickr_picture_path', 'flickr').'/'.$file->filename, FILE_EXISTS_RENAME)) {
546 $form_values['files'][$field] = $file;
547 // Store in session until it has been uploaded to flickr
548 $_SESSION['flickr_upload'][$field] = $file;
549 }
550 else {
551 form_set_error($field, t("Failed to upload the image file; the %directory directory doesn't exist or is not writable.", array('%directory' => variable_get('flickr_picture_path', 'flickr'))));
552 }
553 }
554 }
555 /**
556 * Form callback. Upload to Flickr.
557 */
558 function flickrup_upload_form_submit($form_id, $form_values) {
559 $op = isset($_POST['op']) ? $_POST['op'] : '';
560 $tags = array();
561
562 // Reset option for deleting preloaded images
563 if ($op == t('Reset')) {
564 foreach($form_values['files'] as $index => $file) {
565 file_delete($file->filepath);
566 }
567 unset($_SESSION['flickr_upload']);
568 drupal_set_message(t('The saved images have been deleted.'));
569 } else {
570 // Image submission to Flickr
571 foreach (array('fixed_tags', 'custom_tags') as $field) {
572 if (!empty($form_values[$field])) {
573 $tags[] = $form_values[$field];
574 }
575 }
576 if ($form_values['files']) {
577 $uploads = $errors = 0;
578 foreach ($form_values['files'] as $index => $file) {
579 if (flickrup_upload($file->filepath, $form_values['title'], $tags)) {
580 $uploads++;
581 // Delete files that may be stored in session
582 unset($_SESSION['flickr_upload'][$index]);
583 } else {
584 $errors++;
585 }
586 }
587 if ($uploads) {
588 drupal_set_message(t('Uploaded successfully %images.', array('%images' => format_plural($uploads, '@count image', '@count images'))));
589 }
590 if ($errors) {
591 drupal_set_message(t('Flickr Upload error with %images. The images have been stored in our local server though so you won\'t need to upload them again.', array('%images' => format_plural($uploads, '@count image', '@count images'))));
592 }
593 } else {
594 drupal_set_message(t('Drupal upload error. Please try again later or contact the site administrator.'), 'error');
595 }
596 }
597 }
598
599 /**
600 * Get tags for a node
601 *
602 * @param $node
603 * Node object to get the tags for
604 * @param $display
605 * TRUE to get only display tags
606 */
607 function flickrup_node_tags($node, $display = FALSE) {
608 $tags = array();
609 if ($tag = variable_get('flickr_global_tag', '')) {
610 $tags = array_merge($tags, explode(' ', $tag));
611 }
612 // Node display/upload tags
613 $tag = variable_get('flickr_upload_tag_'.$node->type, '');
614 $tag = $display ? variable_get('flickr_display_tag_'.$node->type, $tag): $tag;
615 if ($tag) {
616 // Apply variables to placeholders
617 if ($placeholders = flickrup_node_variables('values', $node)) {
618 $tag = str_replace(array_keys($placeholders), $placeholders, $tag);
619 }
620 $tags = array_merge($tags, explode(' ', $tag));
621 }
622
623 // Filter and organize
624 $tags = array_map('trim', $tags);
625 return $tags;
626 }
627
628 /**
629 * Actually upload photo to flickr
630 */
631 function flickrup_upload($path, $title = '', $tags = array(), $description = '') {
632 static $flickr; // Static caching for the flickr object to support multiple uploads
633
634 if (!isset($flickr)) {
635 require_once drupal_get_path('module', 'flickrup').'/phpFlickr/phpFlickr.php';
636 // Create the class with auth parameters
637 $flickr = new phpFlickr(trim(variable_get('flickr_api_key', '')), trim(variable_get('flickr_api_secret', '')));
638 $flickr->setToken(trim(variable_get('flickr_api_token', '')));
639 }
640
641 // Prepare tag string
642 if (is_array($tags) && !empty($tags)) {
643 $tagstring = implode(' ', $tags);
644 }
645
646 // Do sync or async uploading depending on options
647 if ($async = variable_get('flickr_upload_async', 0)) {
648 $result = $flickr->async_upload($path, $title, $description, $tagstring, variable_get('flickr_upload_public', 1), 0, 0);
649 // We asume success if no error code. The upload may still be going though
650 $success = $flickr->getErrorCode() ? FALSE : TRUE;
651 } else {
652 $result = $flickr->sync_upload($path, $title, $description, $tagstring, variable_get('flickr_upload_public', 1), 0, 0);
653 $success = $result;
654 }
655 // Log whatever has happened
656 $variables = array(
657 '%image-path' => $path,
658 '%tagstring' => $tagstring,
659 '%upload-mode' => ($async ? t('Asynchronous') : t('Synchronous')),
660 );
661
662 if ($success) { // Success
663 watchdog('flickr upload', t('Flickr successful (%upload-mode) Upload for image %image-path with tags %tagstring', $variables));
664 if (!$async && variable_get('flickr_upload_delete', 0)) {
665 file_delete($path);
666 }
667 } else { // Failure
668 $variables += array(
669 '!error-code' => $flickr->getErrorCode(),
670 '!error-message' => $flickr->getErrorMsg(),
671 );
672 watchdog('flickr upload', t('Flickr (%upload-mode) Upload error (!error-code - !error-message) for image %image_path with tags %tagstring', $variables), WATCHDOG_ERROR);
673 }
674 return $success;
675 }
676
677 /**
678 * Clean up a string value provided by a module, resulting in a
679 * string containing only alphanumerics and separators
680 *
681 * Code from pathauto_cleanstring() function, uses pathauto variables
682 */
683 function flickrup_cleanstring($string) {
684 // Default words to ignore
685 $ignore_words = array(
686 "a", "an", "as", "at", "before", "but", "by", "for", "from",
687 "is", "in", "into", "like", "of", "off", "on", "onto", "per",
688 "since", "than", "the", "this", "that", "to", "up", "via",
689 "with"
690 );
691
692 static $i18n_loaded = false;
693 static $translations = array();
694 if (!$i18n_loaded) {
695 $path = drupal_get_path('module', 'pathauto');
696 if (is_file($path. '/i18n-ascii.txt')) {
697 $translations = parse_ini_file($path. '/i18n-ascii.txt');
698 }
699 $i18n_loaded = true;
700 }
701
702 $output = strtr($output, $translations);
703
704 // Replace or drop apostrophes based on user settings
705 $separator = variable_get('pathauto_separator', '-');
706 $quotes = variable_get('pathauto_quotes', 0);
707 $output = str_replace("'", ($quotes ? $separator : ''), $string);
708
709 // Convert accented characters to their ASCII counterparts...
710 /* $output = strtr(utf8_decode($output),
711 "\xA1\xAA\xBA\xBF".
712 "\xC0\xC1\xC2\xC3\xC5\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF".
713 "\xD0\xD1\xD2\xD3\xD4\xD5\xD8\xD9\xDA\xDB\xDD".
714 "\xE0\xE1\xE2\xE3\xE5\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF".
715 "\xF0\xF1\xF2\xF3\xF4\xF5\xF8\xF9\xFA\xFB\xFD\xFF",
716 "!ao?AAAAACEEEEIIIIDNOOOOOUUUYaaaaaceeeeiiiidnooooouuuyy");
717 // ...and ligatures too
718 $output = utf8_encode(strtr($output, array("\xC4"=>"Ae", "\xC6"=>"AE", "\xD6"=>"Oe",
719 "\xDC"=>"Ue", "\xDE"=>"TH", "\xDF"=>"ss", "\xE4"=>"ae", "\xE6"=>"ae",
720 "\xF6"=>"oe", "\xFC"=>"ue", "\xFE"=>"th")));*/
721 $output = strtr($output, $translations);
722
723 // Get rid of words that are on the ignore list
724 $ignore_re = "\b". preg_replace("/,/", "\b|\b", variable_get('pathauto_ignore_words', $ignore_words)) ."\b";
725 $output = preg_replace("/$ignore_re/ie", "", $output);
726
727 // Preserve alphanumerics, everything else becomes a separator
728 $pattern = '/[^a-zA-Z0-9]+/ ';
729 $output = preg_replace($pattern, $separator, $output);
730
731 // Trim any leading or trailing separators (note the need to
732 // escape the separator if and only if it is not alphanumeric)
733 if ($separator) {
734 if (ctype_alnum($separator)) {
735 $seppattern = $separator;
736 }
737 else {
738 $seppattern = '\\'.$separator;
739 }
740 $output = preg_replace("/^$seppattern+|$seppattern+$/", "", $output);
741 }
742
743 // Enforce the maximum component length
744 $maxlength = min(variable_get('pathauto_max_component_length', 100), 128);
745 $output = drupal_substr($output, 0, $maxlength);
746
747 return $output;
748 }
749
750 /**
751 * Implementation of hook_widget_info().
752 */
753 function flickrup_widget_info() {
754 return array(
755 'flickrup' => array(
756 'label' => 'Flickr Upload',
757 'field types' => array('flickrfield'),
758 ),
759 );
760 }
761
762 /**
763 * Implementation of hook_widget().
764 */
765 function flickrup_widget($op, &$node, $field, &$items) {
766 static $submitted; // Work around for 'process form values' being called twice.
767
768 switch ($op) {
769 case 'prepare form values':
770 _flickrup_prepare($node, $field, $items);
771 break;
772 case 'form':
773 return _flickup_widget_form($node, $field, $items);
774 case 'validate':
775 break;
776 case 'submit':
777 $submitted = TRUE; // Work around for 'process form values' being called twice.
778 break;
779 case 'process form values':
780 if ($submitted) {
781 _flickrup_process($node, $field, $items);
782 }
783 break;
784 }
785 }
786
787 /**
788 * Implementation of hook_widget_settings().
789 */
790 function flickrup_widget_settings($op, $widget) {
791 switch ($op) {
792 case 'form':
793 $form['tags'] = array(
794 '#type' => 'textfield',
795 '#title' => t('Tags'),
796 '#description' => t('These tags will be assigned to photos uploaded using this field. Separate by spaces. This will only apply to future uploads.'),
797 '#size' => 40,
798 '#maxlength' => 255,
799 '#default_value' => $widget['tags'],
800 );
801 return $form;
802 case 'save':
803 return array('tags');
804 }
805 }
806
807 function _flickup_widget_form($node, $field, $items) {
808 require_once(drupal_get_path('module', 'flickr') .'/flickr.inc');
809 $form['flickrup'] = array(
810 '#type' => 'fieldset',
811 '#title' => t('Flickr upload'),
812 '#collapsible' => TRUE,
813 '#description' => t('Changes are not permanent until you save this post. Maximum dimensions are %dimensions and the maximum size is %size kB.', array('%dimensions' => variable_get('flickr_picture_dimensions', '800x600'), '%size' => variable_get('flickr_picture_file_size', '1000')))
814 );
815
816 $form['flickrup']['fieldname'] = array(
817 '#type' => 'hidden',
818 '#value' => $field['field_name'],
819 '#name' => 'flickrup-fieldname',
820 '#id' => 'flickrup-fieldname',
821 );
822
823 // Wrapper for fieldset contents (used by upload JS).
824 $form['flickrup']['wrapper'] = array(
825 '#prefix' => '<div id="flickrup-wrapper">',
826 '#suffix' => '</div>',
827 );
828
829 $form['flickrup']['wrapper'] += _flickrup_form($node, $field, $items);
830
831 return $form;
832 }
833
834 function _flickrup_form($node, $field = NULL, $items = array()) {
835 $form['#theme'] = 'flickrup_form_new';
836
837 if (count($items)) {
838 $form[$field['field_name']]['#theme'] = 'flickrup_form_current';
839 $form[$field['field_name']]['#tree'] = TRUE;
840 foreach ($items as $key => $item) {
841 $preview = $title = '';
842 if ($item['type'] == 'photo_id') {
843 // Remove photos that weren't found on flickr
844 if (!$photo = flickr_photo_get_info($item['id'])) {
845 unset($items[$key]);
846 break;
847 }
848 $item['title'] = $photo['title']['_content'];
849 $item['preview'] = flickr_img($photo, 's');
850 $form[$field['field_name']][$key]['flickr_photo'] = array('#type' => 'value', '#value' => $photo);
851 $form[$field['field_name']][$key]['id'] = array('#type' => 'value', '#value' => $item['id']);
852 }
853 elseif (is_object($item['file'])) {
854 $item['title'] = basename($item['file']->filename);
855 $item['preview'] = theme('image', $item['file']->filepath, '', '', array('height' => 75, 'width' => 75), FALSE);
856 $form[$field['field_name']][$key]['file'] = array('#type' => 'value', '#value' => $item['file']);
857
858 }
859 $form[$field['field_name']][$key]['type'] = array('#type' => 'value', '#value' => 'photo_id');
860 $form[$field['field_name']][$key]['nsid'] = array('#type' => 'value', '#value' => variable_get('flickr_default_userid', ''));
861 $form[$field['field_name']][$key]['preview'] = array(
862 '#type' => 'item',
863 '#value' => $item['preview'],
864 );
865 $form[$field['field_name']][$key]['remove'] = array(
866 '#type' => 'checkbox',
867 '#default_value' => $item['remove'],
868 );
869
870 $form[$field['field_name']][$key]['title'] = array(
871 '#type' => 'textfield',
872 '#description' => t('Link to flickr photo?'),
873 '#size' => 40,
874 '#maxlength' => 255,
875 '#default_value' => $item['title'],
876 );
877 }
878 }
879
880 $form['new'] = array(
881 '#prefix' => '<div id="flickrup-hide">',
882 '#suffix' => '</div>',
883 );
884 $form['new']['flickrfile'] = array(
885 '#title' => t('Upload new image'),
886 '#type' => 'file',
887 '#size' => 48,
888 );
889 $form['new']['flickrup'] = array(
890 '#type' => 'button',
891 '#value' => t('Upload'),
892 '#name' => 'flickrup',
893 '#id' => 'flickrup-button',
894 );
895
896 $form['flickrup-url'] = array('#type' => 'hidden', '#value' => url('flickrup/js', NULL, NULL, TRUE), '#attributes' => array('class' => 'upload'));
897
898 $form['current']['vid'] = array('#type' => 'hidden', '#value' => $node->vid);
899
900 return $form;
901 }
902
903 /**
904 * Theme the attachment form.
905 * Note: required to output prefix/suffix.
906 */
907 function theme_flickrup_form_new($form) {
908 $output = drupal_render($form);
909 return $output;
910 }
911
912 /**
913 * Theme current photos.
914 */
915 function theme_flickrup_form_current($form) {
916 $header = array(t('Preview'), t('Remove'), t('Title'));
917
918 foreach (element_children($form) as $key) {
919 $row = array();
920 $row[] = drupal_render($form[$key]['preview']);
921 $row[] = drupal_render($form[$key]['remove']);
922 $row[] = drupal_render($form[$key]['title']);
923 $rows[] = $row;
924 }
925 $output = theme('table', $header, $rows);
926 $output .= drupal_render($form);
927 return $output;
928 }
929
930 /**
931 * Save new uploads and attach them to the node object.
932 * append flickrup_previews to the node object as well.
933 */
934 function _flickrup_prepare(&$node, $field, &$items) {
935 $fieldname = $field['field_name'];
936 // Clear session variable and files that were leftover from previous uploading session
937 if(count($_POST) == 0) {
938 if (is_array($_SESSION['flickrup_previews']) && count($_SESSION['flickrup_previews'])) {
939 foreach ($_SESSION['flickrup_previews'] as $file) {
940 file_delete($file->filepath);
941 }
942 unset($_SESSION['flickrup_previews']);
943 }
944 }
945
946 if (($file = file_check_upload('flickrfile')) && user_access('upload photos to all nodes')) {
947 $key = 'flickrup_'. count($_SESSION['flickrup_previews']);
948 $file->fid = $key;
949 flickrup_validate_picture($file, 'flickrfile');
950 $_SESSION['flickrup_previews'][$key] = $file;
951 }
952
953 // Attach previews to node
954 if (is_array($_SESSION['flickrup_previews']) && count($_SESSION['flickrup_previews'])) {
955 foreach ($_SESSION['flickrup_previews'] as $fid => $file) {
956 $node->{$fieldname}[$fid] = $file;
957 $items[]['file'] = $file;
958 }
959 }
960 }
961
962 function _flickrup_process(&$node, $field, &$items) {
963 $fieldname = $field['field_name'];
964
965 foreach ($items as $delta => $item) {
966
967 // Remove empty items
968 if ($item['remove'] || (!$item['id'] && !is_object($item['file']))) {
969 if (variable_get('flickrup_remove', '')) {
970 $flickr = flickrup_flickrapi();
971 $flickr->photos_delete($item['id']);
972 }
973 unset($items[$delta]);
974 }
975
976 // Process new files
977 if (is_object($item['file'])) {
978 // Tags
979 $global_tags = explode(' ', variable_get('flickr_global_tag', ''));
980 $field_tags = explode(' ', $field['widget']['tags']);
981 $tags = array_merge($global_tags, $field_tags);
982 $result = flickrup_upload($item['file']->filepath, $item['title'], $tags);
983 $items[$delta]['id'] = $result;
984 }
985 else {
986 if ($item['title'] != $item['flickr_photo']['title']['_content']) {
987 $flickr = flickrup_flickrapi();
988 $flickr->photos_setMeta($item['id'], $item['title'], $item['flickr_photo']['description']['_content']);
989 }
990 }
991 }
992 }
993
994 function flickrup_js() {
995 $node = $_POST;
996 $field = content_fields($node['flickrup-fieldname']);
997 $fieldname = $field['field_name'];
998 $node = (object)$node;
999
1000 // Load node to get existing photos
1001 $node = node_load(array('vid' => $node->vid));
1002
1003 $items = $node->$fieldname;
1004 _flickrup_prepare($node, $field, $items);
1005
1006 $form = _flickrup_form($node, $field, $items);
1007 $form = form_builder('flickrup_js', $form);
1008 $output .= theme('status_messages') . drupal_render($form);
1009 print drupal_to_js(array('status' => TRUE, 'data' => $output));
1010 exit;
1011 }
1012
1013 function flickrup_flickrapi() {
1014 static $flickr;
1015 require_once drupal_get_path('module', 'flickrup').'/phpFlickr/phpFlickr.php';
1016
1017 if (!$flickr) {
1018 $flickr = new phpFlickr(trim(variable_get('flickr_api_key', '')), trim(variable_get('flickr_api_secret', '')));
1019 $flickr->setToken(trim(variable_get('flickr_api_token', '')));
1020 }
1021
1022 return $flickr;
1023 }

  ViewVC Help
Powered by ViewVC 1.1.2