Guest User

mvc

a guest
Aug 18th, 2008
233
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 47.06 KB | None | 0 0
  1. <?php
  2. // $Id: imagefield.module,v 1.30.2.6.2.64 2008/05/13 00:02:02 dopry Exp $
  3.  
  4. /**
  5.  * @file
  6.  * Defines an image field type.
  7.  * imagefield uses content.module to store the fid, and the drupal files
  8.  * table to store the actual file data.
  9.  *
  10.  */
  11.  
  12. /**
  13.  * Implementation of hook_menu().
  14.  */
  15. function imagefield_menu($maycache) {
  16.   $items = array();
  17.   if ($maycache) {
  18.     $items[] = array(
  19.       'path' => 'imagefield/js',
  20.       'callback' => 'imagefield_js',
  21.       //'access' => user_access(),
  22.       'access' => true,
  23.       'type' => MENU_CALLBACK
  24.     );
  25.   }
  26.   elseif ($_SESSION['imagefield']) {
  27.     // do this variable_get once....
  28.     $download_method = variable_get('file_downloads', FILE_DOWNLOADS_PUBLIC);
  29.  
  30.     // Iterate over each field stored in session imagefield looking
  31.     // for files in a preview state to add menu items for. This
  32.     // allows us to preview new uploads before a node is submitted.
  33.     foreach ($_SESSION['imagefield'] as $fieldname => $files) {
  34.       // move on to the next field if there is nothing to process in files.
  35.       if (empty($files)) continue;
  36.  
  37.       foreach ($files as $delta => $file) {
  38.         // If the file is not a preview do not display it.
  39.         if (empty($file['preview']))  continue;
  40.  
  41.         // filepath to pass into _imagefield_preview
  42.         $filepath = $file['preview'];
  43.  
  44.         // build url path for private files menu item.
  45.         if ($download_method == FILE_DOWNLOADS_PRIVATE) {
  46.           // strip out the file_directory_path. It shouldn't be a part
  47.           // of the URL with private downloads.
  48.           if (strpos($file['preview'], file_directory_path()) !== false) {
  49.             $file['preview'] = trim(substr($file['preview'], strlen(file_directory_path())), '\\/');
  50.           }
  51.           $file['preview'] = 'system/files/'. $file['preview'];
  52.         }
  53.  
  54.         $items[] = array(
  55.           'path' => $file['preview'],
  56.           'callback' => '_imagefield_preview',
  57.           'callback arguments' => array($filepath),
  58.           'access' => true,
  59.           'type' => MENU_CALLBACK,
  60.         );
  61.       }
  62.     }
  63.   }
  64.   return $items;
  65. }
  66.  
  67. /**
  68.  *  Transfer a file that is in a 'preview' state.
  69.  *
  70.  *  @todo  multiple support
  71.  */
  72. function _imagefield_preview($filepath) {
  73.   foreach ($_SESSION['imagefield'] as $fieldname => $files) {
  74.     foreach ($files as $delta => $file) {
  75.       if ($file['preview'] == $filepath) {
  76.         // Emulate a normal file transfer by setting cache flags that will
  77.         // prevent the image from needing to be resent on previews. Without
  78.         // setting the cache headers, transfered images still get the expire
  79.         // headers set in drupal_page_header().
  80.         $modified_time = filemtime($file['filepath']);
  81.         $last_modified = gmdate('D, d M Y H:i:s', $modified_time) .' GMT';
  82.         $etag = '"'. md5($last_modified) .'"';
  83.  
  84.         file_transfer($file['filepath'], array(
  85.           'Content-Type: '. mime_header_encode($file['filemime']),
  86.           'Content-Length: '. $file['filesize'],
  87.           'Cache-Control: max-age=1209600',
  88.           'Expires: '. gmdate('D, d M Y H:i:s', time() + 1209600) .' GMT', // Two weeks.
  89.           'Last-Modified: '. $last_modified,
  90.           'ETag: '. $etag,
  91.         ));
  92.       }
  93.     }
  94.   }
  95. }
  96.  
  97. /**
  98.  * Implementation of hook_perm().
  99.  */
  100. function imagefield_perm() {
  101.   return array('view imagefield uploads');
  102. }
  103.  
  104. /**
  105.  * Implementation of hook_field_info().
  106.  */
  107. function imagefield_field_info() {
  108.   return array(
  109.     'image' => array('label' => 'Image'),
  110.   );
  111. }
  112.  
  113. /**
  114.  * Implementation of hook_field_settings().
  115.  */
  116. function imagefield_field_settings($op, $field) {
  117.   switch ($op) {
  118.     case 'callbacks':
  119.       return array('view' => CONTENT_CALLBACK_CUSTOM);
  120.  
  121.     case 'form':
  122.       $form = array();
  123.       $form['default'] = array(
  124.         '#type' => 'fieldset',
  125.         '#title' => t('Default image'),
  126.       );
  127.       // Present a thumbnail of the current default image.
  128.       $form['default']['use_default_image'] = array(
  129.         '#type' => 'checkbox',
  130.         '#title' => t('Use default image'),
  131.         '#default_value' =>  $field['use_default_image'],
  132.         '#description' => t('Check here if you want to use a image as default.'),
  133.       );
  134.       if (!empty($field['default_image'])) {
  135.         $form['default']['default_image_thumbnail'] = array(
  136.           '#type' => 'markup',
  137.           '#value' => theme('imagefield_image', $field['default_image'], '', '', array('width' => '150'), false),
  138.         );
  139.       }
  140.       $form['default']['default_image_upload'] = array(
  141.         '#type'  => 'file',
  142.         '#title' => t('Upload image'),
  143.         '#description' => t('Choose a image that will be used as default.'),
  144.       );
  145.       // We set this value on 'validate' so we can get cck to add it
  146.       // as a standard field setting.
  147.       $form['default_image'] = array(
  148.         '#type' => 'value',
  149.         '#value' => $field['default_image'],
  150.       );
  151.       return $form;
  152.  
  153.     case 'validate':
  154.       // We save the upload here because we can't know the correct
  155.       // file path until we save the file.
  156.       // Check of we got an new upload.
  157.       if (!$file = file_check_upload('default_image_upload')) {
  158.         break;
  159.       }
  160.       // figure steal the file extension and construct a filename for this  
  161.       // fields default image. This is standardized for default image handling
  162.       // with private files.
  163.       $ext = array_pop(explode('.', $file->filename));
  164.       $filename = $field['field_name'] .'.'. $ext;
  165.       // verify the destination exists and is writeable...
  166.       $dst = file_create_path('imagefield_default_images/'. $filename);
  167.       if (!imagefield_check_directory(dirname($dst))) {
  168.         form_set_error('default_image', t("The default image could not be uploaded. The destination(%d) does not exist or is not writable by the webserver.", array('%d' => dirname($dst))));
  169.         break;
  170.       }  
  171.       // save the upload to it's resting place.
  172.       if (!$file = file_save_upload('default_image_upload', $dst)) {
  173.         form_set_error('default_image', t("The default image could not be uploaded. Failed saving to destination(%d).", array('%d' => $dst)));
  174.         break;
  175.       }
  176.       // remove the old one...
  177.       unlink($field['default_image']['filepath']);
  178.       // set the value of the form_item so we can store this in the settings
  179.       // from validate.
  180.       form_set_value(array('#parents' => array('default_image')), (array) $file);
  181.       break;
  182.  
  183.     case 'save':
  184.       return array('default_image', 'use_default_image');
  185.  
  186.     case 'database columns':
  187.       $columns = array(
  188.         'fid' => array('type' => 'int', 'not null' => true, 'default' => '0'),
  189.         'title' => array('type' => 'varchar', 'length' => 255, 'not null' => true, 'default' => "''", 'sortable' => true),
  190.         'alt' => array('type' => 'varchar', 'length' => 255, 'not null' => true, 'default' => "''", 'sortable' => true),
  191.         'caption' => array('type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => "''", 'sortable' => TRUE),
  192.         'credit' => array('type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => "''", 'sortable' => TRUE),
  193.         'feature' => array('type' => 'int', 'not null' => TRUE, 'default' => '0'),
  194.       );
  195.       return $columns;
  196.  
  197.     case 'filters':
  198.       return array(
  199.         'not null' => array(
  200.           'operator' => array('=' => t('Has Image')),
  201.           'list' => 'views_handler_operator_yesno',
  202.           'list-type' => 'select',
  203.           'handler' => 'imagefield_views_handler_filter_is_not_null',
  204.         ),
  205.       );
  206.   }
  207. }
  208.  
  209. /**
  210.  * Custom filter for imagefield NOT null.
  211.  */
  212. function imagefield_views_handler_filter_is_not_null($op, $filter, $filterinfo, &$query) {
  213.   if ($op == 'handler') {
  214.     $query->ensure_table($filterinfo['table']);
  215.     if ($filter['value']) {
  216.       $qs = '%s.%s > 0';
  217.       $query->add_where($qs, $filterinfo['table'], $filterinfo['field']);
  218.     }
  219.     else {
  220.       $qs = '%s.%s = 0 OR %s.%s IS null';
  221.       $query->add_where($qs, $filterinfo['table'], $filterinfo['field'], $filterinfo['table'], $filterinfo['field']);
  222.     }
  223.   }
  224.  
  225. }
  226.  
  227. function imagefield_default_item() {
  228.   return array(
  229.     'fid' => 0,
  230.     'title' => '',
  231.     'alt' => '',
  232.     'caption' => '',
  233.     'credit' => '',
  234.     'feature' => 0,
  235.   );
  236. }
  237.  
  238. /**
  239.  * Insert a file into the database.
  240.  *
  241.  * @param $node
  242.  *    Node object this file is be associated with.
  243.  * @param $file
  244.  *    File to be inserted, passed by reference since fid should be attached.
  245.  */
  246. function imagefield_file_insert($node, &$file, $field) {
  247.   $fieldname = $field['field_name'];
  248.  
  249.   // allow tokenized paths.
  250.   if (function_exists('token_replace')) {
  251.     global $user;
  252.     $widget_image_path = token_replace($field['widget']['image_path'], 'user', $user);
  253.   }
  254.   else {
  255.     $widget_image_path = $field['widget']['image_path'];
  256.   }
  257.  
  258.   $filepath = file_create_path($widget_image_path) .'/'. $file['filename'];
  259.  
  260.   if (imagefield_check_directory($widget_image_path) && $file = file_save_upload((object)$file, $filepath)) {
  261.     $file = (array)$file;
  262.     $file['fid'] = db_next_id('{files}_fid');
  263.     db_query("INSERT into {files} (fid, nid, filename, filepath, filemime, filesize)
  264.             VALUES (%d, %d, '%s','%s','%s',%d)",
  265.             $file['fid'], $node->nid, $file['filename'], $file['filepath'], $file['filemime'], $file['filesize']);
  266.     module_invoke_all('imagefield_file', 'save', $file);
  267.     return (array)$file;
  268.   }
  269.   else {
  270.     // Include file name in upload error.
  271.     form_set_error(null, t('Image upload was unsuccessful.'));
  272.     return false;
  273.   }
  274. }
  275.  
  276. /**
  277.  * Update the file record if necessary.
  278.  *
  279.  * @param $node
  280.  *    Node object this file is be associated with.
  281.  * @param $file
  282.  *   A single CCK image field item to be updated.
  283.  * @param $field
  284.  *   The field definition for this image field.
  285.  */
  286. function imagefield_file_update($node, &$file, $field) {
  287.   $file = (array)$file;
  288.   if ($file['flags']['delete'] == true) {
  289.     // don't delete files if we're creating new revisions, but still return an empty
  290.     // array...
  291.     if ($node->old_vid || _imagefield_file_delete($file, $field['field_name'])) {
  292.       return array();
  293.     }
  294.   }
  295.   if ($file['fid'] == 'upload') {
  296.     return imagefield_file_insert($node, $file, $field);
  297.   }
  298.   else {
  299.     // empty files without fid.
  300.     if ($file['fid'] == 0) {
  301.       $file = array();
  302.     }
  303.     // if fid is not numeric here we should complain.
  304.     // else we update the file table.
  305.   }
  306.   return $file;
  307. }
  308.  
  309. /**
  310.  * Implementation of hook_field().
  311.  */
  312. function imagefield_field($op, $node, $field, &$items, $teaser, $page) {
  313.   $fieldname = $field['field_name'];
  314.   switch ($op) {
  315.     // called after content.module loads default data.
  316.     case 'load':
  317.       if (!count($items)) {
  318.         return;
  319.       }
  320.       foreach ($items as $delta => $item) {
  321.         if (empty($item)) {
  322.           unset($items[$delta]);
  323.         }
  324.         elseif (!empty($item['fid'])) {
  325.           $items[$delta] = array_merge($item, _imagefield_file_load($item['fid']));
  326.         }
  327.       }
  328.       $items = array_values(array_filter($items)); // compact deltas
  329.       return array($fieldname => $items);
  330.       break;
  331.  
  332.     // called before content.module defaults.
  333.     case 'insert':
  334.       foreach ($items as $delta => $item) {
  335.         if ($item['flags']['delete']) {
  336.           unset($items[$delta]);
  337.         }
  338.         else {
  339.           $items[$delta] = imagefield_file_insert($node, $item, $field);
  340.         }
  341.       }
  342.       $items = array_values(array_filter($items)); // compact deltas
  343.       imagefield_clear_field_session($fieldname);
  344.       break;
  345.  
  346.     // called before content.module defaults.
  347.     case 'update':
  348.       foreach ($items as $delta => $item) {
  349.        
  350.         // If we're dealing with a single value field, and we just received
  351.         // a new file item, we need to mark the existing (old) one for
  352.         // deletion.  Otherwise, it will become orphaned.
  353.         if (!$field['multiple'] && !empty($items) && count($items) > 1 && $delta === 0) {
  354.           $item['flags']['hidden'] = true;
  355.           $item['flags']['delete'] = true;
  356.         }
  357.  
  358.         // Update each file item.
  359.         $items[$delta] = imagefield_file_update($node, $item, $field);
  360.  
  361.         // If the file has been deleted, unset the file entry so that it's
  362.         // actually deleted from the database, or at least set it to a
  363.         // default item if CCK won't delete it.
  364.         if (empty($items[$delta])) {
  365.           if ($field['multiple']) {
  366.             unset($items[$delta]);
  367.           }
  368.         }
  369.       }
  370.       $items = array_values(array_filter($items)); // compact deltas
  371.       imagefield_clear_field_session($fieldname);
  372.       break;
  373.  
  374.     case 'delete revision':
  375.       $db_info = content_database_info($field);
  376.       foreach ($items as $delta => $item) {
  377.         $references = db_result(db_query("SELECT count(vid) FROM {%s} WHERE nid=%d AND %s=%d and vid!=%d", $db_info['table'], $node->nid, $db_info['columns']['fid']['column'], $item['fid'], $node->vid));
  378.         if ($references || _imagefield_file_delete($item, $field['field_name'])) {
  379.           $items[$delta] = array();
  380.         }
  381.       }
  382.       $items = array_values($items); // compact deltas
  383.       break;
  384.  
  385.    
  386.     case 'delete':
  387.       foreach ($items as $delta => $item) {
  388.         _imagefield_file_delete($item, $field['field_name']);
  389.       }
  390.       break;
  391.  
  392.     case 'view':
  393.       $context = $teaser ? 'teaser' : 'full';
  394.       $formatter = isset($field['display_settings'][$context]['format']) ? $field['display_settings'][$context]['format'] : 'default';
  395.       if ($field['use_default_image'] && empty($items) ) {
  396.         $items[0] = $field['default_image'];
  397.       }
  398.       foreach ($items as $delta => $item) {
  399.         $items[$delta]['view'] = content_format($field, $item, $formatter, $node);
  400.       }
  401.       return theme('field', $node, $field, $items, $teaser, $page);
  402.   }
  403. }
  404.  
  405. /**
  406.  * Implementation of hook_widget_info().
  407.  */
  408. function imagefield_widget_info() {
  409.   return array(
  410.     'image' => array(
  411.       'label' => 'Image',
  412.       'field types' => array('image'),
  413.     ),
  414.   );
  415. }
  416.  
  417. /**
  418.  * Implementation of hook_widget_settings().
  419.  */
  420. function imagefield_widget_settings($op, $widget) {
  421.   switch ($op) {
  422.     case 'callbacks':
  423.       return array('default value' => CONTENT_CALLBACK_CUSTOM);
  424.  
  425.     case 'form':
  426.       $form = array();
  427.       $form['max_resolution'] = array(
  428.         '#type' => 'textfield',
  429.         '#title' => t('Maximum resolution for Images'),
  430.         '#default_value' => $widget['max_resolution'] ? $widget['max_resolution'] : 0,
  431.         '#size' => 15,
  432.         '#maxlength' => 10,
  433.         '#description' =>
  434.         t('The maximum allowed image size expressed as WIDTHxHEIGHT (e.g. 640x480). Set to 0 for no restriction. If a larger image is uploaded, it will be resized to reflect the given width and height.'),
  435.       );
  436.       $form['max_filesize'] = array(
  437.         '#type' => 'textfield',
  438.         '#title' => t('Maximum filesize for Images'),
  439.         '#default_value' => $widget['max_filesize'] ? $widget['max_filesize'] : 0,
  440.         '#size' => 6,
  441.         '#description' => t('The maximum allowed image file size expressed in kilobytes. Set to 0 for no restriction.')
  442.       );
  443.       $form['max_number_images'] = array(
  444.         '#type' => 'textfield',
  445.         '#title' => t('Maximum number of images'),
  446.         '#default_value' => $widget['max_number_images'] ? $widget['max_number_images'] : 0,
  447.         '#size' => 4,
  448.         '#description' => t('The maximum number of images allowed. Set to 0 for no restriction. This only applies if multiple values are enabled.')
  449.       );
  450.       $form['image_path'] = array(
  451.         '#type' => 'textfield',
  452.         '#title' => t('Image path'),
  453.         '#default_value' => $widget['image_path'] ? $widget['image_path'] : '',
  454.         '#description' => t('Optional subdirectory within the "%dir" directory where images will be stored. Do not include trailing slash.', array('%dir' => variable_get('file_directory_path', 'files'))),
  455.       );
  456.       if (function_exists('token_replace')) {
  457.         $form['image_path']['#description'] .= ' '. t('You can use the following tokens in the image path.');
  458.         $form['image_path']['#suffix'] = theme('token_help', 'user');
  459.       }
  460.       $form['file_extensions'] = array(
  461.         '#type' => 'textfield',
  462.         '#title' => t('Permitted upload file extensions.'),
  463.         '#default_value' => $widget['file_extensions'] ? $widget['file_extensions'] : 'jpg jpeg png gif',
  464.         '#size' => 64,
  465.         '#maxlength' => 64,
  466.         '#description' => t('Extensions a user can upload to this field. Seperate extensions with a space and do not include the leading dot.')
  467.       );
  468.  
  469.       $form['custom_alt'] = array(
  470.         '#type' => 'checkbox',
  471.         '#title' => t('Enable custom alternate text'),
  472.         '#default_value' =>  $widget['custom_alt'] ? $widget['custom_alt'] : 0,
  473.         '#description' => t('Enable custom alternate text for images. Filename will be used if not checked.'),
  474.       );
  475.       $form['custom_title'] = array(
  476.         '#type' => 'checkbox',
  477.         '#title' => t('Enable custom title text'),
  478.         '#default_value' =>  $widget['custom_title'] ? $widget['custom_title'] : 0,
  479.         '#description' => t('Enable custom title text for images. Filename will be used if not checked.'),
  480.       );
  481.       $form['custom_caption'] = array(
  482.         '#type' => 'checkbox',
  483.         '#title' => t('Enable custom caption text'),
  484.         '#default_value' =>  $widget['custom_caption'] ? $widget['custom_caption'] : 0,
  485.         '#description' => t('Enable custom caption text for images. Will be left blank if not checked.'),
  486.       );
  487.       $form['custom_credit'] = array(
  488.         '#type' => 'checkbox',
  489.         '#title' => t('Enable custom credit text'),
  490.         '#default_value' =>  $widget['custom_credit'] ? $widget['custom_credit'] : 0,
  491.         '#description' => t('Enable custom credit text for images. Will be left blank if not checked.'),
  492.       );
  493.       $form['custom_feature'] = array(
  494.         '#type' => 'checkbox',
  495.         '#title' => t('Enable featured images'),
  496.         '#default_value' =>  $widget['custom_feature'] ? $widget['custom_feature'] : 0,
  497.         '#description' => t('Enable the selection of images that should be featured.'),
  498.       );
  499.       return $form;
  500.  
  501.     case 'validate':
  502.       // strip slashes from the beginning and end of $widget['image_path']
  503.       $widget['image_path'] = trim($widget['image_path'], '\\/');
  504.       form_set_value(array('#parents' => array('image_path')),  $widget['image_path']);
  505.       break;
  506.  
  507.     case 'save':
  508.       return array('max_resolution', 'max_filesize', 'max_number_images', 'image_path', 'file_extensions', 'custom_alt', 'custom_title', 'custom_caption', 'custom_credit', 'custom_feature');
  509.   }
  510. }
  511.  
  512. /**
  513.  * Implementation of hook_form_alter(). Set the appropriate
  514.  * attibutes to allow file uploads on the field settings form.
  515.  */
  516. function imagefield_form_alter($form_id, &$form) {
  517.   if ($form_id == '_content_admin_field') {
  518.     $form['#attributes'] = array('enctype' => 'multipart/form-data');
  519.   }
  520. }
  521.  
  522. /**
  523.  * Create the image directory relative to the 'files' dir recursively for every
  524.  * directory in the path.
  525.  *
  526.  * @param $directory
  527.  *   The directory path under files to check, such as 'photo/path/here'
  528.  * @param $form_element
  529.  *   A form element to throw an error on if the directory is not writable
  530.  */
  531. function imagefield_check_directory($directory, $form_element = array()) {
  532.   foreach (explode('/', $directory) as $dir) {
  533.     $dirs[] = $dir;
  534.     $path = file_create_path(implode($dirs, '/'));
  535.     if (!file_check_directory($path, FILE_CREATE_DIRECTORY, $form_element['#parents'][0])) {
  536.       watchdog('imagefield', t('Imagefield failed to create directory(%d) at (%p).', array('%d' => $directory, '%p' => $path)), WATCHDOG_ERROR);
  537.       return false;
  538.     }
  539.   }
  540.   return true;
  541. }
  542.  
  543. function _imagefield_scale_image($file, $resolution = 0) {
  544.   $info = image_get_info($file['filepath']);
  545.   if ($info) {
  546.     list($width, $height) = explode('x', $resolution);
  547.     if ($width && $height) {
  548.       $result = image_scale($file['filepath'], $file['filepath'], $width, $height);
  549.       if ($result) {
  550.         $file['filesize'] = filesize($file['filepath']);
  551.         drupal_set_message(t('The image %filename was resized to fit within the maximum allowed resolution of %resolution pixels', array('%resolution' => $resolution, '%filename' => $file['filename'])));
  552.       }
  553.     }
  554.   }
  555.   return $file;
  556. }
  557.  
  558. function imagefield_clear_session() {
  559.   if (is_array($_SESSION['imagefield']) && count($_SESSION['imagefield'])) {
  560.     foreach (array_keys($_SESSION['imagefield']) as $fieldname) {
  561.       imagefield_clear_field_session($fieldname);
  562.     }
  563.     unset($_SESSION['imagefield']);
  564.   }
  565. }
  566.  
  567. function imagefield_clear_field_session($fieldname) {
  568.   if (is_array($_SESSION['imagefield'][$fieldname]) && count($_SESSION['imagefield'][$fieldname])) {
  569.     foreach ($_SESSION['imagefield'][$fieldname] as $delta => $file) {
  570.       if (is_file($file['filepath'])) {
  571.         file_delete($file['filepath']);
  572.       }
  573.     }
  574.     unset($_SESSION['imagefield'][$fieldname]);
  575.   }
  576. }
  577.  
  578. function _imagefield_file_delete($file, $fieldname) {
  579.   if (is_numeric($file['fid'])) {
  580.     db_query('DELETE FROM {files} WHERE fid = %d', $file['fid']);
  581.   }
  582.   else {
  583.     unset($_SESSION['imagefield'][$fieldname][$file['sessionid']]);
  584.   }
  585.   module_invoke_all('imagefield_file', 'delete', $file);
  586.   return file_delete($file['filepath']);
  587. }
  588.  
  589. /**
  590.  * Implementation of hook_widget().
  591.  */
  592. function imagefield_widget($op, &$node, $field, &$items) {
  593.   switch ($op) {
  594.     case 'default value':
  595.       return array();
  596.  
  597.     case 'prepare form values':
  598.       _imagefield_widget_prepare_form_values($node, $field, $items);
  599.       return;
  600.  
  601.     case 'form':
  602.       return _imagefield_widget_form($node, $field, $items);
  603.  
  604.     case 'validate':
  605.       _imagefield_widget_validate($node, $field, $items);
  606.       return;
  607.   }
  608. }
  609.  
  610. function _imagefield_widget_prepare_form_values(&$node, $field, &$items) {
  611.   $fieldname = $field['field_name'];
  612.   // clean up the session if we weren't posted.
  613.   if (!count($_POST)) {
  614.     imagefield_clear_session();
  615.   }
  616.  
  617.   // Attach new files
  618.   if ($file = file_check_upload($fieldname .'_upload')) {
  619.     $file = (array)$file;
  620.  
  621.     // Validation must happen immediately after the image is uploaded so we
  622.     // can discard the file if it turns out not to be a valid mime type
  623.     $valid_image = _imagefield_widget_upload_validate($node, $field, $items, $file);
  624.     //$valid_image = true;
  625.  
  626.     if ($valid_image) {
  627.       $file = _imagefield_scale_image($file, $field['widget']['max_resolution']);
  628.  
  629.       // Allow tokenized paths if available
  630.       if (function_exists('token_replace')) {
  631.         global $user;
  632.         $widget_image_path = token_replace($field['widget']['image_path'], 'user', $user);
  633.       }
  634.       else {
  635.         $widget_image_path = $field['widget']['image_path'];
  636.       }
  637.       imagefield_check_directory($widget_image_path);
  638.       $filepath = file_create_filename($file['filename'], file_create_path($widget_image_path));
  639.  
  640.       $file['fid'] = 'upload';
  641.       $file['preview'] = $filepath;
  642.  
  643.       // If a single field, mark any other images for deletion and delete files in session
  644.       if (!$field['multiple']) {
  645.         if (is_array($items)) {
  646.           foreach ($items as $delta => $session_file) {
  647.             $items[$delta]['flags']['hidden'] = true;
  648.             $items[$delta]['flags']['delete'] = true;
  649.           }
  650.         }
  651.         imagefield_clear_field_session($fieldname);
  652.       }
  653.       // Add the file to the session
  654.       $file_id = count($items) + count($_SESSION['imagefield'][$fieldname]);
  655.       $file['sessionid'] = $file_id;
  656.       $_SESSION['imagefield'][$fieldname][$file_id] = $file;
  657.     }
  658.     else {
  659.       // Delete the invalid file
  660.       file_delete($file['filepath']);
  661.  
  662.       // If a single field and a valid file is in the session, mark existing image for deletion
  663.       if (!$field['multiple']) {
  664.         if (!empty($_SESSION['imagefield'][$fieldname]) && !empty($items)) {
  665.           foreach ($items as $delta => $session_file) {
  666.             $items[$delta]['flags']['hidden'] = true;
  667.             $items[$delta]['flags']['delete'] = true;
  668.           }
  669.         }
  670.       }
  671.     }
  672.   }
  673.  
  674.   // Load files from preview state. before committing actions.
  675.   if (is_array($_SESSION['imagefield'][$fieldname]) && count($_SESSION['imagefield'][$fieldname])) {
  676.     foreach ($_SESSION['imagefield'][$fieldname] as $delta => $file) {
  677.       $items[] = $file;
  678.     }
  679.   }
  680. }
  681.  
  682. function _imagefield_widget_form($node, $field, &$items) {
  683.   drupal_add_js('misc/progress.js');
  684.   drupal_add_js('misc/upload.js');
  685.   drupal_add_js(drupal_get_path('module', 'imagefield') .'/imagefield.js');
  686.   drupal_add_css(drupal_get_path('module', 'imagefield') .'/imagefield.css');
  687.  
  688.   $fieldname = $field['field_name'];
  689.  
  690.   $form = array();
  691.  
  692.   $form[$fieldname] = array(
  693.     '#type' => 'fieldset',
  694.     '#title' => t($field['widget']['label']),
  695.     '#weight' => $field['widget']['weight'],
  696.     '#description' => t('Images are not saved until the form is submitted.'),
  697.     '#collapsible' => true,
  698.     '#collapsed' => false,
  699.     '#tree' => true,
  700.     '#prefix' => '<div id="'. form_clean_id($fieldname .'-attach-wrapper') .'">',
  701.     '#suffix' => '</div>',
  702.   );
  703.  
  704.   $form[$fieldname]['new'] = array(
  705.     '#tree' => false,
  706.     '#prefix' => '<div id="'. form_clean_id($fieldname .'-attach-hide') .'">',
  707.     '#suffix' => '</div>',
  708.     '#weight' => 100,
  709.   );
  710.  
  711.   $max_images = $field['widget']['max_number_images'];
  712.   if ($field['multiple'] && $max_images && $max_images <= count($items)) {
  713.     $form[$fieldname]['#prefix'] = '<div>';
  714.     $form[$fieldname]['new']['#prefix'] = '<div>';
  715.     $form[$fieldname]['new']['#value'] = format_plural($max_images, 'You can only attach one image to this field. Delete the image if you wish to be able to upload a different one.', 'You can only attach @count images to this field. Delete an image if you wish to be able to upload different images.');
  716.   }
  717.   else {
  718.  
  719.     // multiupload: add an add new field button.
  720.     // onchange ajax upload each file input after validation.
  721.     // update date 'file_inputs' with qty of file inputs.
  722.     // name file inputs $fieldname .'_upload_'. number of file input.
  723.     // inprepare form_values hook iterate over each input.
  724.     // can we display files sizes to predict the total size of an upload.
  725.  
  726.     $extensions_description = empty($field['widget']['file_extensions'])
  727.     ? ''
  728.     : t('<br />Allowed extensions: %ext', array('%ext' => $field['widget']['file_extensions']));
  729.  
  730.     // Seperate from tree becase of that silly things won't be
  731.     // displayed if they are a child of '#type' = form issue
  732.     $form[$fieldname]['new'][$fieldname .'_upload'] = array(
  733.       '#type'  => 'file',
  734.       '#title' => t('Upload a new image'),
  735.       '#description' => $field['widget']['description'] . $extensions_description,
  736.       '#tree' => false,
  737.       '#weight' => 9,
  738.       '#attributes' => array('class' => 'imagefield imagefield-'. $fieldname, 'accept' => str_replace(' ', '|', trim($field['widget']['file_extensions']))),
  739.     );
  740.  
  741.     $form[$fieldname]['new']['upload'] = array(
  742.       '#type' => 'button',
  743.       '#value' => t('Upload'),
  744.       '#name' => 'cck_imagefield_'. $fieldname .'_op',
  745.       '#id' => form_clean_id($fieldname .'-attach-button'),
  746.       '#tree' => false,
  747.       '#weight' => 10,
  748.     );
  749.     // The class triggers the js upload behaviour.
  750.     $form[$fieldname .'-attach-url'] = array('#type' => 'hidden', '#value' => url('imagefield/js', null, null, true), '#attributes' => array('class' => 'upload'));
  751.   }
  752.  
  753.   // @todo split following if block into its own function.
  754.   // Store the file data object to be carried on.
  755.   if (!empty($items)) {
  756.     foreach ($items as $delta => $file) {
  757.       if ($file['filepath'] && !$file['flags']['hidden']) {
  758.         $form[$fieldname][$delta] = array(
  759.           '#theme' => 'imagefield_edit_image_row',
  760.         );
  761.  
  762.         $form[$fieldname][$delta]['flags']['delete'] = array(
  763.           '#type' => 'checkbox',
  764.           '#title' => t('Delete'),
  765.           '#default_value' => isset($file['flags']['delete']) ? $file['flags']['delete'] : 0,
  766.         );
  767.  
  768.         if (function_exists('token_replace')) {
  769.           global $user;
  770.           $filename = $file['fid'] == 'upload' ? file_create_filename($file['filename'], file_create_path(token_replace($field['widget']['image_path'], 'user', $user))) : $file['filepath'];
  771.         }
  772.         else {
  773.           $filename = $file['fid'] == 'upload' ? file_create_filename($file['filename'], file_create_path($field['widget']['image_path'])) : $file['filepath'];
  774.         }
  775.  
  776.         $form[$fieldname][$delta]['admin_preview'] = array(
  777.           '#type' => 'markup',
  778.           '#value' => theme('imagefield_image', $file, $file['alt'], $file['title'], $file['caption'], $file['credit'], array('width' => '150'), false),
  779.         );
  780.  
  781.         $form[$fieldname][$delta]['description'] = array(
  782.           '#type' => 'markup',
  783.           '#value' => '<strong>'. t('Filename: ') .'</strong>'. $file['filename'],
  784.         );
  785.  
  786.         $form[$fieldname][$delta]['alt'] = array(
  787.           '#type' => 'hidden',
  788.           '#value' => $file['filename'],
  789.         );
  790.         // overwrite with an input field if custom_alt is flagged;
  791.         if ($field['widget']['custom_alt']) {
  792.           $form[$fieldname][$delta]['alt'] = array(
  793.             '#type' => 'textfield',
  794.             '#title' =>  t('Alternate text'),
  795.             '#default_value' => $file['alt'],
  796.             '#description' => t('Alternate text to be displayed if the image cannot be displayed.'),
  797.             '#maxlength' => 255,
  798.             '#size' => 10,
  799.           );
  800.         }
  801.  
  802.         $form[$fieldname][$delta]['title'] = array(
  803.           '#type' => 'hidden',
  804.           '#value' => $file['filename'],
  805.         );
  806.         // overwrite with an input field if custom_title is flagged;
  807.         if ($field['widget']['custom_title']) {
  808.           $form[$fieldname][$delta]['title'] = array(
  809.             '#type' => 'textfield',
  810.             '#title' =>  t('Title'),
  811.             '#default_value' =>  $file['title'],
  812.             '#description' => t('Text to be displayed on mouse overs.'),
  813.             '#maxlength' => 255,
  814.             '#size' => 10,
  815.           );
  816.         }
  817.  
  818.         $form[$fieldname][$delta]['caption'] = array(
  819.           '#type' => 'hidden',
  820.           '#value' => '',
  821.         );
  822.         // overwrite with an input field if custom_caption is flagged;
  823.         if ($field['widget']['custom_caption']) {
  824.           $form[$fieldname][$delta]['caption'] = array(
  825.             '#type' => 'textfield',
  826.             '#title' =>  t('Caption'),
  827.             '#default_value' =>  $file['caption'],
  828.             '#description' => t('Caption text.'),
  829.             '#maxlength' => 255,
  830.             '#size' => 10,
  831.           );
  832.         }
  833.  
  834.         $form[$fieldname][$delta]['credit'] = array(
  835.           '#type' => 'hidden',
  836.           '#value' => '',
  837.         );
  838.         // overwrite with an input field if custom_credit is flagged;
  839.         if ($field['widget']['custom_credit']) {
  840.           $form[$fieldname][$delta]['credit'] = array(
  841.             '#type' => 'textfield',
  842.             '#title' =>  t('Credit'),
  843.             '#default_value' =>  $file['credit'],
  844.             '#description' => t('Photo Credit.'),
  845.             '#maxlength' => 255,
  846.             '#size' => 10,
  847.           );
  848.         }
  849.  
  850.         $form[$fieldname][$delta]['feature'] = array(
  851.           '#type' => 'hidden',
  852.           '#value' => '0',
  853.         );
  854.         // overwrite with an input field if custom_feature is flagged;
  855.         if ($field['widget']['custom_feature']) {
  856.           $form[$fieldname][$delta]['feature'] = array(
  857.             '#type' => 'select',
  858.             '#options' => array(0 => t('No'), 1 => t('Yes')),
  859.             '#title' =>  t('Featured'),
  860.             '#default_value' =>  $file['feature'],
  861.             '#description' => t('Feature this image.'),
  862.           );
  863.         }
  864.  
  865.         // Special handling for single value fields
  866.         if (!$field['multiple']) {
  867.           $form[$fieldname][$delta]['replace'] = array(
  868.             '#type' => 'markup',
  869.             '#value' => t('If a new image is chosen, the current image will be replaced upon submitting the form.'),
  870.           );
  871.         }
  872.       }
  873.       elseif ($file['filepath'] && $file['flags']['hidden']) {
  874.         // Render all the form values of this item if it is hidden.
  875.         $form[$fieldname][$delta]['flags']['hidden'] = array('#type' => 'value', '#value' => $file['flags']['hidden']);
  876.         $form[$fieldname][$delta]['flags']['delete'] = array('#type' => 'value', '#value' => $file['flags']['delete']);
  877.         $form[$fieldname][$delta]['title'] = array('#type' => 'value', '#value' => $file['title']);
  878.         $form[$fieldname][$delta]['alt'] = array('#type' => 'value', '#value' => $file['alt']);
  879.         $form[$fieldname][$delta]['caption'] = array('#type' => 'value', '#value' => $file['caption']);
  880.         $form[$fieldname][$delta]['credit'] = array('#type' => 'value', '#value' => $file['credit']);
  881.         $form[$fieldname][$delta]['feature'] = array('#type' => 'value', '#value' => $file['feature']);
  882.       }
  883.       if (isset($file['sessionid'])) {
  884.         $form[$fieldname][$delta]['sessionid'] = array('#type' => 'value',  '#value' => $file['sessionid']);
  885.       }
  886.       $form[$fieldname][$delta]['filename'] = array('#type' => 'value',  '#value' => $file['filename']);
  887.       $form[$fieldname][$delta]['filepath'] = array('#type' => 'value',  '#value' => $file['filepath']);
  888.       $form[$fieldname][$delta]['preview'] = array('#type' => 'value',  '#value' => $file['preview']);
  889.       $form[$fieldname][$delta]['filemime'] = array('#type' => 'value',  '#value' => $file['filemime']);
  890.       $form[$fieldname][$delta]['filesize'] = array('#type' => 'value',  '#value' => $file['filesize']);
  891.       $form[$fieldname][$delta]['fid'] = array('#type' => 'value',  '#value' => $file['fid']);
  892.     }
  893.   }
  894.  
  895.   // Some useful info for our js callback.
  896.   $form['vid'] = array(
  897.     '#type' => 'hidden',
  898.     '#value' => $node->vid,
  899.     '#tree' => false,
  900.   );
  901.   $form['nid'] = array(
  902.     '#type' => 'hidden',
  903.     '#value' => $node->nid,
  904.     '#tree' => false,
  905.   );
  906.   $form['type'] = array(
  907.     '#type' => 'hidden',
  908.     '#value' => $node->type,
  909.     '#tree' => false,
  910.   );
  911.  
  912.   return $form;
  913. }
  914.  
  915. /**
  916.  * Validate the widget.
  917.  */
  918. function _imagefield_widget_validate($node, $field, $items) {
  919.  
  920.   if ($field['required']) {
  921.     // Sum all the items marked for deletion, so we can make sure the end user
  922.     // isn't deleting all of the images.
  923.     $deleted = 0;
  924.     foreach ($items as $item) {
  925.       if ($item['flags']['delete']) {
  926.         ++$deleted;
  927.       }
  928.     }
  929.  
  930.     if (!count($items)) {
  931.       form_set_error($field['field_name'], t('@field is required. Please upload an image.', array('@field' => $field['widget']['label'])));
  932.     }
  933.     else if (count($items) == $deleted ) {
  934.       form_set_error($field['field_name'],  t('@field is required. Please uncheck at least one delete checkbox or upload another image.', array('@field' => $field['widget']['label'])));
  935.     }
  936.   }
  937. }
  938.  
  939. function _imagefield_widget_upload_validate($node, $field, $items, $file) {
  940.   // initialize our validation state, innocent until proven guilty.
  941.   $valid = true;
  942.  
  943.   // Do we even need to test file extensions?
  944.   if (!empty($field['widget']['file_extensions'])) {
  945.     // Pop out the extensions and turn file_extensions into an array.
  946.     $ext = strtolower(array_pop(explode('.', $file['filename'])));
  947.     $allowed_extensions = array_unique(explode(' ', strtolower(trim($field['widget']['file_extensions']))));
  948.     // Is it the file extension in the allowed_extensions array?
  949.     if (!in_array($ext, $allowed_extensions)) {
  950.       // Sorry no..
  951.       form_set_error($field['field_name'], t('Files with the extension %ext are not allowed. Please upload a file with an extension from the following list: %allowed_extensions', array('%ext' => $ext, '%allowed_extensions' => $field['widget']['file_extensions'])));
  952.       $valid = false;
  953.     }
  954.   }
  955.  
  956.   // If max filesize is set.
  957.   if (!empty($field['widget']['max_filesize'])) {
  958.     if ($file['filesize'] > ($field['widget']['max_filesize'] * 1024)) {
  959.       form_set_error($field['field_name'], t('The file you uploaded has a filesize greater than the maximum allowed filesize of %sizekb.', array('%size' => $field['widget']['max_filesize'])));
  960.       $valid = false;
  961.     }
  962.   }
  963.  
  964.   // Is the mime type a match for image.
  965.   if (strpos($file['filemime'], 'image/') !== 0) {
  966.     // sorry no it isn't. do not pass go, do not collect $200.
  967.     form_set_error($field['field_name'], t('Mime Type mismatch. Only image files may be upload. You uploaded a file with mime type: %mime', array('%mime' => $file['filemime'])));
  968.     $valid = false;
  969.   }
  970.  
  971.   // If max number of images is set
  972.   if ($field['multiple'] && !empty($field['widget']['max_number_images'])) {
  973.     $count = count($items) + count($_SESSION['imagefield'][$field['field_name']]);
  974.     if ($count >= $field['widget']['max_number_images']) {
  975.       form_set_error($field['field_name'], t('You are only allowed to upload up to %maximages images.', array('%maximages' => $field['widget']['max_number_images'])));
  976.       $valid = false;
  977.     }
  978.   }
  979.  
  980.   return $valid;
  981. }
  982.  
  983.  
  984. /**
  985.  * Implementation of hook_field_formatter_info().
  986.  
  987.  */
  988. function imagefield_field_formatter_info() {
  989.   $formatters = array(
  990.     'imagefield_default' => array(
  991.       'label' => 'Default',
  992.       'field types' => array('image'),
  993.     ),
  994.     'imagefield_nodelink' => array(
  995.       'label' => t('link to node'),
  996.       'field types' => array('image'),
  997.     ),
  998.     'imagefield_imagelink' => array(
  999.       'label' => t('link to image'),
  1000.       'field types' => array('image'),
  1001.     ),
  1002.     'imagefield_path' => array(
  1003.        'label' => t('path to image'),
  1004.        'field types' => array('image'),
  1005.     ),  
  1006.     'imagefield_url' => array(
  1007.        'label' => t('url to image'),
  1008.        'field types' => array('image'),
  1009.     ),  
  1010.   );
  1011.   return $formatters;
  1012. }
  1013.  
  1014. /**
  1015.  * Implementation of hook_field_formatter().
  1016.  */
  1017. function imagefield_field_formatter($field, $item, $formatter, $node = null) {
  1018.   if (empty($item['fid']) && $field['use_default_image']) {
  1019.     $item = $field['default_image'];
  1020.   }
  1021.   // If there is no image on the database, use default.
  1022.   if (empty($item['filepath'])) {
  1023.     $item = array_merge($item, _imagefield_file_load($item['fid']));
  1024.   }
  1025.  
  1026.   $parts = explode('_', $formatter);
  1027.   $style = array_pop($parts);
  1028.   $fieldtype = implode('_', $parts);
  1029.  
  1030.   $class = 'imagefield imagefield-'. $field['field_name'];
  1031.  
  1032.   switch ($style) {
  1033.     case 'imagelink':
  1034.       $original_image_url = file_create_url($item['filepath']);
  1035.       $imagetag =  theme('imagefield_image', $item, $item['alt'], $item['title'], array('class' => $class));
  1036.       $class .= ' imagefield-imagelink';
  1037.       return l($imagetag, $original_image_url, array('class' => $class), null, null, false, true);
  1038.  
  1039.     case 'nodelink':
  1040.       $imagetag =  theme('imagefield_image', $item, $item['alt'], $item['title'], array('class' => $class));
  1041.       $class .= ' imagefield-nodelink';
  1042.       $id = 'imagefield-nodelink-'. $node->nid;
  1043.       return l($imagetag, 'node/'. $node->nid, array('class' => $class, 'id' => $id), null, null, false, true);
  1044.    
  1045.     case 'url':
  1046.       return theme('imagefield_formatter_url', file_create_url($item['filepath']), array('class' => $class));
  1047.  
  1048.     case 'path':
  1049.       return theme('imagefield_formatter_path', file_create_path($item['filepath']), array('class' => $class));
  1050.  
  1051.     default:
  1052.       return theme('imagefield_image', $item, $item['alt'], $item['title'], $item['caption'], $item['credit'], array('class' => $class));
  1053.   }
  1054. }
  1055.  
  1056. function _imagefield_file_load($fid = null) {
  1057.   // Don't bother if we weren't passed and fid.
  1058.   if (!empty($fid) && is_numeric($fid)) {
  1059.     $result = db_query('SELECT * FROM {files} WHERE fid = %d', $fid);
  1060.     $file = db_fetch_array($result);
  1061.     if ($file) {
  1062.       return $file;
  1063.     }
  1064.   }
  1065.   // return an empty array if nothing was found.
  1066.   return array();
  1067. }
  1068.  
  1069. function theme_imagefield_formatter_url($url, $attributes = array()) {
  1070.   $attributes['class'] .= ' imagefield-formatter-path';
  1071.   return '<span '. drupal_attributes($attributes) .'>'. $url .'</span>';
  1072. }
  1073.  
  1074. function theme_imagefield_formatter_path($path, $attributes = array()) {
  1075.   $attributes['class'] .= ' imagefield-formatter-url';
  1076.   return '<span '. drupal_attributes($attributes) .'>'. $path .'</span>';
  1077. }
  1078.  
  1079.  
  1080. function theme_imagefield_view_image($file, $alt = '', $title = '', $caption = '', $credit = '', $attributes = null, $getsize = true) {
  1081.   return theme('imagefield_image', $file, $alt, $title, $caption, $credit, $attributes , $getsize);
  1082. }
  1083.  
  1084. function theme_imagefield_edit_image_row($element) {
  1085.   $output = '<div class="imagefield-edit-preview">'. drupal_render($element['admin_preview']) .'</div>';
  1086.   $output .= '<div class="imagefield-edit-image-detail">';
  1087.   $output .= '<div class="imagefield-edit-image-flags">'. drupal_render($element['flags']) .'</div>';
  1088.   $output .= '<div class="imagefield-edit-image-description">'. drupal_render($element['description']) .'</div>';
  1089.   $output .= drupal_render($element['alt']);
  1090.   $output .= drupal_render($element['title']);
  1091.   $output .= drupal_render($element['caption']);
  1092.   $output .= drupal_render($element['credit']);
  1093.   $output .= drupal_render($element['feature']);
  1094.   $output .= '</div>';
  1095.   $output = '<div class="imagefield-edit-image-row clear-block">'. $output .'</div>';
  1096.   if (isset($element['replace'])) {
  1097.     $output .= '<div class="imagefield-edit-image-replace">'. drupal_render($element['replace']) .'</div>';
  1098.   }
  1099.   return $output;
  1100. }
  1101.  
  1102. function theme_imagefield_image($file, $alt = '', $title = '', $caption = '', $credit = '', $attributes = null, $getsize = true) {
  1103.   $file = (array)$file;
  1104.   if (!is_file($file['filepath'])) {
  1105.     return;
  1106.   }
  1107.   if (!$getsize || (list($width, $height, $type, $image_attributes) = @getimagesize($file['filepath']))) {
  1108.     $attributes = drupal_attributes($attributes);
  1109.     $path = ($file['fid'] == 'upload') ? $file['preview'] : $file['filepath'];
  1110.     $alt = empty($alt) ? $file['alt'] : $alt;
  1111.     $title = empty($title) ? $file['title'] : $title;
  1112.     $caption = empty($caption) ? $file['caption'] : $caption;
  1113.     $credit = empty($credit) ? $file['credit'] : $credit;
  1114.     $url = file_create_url($path);
  1115.     return theme('imagefield_credit', $credit) .'<img src="'. check_url($url) .'" alt="'.
  1116.         check_plain($alt) .'" title="'. check_plain($title) .'" '. $image_attributes . $attributes .' />' . theme('imagefield_caption', $caption);
  1117.   }
  1118. }
  1119.  
  1120. function theme_imagefield_caption($caption){
  1121.   if(!empty($caption)){
  1122.     return '<div class="imagefield-caption">'. check_markup($caption) .'</div>';
  1123.   }
  1124.   return '';
  1125. }
  1126.  
  1127. function theme_imagefield_credit($credit){
  1128.   if(!empty($credit)){
  1129.     return '<div class="imagefield-credit">'. check_markup($credit) .'</div>';
  1130.   }
  1131.   return '';
  1132. }
  1133.  
  1134. /**
  1135.  * Formats an array of images.
  1136.  *
  1137.  * @param images
  1138.  *    array of individually themed images
  1139.  * @return
  1140.  *    html string
  1141.  */
  1142. function theme_imagefield_multiple($images) {
  1143.   return implode("\n", $images);
  1144. }
  1145.  
  1146. /**
  1147.  * Implementation of hook_file_download().
  1148.  * Replicated from upload.module.
  1149.  *
  1150.  * Conditionally included since we're just replicating the
  1151.  * work of upload.module for now.
  1152.  */
  1153.  
  1154. if (!function_exists('upload_file_download')) {
  1155.   function imagefield_file_download($file) {
  1156.     // if this isn't a default image look it up from the db...
  1157.     if (strpos($file, 'imagefield_default_images') !== false) {
  1158.       $fieldname = array_shift(explode('.', basename($file)));
  1159.       $field = content_fields($fieldname);
  1160.       $file = $field['default_image'];
  1161.     }
  1162.     else {
  1163.       $file = file_create_path($file);
  1164.  
  1165.       $result = db_query("SELECT f.* FROM {files} f WHERE filepath = '%s'", $file);
  1166.       if (!$file = db_fetch_object($result)) {
  1167.         // We don't really care about this file.
  1168.         return;
  1169.       }
  1170.     }
  1171.  
  1172.     // @todo: check the node for this file to be referenced in a field
  1173.     // to determine if it is managed by imagefield. and do the access denied part here.
  1174.     if (!user_access('view imagefield uploads')) {
  1175.       // sorry you do not have the proper permissions to view
  1176.       // imagefield uploads.
  1177.       return -1;
  1178.     }
  1179.  
  1180.     // @hack: default images dont' have nids....
  1181.     // I'm not going to bother checking perms for default images...
  1182.     // it's a bug, but we'll resolve it later.
  1183.     if (!empty($file->nid)) {
  1184.       $node = node_load($file->nid);
  1185.       if (!node_access('view', $node)) {
  1186.         // You don't have permission to view the node
  1187.         // this file is attached to.
  1188.         return -1;
  1189.       }
  1190.     }
  1191.  
  1192.     // Well I guess you can see this file.
  1193.     $name = mime_header_encode($file->filename);
  1194.     $type = mime_header_encode($file->filemime);
  1195.     // Serve images and text inline for the browser to display rather than download.
  1196.     $disposition = ereg('^(text/|image/)', $file->filemime) ? 'inline' : 'attachment';
  1197.     return array(
  1198.       'Content-Type: '. $type .'; name='. $name,
  1199.       'Content-Length: '. $file->filesize,
  1200.       'Content-Disposition: '. $disposition .'; filename='. $name,
  1201.       'Cache-Control: private',
  1202.     );
  1203.   }
  1204. }
  1205.  
  1206. /**
  1207.  * Menu-callback for JavaScript-based uploads.
  1208.  */
  1209. function imagefield_js() {
  1210.   // Parse fieldname from submit button.
  1211.   $matches = array();
  1212.   foreach (array_keys($_POST) as $key) {
  1213.     if (preg_match('/cck_imagefield_(.*)_op/', $key, $matches)) {
  1214.       break;
  1215.     }
  1216.   }
  1217.   $fieldname = $matches[1];
  1218.  
  1219.   $node = (object)$_POST;
  1220.   // Load field data.
  1221.   $field = content_fields($fieldname, $node->type);
  1222.  
  1223.   // Load fid's stored by content.module
  1224.   $items = array();
  1225.   $values  = content_field('load', $node, $field, $items, false, false);
  1226.   $items = $values[$fieldname];
  1227.  
  1228.   // Load additional field data
  1229.   imagefield_field('load', $node, $field, $items, false, false);
  1230.  
  1231.   // Handle uploads and validation.
  1232.   _imagefield_widget_prepare_form_values($node, $field, $items);
  1233.   _imagefield_widget_validate($node, $field, $items);
  1234.  
  1235.   if (is_array($node->{$fieldname}) && count($node->{$fieldname}) > 0) {
  1236.     foreach ($node->{$fieldname} as $key => $image) {
  1237.       // Set the alt and title from POST
  1238.       $items[$key]['alt'] = $image['alt'];
  1239.       $items[$key]['title'] = $image['title'];
  1240.       $items[$key]['caption'] = $image['caption'];
  1241.       $items[$key]['credit'] = $image['credit'];
  1242.       $items[$key]['feature'] = $image['feature'];
  1243.       $items[$key]['flags']['delete'] = $image['flags']['delete'];
  1244.     }
  1245.   }
  1246.  
  1247.   // Get our new form baby, yeah tiger, get em!
  1248.   $form = _imagefield_widget_form($node, $field, $items);
  1249.  
  1250.   foreach (module_implements('form_alter') as $module) {
  1251.     $function = $module .'_form_alter';
  1252.     $function('imagefield_js', $form);
  1253.   }
  1254.   $form = form_builder('imagefield_js', $form);
  1255.  
  1256.   $output =  theme('status_messages') . drupal_render($form);
  1257.  
  1258.   // We send the updated file attachments form.
  1259.   echo drupal_to_js(array('status' => true, 'data' => $output));
  1260.   exit;
  1261.  
  1262. }
Advertisement
Add Comment
Please, Sign In to add comment