[ Index ]

PHP Cross Reference of Drupal 6 (gatewave)

title

Body

[close]

/sites/all/modules/upload_element/ -> upload_element.module (source)

   1  <?php
   2  // $Id: upload_element.module,v 1.1.2.6 2009/06/24 10:31:06 aland Exp $
   3  
   4  /**
   5   * @file
   6   * A module that provides two new elements to the FAPI for file handling.
   7   *
   8   * This module provides two new elements to add a layer of abstraction to the
   9   * file handling within the FAPI.
  10   *
  11   * upload_element - a generic file element
  12   * image_upload_element - a generic image element
  13   */
  14  
  15  define('UPLOAD_ELEMENT_NONE', 0);
  16  define('UPLOAD_ELEMENT_NEW', 1);
  17  define('UPLOAD_ELEMENT_DELETE', 2);
  18  define('UPLOAD_ELEMENT_REPLACE', 3);
  19  
  20  /**
  21   * Implementation of hook_help().
  22   */
  23  function upload_element_help($path, $arg) {
  24    switch ($path) {
  25      case 'admin/help#upload_element':
  26        $output = '<p>'. t('A module that provides two new FAPI elements to handle file uploads.') .'</p>';
  27        return $output;
  28    }
  29  }
  30  
  31  /**
  32   * Implementation of hook_menu().
  33   */
  34  function upload_element_menu() {
  35    $items = array();
  36    $items['upload_element'] = array(
  37      'title' => t('Upload element preview'),
  38      'file' => 'upload_element.pages.inc',
  39      'type' => MENU_CALLBACK,
  40      'access arguments' => array('access content'),
  41      'page callback' => 'image_upload_element_thumb',
  42      'page arguments' => array(),
  43    );
  44    $items['upload_element_js/%/%/%'] = array(
  45      'title' => t('AHAH Callback'),
  46      'file' => 'upload_element.pages.inc',
  47      'type' => MENU_CALLBACK,
  48      'access arguments' => array('access content'),
  49      'page callback' => 'upload_element_js',
  50      'page arguments' => array(1, 2, 3),
  51    );
  52    return $items;
  53  }
  54  
  55  /**
  56   * Implementation of hook_theme().
  57   */
  58  function upload_element_theme() {
  59    return array(
  60      'upload_element' => array(
  61        'arguments' => array('element' => NULL),
  62      ),
  63      'image_upload_element' => array(
  64        'arguments' => array('element' => NULL),
  65      ),
  66      'upload_element_preview' => array(
  67        'arguments' => array('element' => NULL),
  68      ),
  69      'upload_element_image_preview' => array(
  70        'arguments' => array('element' => NULL),
  71      ),
  72      'upload_element_file_description' => array(
  73        'arguments' => array('element' => NULL),
  74      ),
  75    );
  76  }
  77  
  78  /**
  79   * Implementation of hook_init().
  80   */
  81  function upload_element_init() {
  82    drupal_add_css(drupal_get_path('module', 'upload_element') .'/upload_element.css');
  83  }
  84  
  85  /**
  86   * Implementation of hook_elements().
  87   *
  88   * Defines two file form elements that are linked into the
  89   * native Drupal file handling system.
  90   *
  91   * The elements share four native parameters:
  92   * #file_formatter - theming function to preview the element
  93   * #file_validators - array of additional validation functions
  94   *    to perform on the uploaded file element.
  95   *
  96   * The image_upload_element integrates into imagecache to enable a preset to
  97   * be run against the image when saving this to the new location.
  98   */
  99  function upload_element_elements() {
 100    $type['upload_element'] = array(
 101      '#input' => TRUE,
 102      '#default_value' => '',
 103      '#process' => array('_upload_element_expand'),
 104      '#element_validate' => array('upload_element_element_validate'),
 105      '#file_formatter' => 'upload_element_preview',
 106      '#file_validators' => array(),
 107      '#file_validator_seperator' => '<br />',
 108    );
 109  
 110    $type['image_upload_element'] = array(
 111      '#input' => TRUE,
 112      '#default_value' => '',
 113      '#process' => array('_upload_element_expand'),
 114      '#element_validate' => array('upload_element_element_validate'),
 115      '#file_formatter' => 'upload_element_preview',
 116      '#file_validators' => array(),
 117      '#file_validator_seperator' => '<br />',
 118      '#image_formatter' => 'upload_element_image_preview',
 119      '#image_preview_size' => '100x100',
 120    );
 121    return $type;
 122  }
 123  
 124  /**
 125   * Our #process callback to expand the control.
 126   */
 127  function _upload_element_expand($element, $edit, &$form_state, $complete_form) {
 128    // We need this to parse the form cache for image preview
 129    // and ajax functions.
 130    $element['#build_id'] = $complete_form['#build_id'];
 131  
 132    // A form rebuild changes the form build id
 133    if (isset($form_state['#'.$element['#name']])) {
 134      if ($form_state['#'.$element['#name']] != $element['#build_id']) {
 135        if (isset($_SESSION['files']['upload_element'][$form_state['#'.$element['#name']]])) {
 136          $_SESSION['files']['upload_element'][$element['#build_id']] = $_SESSION['files']['upload_element'][$form_state['#'.$element['#name']]];
 137          unset($_SESSION['files']['upload_element'][$form_state['#'.$element['#name']]]);
 138          $form_state['rebuild'] = TRUE;
 139        }
 140      }
 141    }
 142    $form_state['#'.$element['#name']] = $element['#build_id'];
 143    if (!count($complete_form['#post'])) {
 144      $_SESSION['files']['upload_element'][$element['#build_id']][$element['#name'] .'_default'] = array_key_exists('#value', $element) ? $element['#value']: $element['#default_value'];
 145    }
 146  
 147    // move things around a bit
 148    $children = element_children($element);
 149    $element[$element['#name'] .'_custom_elements'] = array();
 150    foreach($children as $child) {
 151      $element[$element['#name'] .'_custom_elements'][$child] = $element[$child];
 152      unset($element[$child]);
 153    }
 154  
 155    $element[$element['#name'] .'_upload_element_file'] = array(
 156      '#type' => 'file',
 157      '#size' => $element['#size'] ? $element['#size'] : 40,
 158      '#name' => 'files['. $element['#name'] .']',
 159      '#id' => form_clean_id("edit-file-{$element['#name']}"),
 160      '#description' => theme('upload_element_file_description', $element),
 161    );
 162    $element[$element['#name'] .'_upload_element_ahah'] = array(
 163      '#type' => 'submit',
 164      '#value' => t('Update'),
 165      '#name' => $element['#name'] .'-upload-element',
 166      '#prefix' => '<div class="form-item">',
 167      '#suffix' => '</div>',
 168      '#ahah' => array(
 169        'path' => 'upload_element_js/'. $element['#build_id'] .'/'. $complete_form['form_id']['#value'] .'/'. $element['#name'],
 170        'wrapper' => $element['#id'] .'-ahah-wrapper',
 171        'method' => 'replace',
 172        'progress' => array('type' => 'bar', 'message' => t('Please wait...')),
 173        'effect' => 'none',
 174      ),
 175    );
 176    return $element;
 177  }
 178  
 179  
 180  /**
 181   * This is the core function that handles the uploading and workflow
 182   * of the submitted files.
 183   *
 184   * @param array $form The form element whose value is being populated.
 185   * @param mixed $edit The incoming POST data to populate the form element.
 186   * If this is FALSE, the element's default value should be returned.
 187   *
 188   * @return mixed The file object or empty string.
 189   */
 190  function form_type_image_upload_element_value($form, $edit = FALSE) {
 191    return form_type_upload_element_value($form, $edit);
 192  }
 193  
 194  /**
 195   * This is the core function that handles the uploading and workflow
 196   * of the submitted files.
 197   *
 198   * @param array $form The form element whose value is being populated.
 199   * @param mixed $edit The incoming POST data to populate the form element.
 200   * If this is FALSE, the element's default value should be returned.
 201   *
 202   * @return mixed The file object or empty string.
 203   */
 204  function form_type_upload_element_value($form, $edit = FALSE) {
 205    if ($edit !== FALSE) {
 206      $name = $form['#name'];
 207      $action = $form['#post'][$name][$name .'_action'];
 208      if (is_object($form['#default_value'])) {
 209        if ($action == 'delete') {
 210          upload_element_session_handler('delete', $form);
 211        }
 212        if ($action == 'restore') {
 213          upload_element_session_handler('restore', $form);
 214        }
 215      }
 216      if ($action == 'revert') {
 217        upload_element_session_handler('revert', $form);
 218      }
 219      // add image validator, default max size validators have no meaning here
 220      // as the form submission will have already failed.
 221      if ($form['#type'] == 'image_upload_element') {
 222        $form['#file_validators']['file_validate_is_image'] = array();
 223      }
 224      $file = file_save_upload($name, $form['#file_validators']);
 225      if (!$file && isset($_FILES['files']) && $_FILES['files']['name'][$name]) {
 226        switch ($_FILES['files']['error'][$name]) {
 227          case UPLOAD_ERR_INI_SIZE:
 228          case UPLOAD_ERR_FORM_SIZE:
 229            drupal_set_message(t('The file %file could not be saved, because it exceeds %maxsize, the maximum allowed size for uploads.', array('%file' => $source, '%maxsize' => format_size(file_upload_max_size()))), 'error');
 230        }
 231      }
 232      $value = !empty($file)
 233          ? upload_element_session_handler('store', $form, $file)
 234          : upload_element_session_handler('value', $form);
 235      return $value;
 236    }
 237    else {
 238      return $form['#default_value'];
 239    }
 240  }
 241  
 242  /**
 243   * A private helper function to parse the real value from
 244   * the element. This takes into account the submit_action
 245   * when present.
 246   *
 247   * @param array $element Upload element
 248   * @return mixed File object or FALSE.
 249   */
 250  function _upload_element_parse_value($element) {
 251    if (is_object($element['#value'])) {
 252      if (isset($element['#value']->submit_action)) {
 253        return ($element['#value']->submit_action == UPLOAD_ELEMENT_DELETE)
 254          ? FALSE : $element['#value'];
 255      }
 256      else {
 257        return $element['#value'];
 258      }
 259    }
 260    return FALSE;
 261  }
 262  
 263  /**
 264   * The custom validation required for files that are marked
 265   * as deleted, but are required.
 266   *
 267   * @param array $element
 268   * @param array $form_state
 269   */
 270  function upload_element_element_validate($element, &$form_state) {
 271    if ($element['#required'] && !_upload_element_parse_value($element)) {
 272      form_error($element, t('!name field is required.', array('!name' => $element['#title'])));
 273    }
 274  }
 275  
 276  /**
 277   * Simple helper function to compare to file elements
 278   *
 279   * @param mixed $a file object to compare
 280   * @param mixed $b file object to compare
 281   * @return bool
 282   */
 283  function upload_element_equals($a = FALSE, $b = FALSE) {
 284    if (is_object($a) && is_object($b)) {
 285      return $a->fid == $b->fid;
 286    }
 287    return FALSE;
 288  }
 289  
 290  /**
 291   * Theme function to format the edit form.
 292   */
 293  function theme_image_upload_element($element) {
 294    return theme('upload_element', $element);
 295  }
 296  
 297  /**
 298   * Theme function to format the edit form.
 299   */
 300  function theme_upload_element($element) {
 301    _form_set_class($element, array('form-file'));
 302    $preview = '';
 303    if ($element['#image_formatter']) {
 304      $preview = theme($element['#image_formatter'], $element);
 305      // We need to calculate the required margin for the details section.
 306      $width = 100;
 307      if ($element['#image_preview_size'] && preg_match('/^\d+x\d+$/', $element['#image_preview_size'])) {
 308        list($width,) = explode('x', $element['#image_preview_size'], 2);
 309      }
 310      $details_styles = ' style="margin-left:'. ($width + 10) . 'px;"';
 311    }
 312    $file_details = '';
 313    if ($element['#file_formatter']) {
 314      $file_details = theme($element['#file_formatter'], $element);
 315    }
 316  
 317    $messages = '';
 318    if (!empty($element['#messages'])) {
 319      $messages = ' <div class="ahah-messages">'. $element['#messages'] ."</div>\n";
 320    }
 321    $action_field = _upload_element_action_field($element);
 322    $description = $element['#description'] ? '<div class="description">'. $element['#description'] .'</div>' : '';
 323    $value = <<<END
 324      {$preview}
 325      <div class="upload-element-detail" {$details_styles}>
 326        {$messages}
 327        {$file_details}
 328        {$action_field}
 329        {$element['#children']}
 330        <br class="upload-element-clear" />
 331        {$description}
 332      </div>
 333      <br class="upload-element-clear" />
 334  END;
 335      $ahah_wrapper_id = $element['#id'] .'-ahah-wrapper';
 336      unset($element['#id']);
 337      unset($element['#description']);
 338      return isset($element['#is_ahah']) ? $value : theme('form_element', $element, "<div id=\"{$ahah_wrapper_id}\" class=\"upload-element-row\">". $value .'</div>');
 339  }
 340  
 341  /**
 342   * Private function to generate the options that go with the
 343   * upload element
 344   *
 345   * @param array $element Parent upload element
 346   * @return array $children Child elements
 347   */
 348  function _upload_element_action_field($element) {
 349    $children = array();
 350    if (is_object($element['#value'])) {
 351      $name = $element['#name'];
 352      $key = $name .'_action';
 353      $children[$key]= array(
 354        '#type' => 'checkbox',
 355        '#id' => form_clean_id("edit-{$key}"),
 356        '#name' => "{$name}[{$key}]",
 357        '#value' => 0,
 358        '#weight' => -10,
 359      );
 360      // TODO: While this is working, there may be two logical bugs
 361      // the negate each other.
 362      if (upload_element_equals($element['#value'], $element['#default_value'])) {
 363        if (isset($element['#value']->submit_action) && $element['#value']->submit_action == UPLOAD_ELEMENT_DELETE) {
 364          $children[$key]['#return_value'] = 'restore';
 365          $children[$key]['#title'] = t('Restore original');
 366        }
 367        else {
 368          $children[$key]['#return_value'] = 'delete';
 369          $children[$key]['#title'] = t('Delete original');
 370          $children[$key]['#value'] = (isset($element['#value']->submit_action)
 371                ? ($element['#value']->submit_action == UPLOAD_ELEMENT_DELETE ? 'delete' : 0)
 372                : 0);
 373        }
 374      }
 375      else {
 376        $children[$key]['#return_value'] = 'revert';
 377        $children[$key]['#title'] = (is_object($element['#default_value']) ? t('Discard replacment') : t('Discard upload'));
 378      }
 379    }
 380    return drupal_render($children);
 381  }
 382  
 383  /**
 384   * Simple theming function to display the uploaded file.
 385   *
 386   * @param object $file File object
 387   * @return string HTML of the filename and size.
 388   */
 389  function theme_upload_element_preview($element = NULL) {
 390    $label = t('Filename');
 391    $filename = '--';
 392    $filesize = '';
 393    $class = 'upload-element-preview';
 394    if ($file = _upload_element_parse_value($element)) {
 395      $filename = check_plain($file->filename);
 396      $filesize = '('. format_size($file->filesize) .')';
 397      // Add some nice mime type classes
 398      if ($file->filemime) {
 399        list($base_mime, $extended_mime) = explode('/', $file->filemime);
 400        $class = trim($class .' mime-'. $base_mime .' '. ($extended_mime ? ' mime-'. $base_mime .'-'. $extended_mime : ''));
 401      }
 402    }
 403    return <<<END
 404        <div class="upload-element-file-description">
 405          <strong>{$label}: </strong>
 406          <span class="{$class}">{$filename} {$filesize}</span>
 407        </div>
 408  
 409  END;
 410  }
 411  
 412  /**
 413   * This creates the thumbnail preview HTML.
 414   *
 415   * @param array $element
 416   * @return string HTML for image thumbnail.
 417   */
 418  function theme_upload_element_image_preview($element = NULL) {
 419    $fid = 'no_image';
 420    if ($file = _upload_element_parse_value($element)) {
 421      $fid = $file->fid;
 422    }
 423    $src = url('upload_element/'. $element['#build_id'] .'/'. $element['#name'] .'/'. $fid);
 424    return '<div class="upload-element-preview"><img src="'. $src .'" alt="'. t('Image preview') .'" /></div>';
 425  }
 426  
 427  /**
 428   * Saves an uploaded file
 429   *
 430   * @param object $file File object
 431   * @param string $dest destination directory to move the file to
 432   * @param int $replace files move action
 433   * @param string $presetname Imagecache preset to perfrom on the uploaded image.
 434   * @param bool $delete_original A flag to tell the function how to handle
 435   *   the existing file when it is deleted or replaced. This is used to
 436   *   prevent the status flag being set to temperory when the file is still used
 437   *   by the system somewhere else. For example, if you are saving a new
 438   *   node revision, with a new file, you would want to ensure that this is
 439   *   set to FALSE if the old image is still valid for some other revision.
 440   * @return int The {files}.fid or 0
 441   */
 442  function upload_element_save(&$file, $dest = 0, $replace = FILE_EXISTS_RENAME, $presetname = FALSE, $delete_original = TRUE) {
 443    $fid = 0;
 444    if (is_object($file)) {
 445      $base = file_directory_path();
 446      if (strstr($dest, $base) === FALSE) {
 447        $dest = $base .'/'. ltrim($dest, '/');
 448      }
 449  
 450      file_check_directory($dest, 1);
 451      if (!isset($file->submit_action)) {
 452        $file->submit_action = UPLOAD_ELEMENT_NONE;
 453      }
 454      switch ($file->submit_action) {
 455        case UPLOAD_ELEMENT_NONE:
 456          $fid = $file->fid;
 457          break;
 458        case UPLOAD_ELEMENT_DELETE:
 459          if ($delete_original) {
 460            _upload_element_delete($file->fid);
 461          }
 462          break;
 463        case UPLOAD_ELEMENT_REPLACE:
 464          if ($delete_original) {
 465            _upload_element_delete($file->original_fid);
 466          }
 467          // fall through
 468        case UPLOAD_ELEMENT_NEW:
 469          $uploaded = FALSE;
 470          if ($presetname) {
 471            $destination = file_create_filename($file->filename, $dest);
 472            if (upload_element_imagecache_action($presetname, $file->filepath, $destination)) {
 473              $file->filepath = $destination;
 474              $uploaded = TRUE;
 475            }
 476          }
 477          if (!$uploaded) {
 478            $uploaded = file_move($file, $dest .'/'. $file->filename, $replace);
 479          }
 480          if ($uploaded) {
 481            $file->status = FILE_STATUS_PERMANENT;
 482            // Clear PHP stat cache in case filesize has changed.
 483            clearstatcache();
 484            if ($file_size = @filesize($file->filepath)) {
 485              $file->filesize = $file_size;
 486            }
 487            drupal_write_record('files', $file, 'fid');
 488            $fid = $file->fid;
 489            // Imagecache may need flushing if using the same filepath.
 490            if (function_exists('imagecache_image_flush')) {
 491              imagecache_image_flush($file->filepath);
 492            }
 493          }
 494          else {
 495            drupal_set_message(t('Error occured while saving the image!'), 'error');
 496          }
 497          break;
 498      }
 499    }
 500    // This cleans up the session by flushing old values.
 501    upload_element_clean_session();
 502  
 503    return $fid;
 504  }
 505  
 506  /**
 507   * Hooks into imageache preset for save action
 508   *
 509   * @param string $presetname Imagecache preset to perfrom on the uploaded image.
 510   * @param string $path Path to the temp original image file.
 511   * @param string $dest Path to save the new image to.
 512   *
 513   * @return bool FALSE if there was a problem saving the image, TRUE otherwise.
 514   */
 515  function upload_element_imagecache_action($presetname, $path, $dst) {
 516    if (!function_exists('imagecache_preset_by_name')) {
 517      return FALSE;
 518    }
 519  
 520    if (!$preset = imagecache_preset_by_name($presetname)) {
 521      return FALSE;
 522    }
 523    if (is_file($dst)) {
 524      return TRUE;
 525    }
 526    $src = $path;
 527    if (!is_file($src) && !is_file($src = file_create_path($src))) {
 528      return FALSE;
 529    };
 530    if (!getimagesize($src)) {
 531      return FALSE;
 532    }
 533    $lockfile = file_directory_temp() .'/'. $preset['presetname'] . basename($src);
 534    if (file_exists($lockfile)) {
 535      watchdog('imagecache', 'Imagecache already generating: %dst, Lock file: %tmp.', array('%dst' => $dst, '%tmp' => $lockfile), WATCHDOG_NOTICE);
 536      return FALSE;
 537    }
 538    touch($lockfile);
 539    register_shutdown_function('file_delete', realpath($lockfile));
 540    if (file_exists($dst) || imagecache_build_derivative($preset['actions'], $src, $dst)) {
 541      return TRUE;
 542    }
 543    // Generate an error if image could not generate.
 544    watchdog('imagecache', 'Failed generating an image from %image using imagecache preset %preset.', array('%image' => $path, '%preset' => $preset['presetname']), WATCHDOG_ERROR);
 545    return FALSE;
 546  }
 547  
 548  /**
 549   * The core storage handler for keeping the correct state
 550   * of the element in between form submissions/AHAH requests.
 551   *
 552   * @param string $op Operation key.
 553   * @param array $form The upload_element element.
 554   * @param mixed $file File object or empty string
 555   * @return mixed File object or NULL depending on the $op.
 556   */
 557  function upload_element_session_handler($op, &$form, $file = '') {
 558    $name = $form['#name'];
 559    $form_build_id = $form['#post']['form_build_id'];
 560    $session_files = &$_SESSION['files']['upload_element'][$form_build_id];
 561    switch ($op) {
 562      case 'revert':
 563        unset($session_files[$name]);
 564        if (is_object($session_files[$name .'_default'])) {
 565          $session_files[$name .'_default']->submit_action = UPLOAD_ELEMENT_NONE;
 566        }
 567        break;
 568      case 'value':
 569        $file = (isset($session_files[$name])) ? $session_files[$name] : $session_files[$name .'_default'];
 570        return is_object($file) ? $file : '';
 571      case 'restore':
 572      // delete op only applies to default file that is stored in the session
 573      case 'delete':
 574        $submit_action = ($op == 'restore') ? UPLOAD_ELEMENT_NONE : UPLOAD_ELEMENT_DELETE;
 575        $session_files[$name .'_default']->submit_action = $submit_action;
 576        unset($session_files[$name]);
 577        if (is_object($form['#default_value'])) {
 578          $form['#default_value']->submit_action = $submit_action;
 579        }
 580        break;
 581      case 'store':
 582        if (is_object(($session_files[$name .'_default']))) {
 583          $file->submit_action = UPLOAD_ELEMENT_REPLACE;
 584          $file->original_fid = $session_files[$name .'_default']->fid;
 585        }
 586        else {
 587          $file->submit_action = UPLOAD_ELEMENT_NEW;
 588        }
 589        $session_files[$name] = $file;
 590        return $file;
 591    }
 592  }
 593  
 594  /**
 595   * Session cleaning function.
 596   *
 597   * This is used to prevent excess values getting stored
 598   * within the $_SESSION over multiple requests. It uses
 599   * the form cache to determine if the value should be
 600   * deleted or not.
 601   */
 602  function upload_element_clean_session() {
 603    $form_state = array('submitted' => FALSE);
 604    foreach($_SESSION['files']['upload_element'] as $form_build_id => $values) {
 605      if (!$form = form_get_cache($form_build_id, $form_state)) {
 606        unset($_SESSION['files']['upload_element'][$form_build_id]);
 607      }
 608    }
 609  }
 610  
 611  /**
 612   * This theming function can be used to assign different text to
 613   * the description that is found under the file HTML element.
 614   *
 615   * @param array $element FAPI upload element
 616   */
 617  function theme_upload_element_file_description($element) {
 618    // set file validation defaults for the theming functions
 619    _upload_element_add_file_validators($element);
 620  
 621    $validation_messages = array();
 622    if (isset($element['#file_validators']['file_validate_extensions'])) {
 623      $ext = _upload_element_allowed_extensions($element);
 624      $validation_messages[] = t('Only files with the following extensions are allowed: %ext.', array('%ext' => implode(', ', $ext)));
 625    }
 626    elseif (isset($element['#file_validators']['file_validate_is_image'])) {
 627      $validation_messages[] = t('Only JPEG, PNG and GIF images are allowed.');
 628    }
 629    if (isset($element['#file_validators']['file_validate_size'])) {
 630      $validation_messages[] = t('The maximum upload size is %filesize.', array('%filesize' => format_size($element['#file_validators']['file_validate_size'][0])));
 631    }
 632    $validation_messages[] = t('Changes made are not permanent until you save this form.');
 633    $validator_seperator = isset($element['#file_validator_seperator']) ? $element['#file_validator_seperator'] : '<br />';
 634    return implode($validator_seperator, $validation_messages);
 635  }
 636  
 637  /**
 638   * Private helper function to help pull out the allowed
 639   * extensions.
 640   *
 641   * @param array $element
 642   */
 643  function _upload_element_allowed_extensions($element) {
 644    if ($element['#type'] == 'upload_element') {
 645      return array_filter(explode(' ', strtoupper($element['#file_validators']['file_validate_extensions'][0])));
 646    }
 647    elseif (isset($element['#file_validators']['file_validate_extensions'])) {
 648      return array_intersect(explode(' ', strtoupper($element['#file_validators']['file_validate_extensions'][0])), array('JPEG', 'GIF', 'PNG'));
 649    }
 650    else {
 651      return array('JPEG', 'GIF', 'PNG');
 652    }
 653  }
 654  
 655  /**
 656   * This is used to set the default validators
 657   *
 658   * We are in a catch-22 here. If we set it in hook_elements,
 659   * the chances are that these will be overridden by any user
 660   * defined values. If we set these in the #process callback,
 661   * the options are not available to form_type_"hook"_value
 662   * or theme functions.
 663   *
 664   * As such, we dynamically add these here.
 665   */
 666  function _upload_element_add_file_validators(&$element) {
 667    // Add the default validators.
 668    if ($element['#type'] == 'image_upload_element') {
 669      $element['#file_validators']['file_validate_is_image'] = array();
 670    }
 671    // Check user defined max size is not greater than form/post size.
 672    $max = file_upload_max_size();
 673    if (isset($element['#file_validators']['file_validate_size'])) {
 674      if ($element['#file_validators']['file_validate_size'][0] > $max) {
 675        $element['#file_validators']['file_validate_size'] = array($max);
 676      }
 677    }
 678    else {
 679      $element['#file_validators']['file_validate_size'] = array($max);
 680    }
 681  }
 682  
 683  /**
 684   * Private helper function for to delete files during the save process
 685   *
 686   * @param $fid The fid of a file object to delete.
 687   */
 688  function _upload_element_delete($fid) {
 689    $result = db_query('SELECT * FROM {files} WHERE fid = %d', $fid);
 690    if ($file = db_fetch_object($result)) {
 691      if (file_exists($file->filepath)) {
 692        // If files that exist cannot be deleted, log it for manual deletion.
 693        if (!file_delete($file->filepath)) {
 694          watchdog('upload_element', 'Could not delete file "%path".', array('%path' => $file->filepath), 'error');
 695        }
 696      }
 697      else {
 698        watchdog('upload_element', 'Attempting to delete missing file "%path".', array('%path' => $file->filepath), 'error');
 699      }
 700    }
 701    db_query('DELETE FROM {files} WHERE fid = %d', $fid);
 702  }


Generated: Thu Mar 24 11:18:33 2011 Cross-referenced by PHPXref 0.7