[ Index ]

PHP Cross Reference of Drupal 6 (gatewave)

title

Body

[close]

/sites/all/modules/imce/inc/ -> imce.page.inc (source)

   1  <?php
   2  // $Id: imce.page.inc,v 1.1.2.9 2010/12/27 20:08:33 ufku Exp $
   3  
   4  /**
   5   * @file
   6   * Implements the file browser.
   7   */
   8  
   9  /**
  10   * q = imce.
  11   */
  12  function imce() {
  13    module_invoke('admin_menu', 'suppress');//suppress admin_menu
  14    $jsop = isset($_GET['jsop']) ? $_GET['jsop'] : NULL;
  15    print imce_page($GLOBALS['user'], $jsop);
  16    exit();
  17  }
  18  
  19  /**
  20   * q = user/x/imce.
  21   */
  22  function imce_user_page($account) {
  23    return theme('imce_user_page', $account);
  24  }
  25  
  26  /**
  27   * Returns the imce page for the specified user.
  28   */
  29  function imce_page($user, $jsop = NULL) {
  30    return theme('imce_page', imce_content($user, $jsop));
  31  }
  32  
  33  /**
  34   * Returns the content of the file browser.
  35   */
  36  function imce_content($user, $jsop = NULL) {
  37  
  38    //execute ajax calls.
  39    if ($jsop) {
  40      return imce_js($user, $jsop);
  41    }
  42  
  43    //initiate configuration profile
  44    if (!$imce = imce_initiate_profile($user)) {
  45      return '';
  46    }
  47    imce_process_profile($imce);//get active directory content
  48  
  49    //Before creating the content let's add main files required for imce to function properly.
  50    $path = drupal_get_path('module', 'imce');
  51    drupal_add_js($path . '/js/jquery.form.js');
  52    drupal_add_js($path . '/js/imce.js');
  53    drupal_add_js($path . '/js/imce_extras.js');
  54    drupal_add_css($path . '/css/imce-content.css');
  55  
  56    //process forms.
  57    //reference imce inside an array so it will stay referenced during argument copy of drupal_get_form
  58    $imce_ref = array('imce' => &$imce);
  59    $forms = '';
  60  
  61    if (!$imce['error']) {
  62      //process file upload.
  63      if (imce_perm_exists($imce, 'upload')) {
  64        $forms .= drupal_get_form('imce_upload_form', $imce_ref);
  65      }
  66      //process file operations.
  67      $forms .= drupal_get_form('imce_fileop_form', $imce_ref);
  68    }
  69  
  70    //run custom content functions. possible to insert extra forms. content is invisible when js is enabled.
  71    foreach (variable_get('imce_custom_content', array()) as $func => $state) {
  72      if ($state && function_exists($func) && $output = $func($imce)) {
  73        $forms .= $output;
  74      }
  75    }
  76  
  77    $content = theme('imce_content', imce_create_tree($imce), $forms, $imce_ref);
  78  
  79    //make necessary changes for js conversion
  80    $imce['dir'] = str_replace('%2F', '/', rawurlencode($imce['dir']));
  81    unset($imce['files'], $imce['name'], $imce['directories'], $imce['subdirectories'], $imce['filesize'], $imce['quota'], $imce['tuquota'], $imce['thumbnails'], $imce['uid'], $imce['usertab']);
  82  
  83    drupal_add_js($imce_ref, 'setting');
  84  
  85    return $content;
  86  }
  87  
  88  /**
  89   * Ajax operations. q=imce&jsop={op}
  90   */
  91  function imce_js($user, $jsop = '') {
  92    $response = array();
  93  
  94    //data
  95    if ($imce = imce_initiate_profile($user)) {
  96      imce_process_profile($imce);
  97      if (!$imce['error']) {
  98        module_load_include('inc', 'imce', 'inc/imce.js');
  99        if (function_exists($func = 'imce_js_'. $jsop)) {
 100          $response['data'] = $func($imce);
 101        }
 102      }
 103    }
 104    //messages
 105    $response['messages'] = drupal_get_messages();
 106  
 107    //disable devel log.
 108    $GLOBALS['devel_shutdown'] = FALSE;
 109    //for upload we must return plain text header.
 110    drupal_set_header('Content-Type: text/'. ($jsop == 'upload' ? 'html' : 'javascript') .'; charset=utf-8');
 111    print drupal_to_js($response);
 112    exit();
 113  }
 114  
 115  /**
 116   * Upload form.
 117   */
 118  function imce_upload_form(&$form_state, $ref) {
 119    $imce =& $ref['imce'];
 120    $form['imce'] = array(
 121      '#type' => 'file',
 122      '#title' => t('File'),
 123      '#size' => 30,
 124    );
 125    if (!empty($imce['thumbnails'])) {
 126      $form['thumbnails'] = array(
 127        '#type' => 'checkboxes',
 128        '#title' => t('Create thumbnails'),
 129        '#options' => imce_thumbnail_options($imce['thumbnails']),
 130      );
 131    }
 132    $form['upload'] = array(
 133      '#type' => 'submit',
 134      '#value' => t('Upload'),
 135      '#submit' => $imce['perm']['upload'] ? array('imce_upload_submit') : NULL,
 136    );
 137    $form = array('fset_upload' => array('#type' => 'fieldset', '#title' => t('Upload file')) + $form);
 138    $form['#attributes']['enctype'] = 'multipart/form-data';
 139    $form['#action'] = $imce['url'];
 140    return $form;
 141  }
 142  
 143  /**
 144   * File operations form.
 145   */
 146  function imce_fileop_form(&$form_state, $ref) {
 147    $imce =& $ref['imce'];
 148    $form['filenames'] = array(
 149      '#type' => 'textfield',
 150      '#title' => t('Selected files'),
 151      '#maxlength' => $imce['filenum'] ? $imce['filenum']*255 : NULL,
 152    );
 153  
 154    //thumbnail
 155    if (!empty($imce['thumbnails']) && imce_perm_exists($imce, 'thumb')) {
 156      $form['fset_thumb'] = array(
 157        '#type' => 'fieldset',
 158        '#title' => t('Thumbnails'),
 159      ) + imce_thumb_form($imce);
 160    }
 161  
 162    //delete
 163    if (imce_perm_exists($imce, 'delete')) {
 164      $form['fset_delete'] = array(
 165        '#type' => 'fieldset',
 166        '#title' => t('Delete'),
 167      ) + imce_delete_form($imce);
 168    }
 169  
 170    //resize
 171    if (imce_perm_exists($imce, 'resize')) {
 172      $form['fset_resize'] = array(
 173        '#type' => 'fieldset',
 174        '#title' => t('Resize'),
 175      ) + imce_resize_form($imce);
 176    }
 177   
 178    $form['#action'] = $imce['url'];
 179    return $form;
 180  }
 181  
 182  /**
 183   * Thumbnail form.
 184   */
 185  function imce_thumb_form(&$imce) {
 186    $form['thumbnails'] = array(
 187      '#type' => 'checkboxes',
 188      '#title' => t('Thumbnails'),
 189      '#options' => imce_thumbnail_options($imce['thumbnails']),
 190    );
 191    $form['thumb'] = array(
 192      '#type' => 'submit',
 193      '#value' => t('Create thumbnails'),
 194      '#submit' => $imce['perm']['thumb'] ? array('imce_thumb_submit') : NULL,
 195    );
 196    return $form;
 197  }
 198  
 199  /**
 200   * Delete form.
 201   */
 202  function imce_delete_form(&$imce) {
 203    $form['delete'] = array(
 204      '#type' => 'submit',
 205      '#value' => t('Delete'),
 206      '#submit' => $imce['perm']['delete'] ? array('imce_delete_submit') : NULL,
 207    );
 208    return $form;
 209  }
 210  
 211  /**
 212   * Resizing form.
 213   */
 214  function imce_resize_form(&$imce) {
 215    $form['width'] = array(
 216      '#type' => 'textfield',
 217      '#title' => t('Width x Height'),
 218      '#size' => 5,
 219      '#maxlength' => 4,
 220      '#prefix' => '<div class="container-inline">',
 221    );
 222    $form['height'] = array(
 223      '#type' => 'textfield',
 224      '#size' => 5,
 225      '#maxlength' => 4,
 226      '#prefix' => 'x',
 227    );
 228    $form['resize'] = array(
 229      '#type' => 'submit',
 230      '#value' => t('Resize'),
 231      '#submit' => $imce['perm']['resize'] ? array('imce_resize_submit') : NULL,//permission for submission
 232      '#suffix' => '</div>',
 233    );
 234    $form['copy'] = array(
 235      '#type' => 'checkbox',
 236      '#title' => t('Create a new image'),
 237      '#default_value' => 1,
 238    );
 239    return $form;
 240  }
 241  
 242  /**
 243   * Validate file operations form.
 244   */
 245  function imce_fileop_form_validate($form, &$form_state) {
 246    $imce =& $form['#parameters'][2]['imce'];
 247  
 248    //check if the filenames is empty
 249    if ($form_state['values']['filenames'] == '') {
 250      return form_error($form['filenames'], t('Please select a file.'));
 251    }
 252  
 253    //filenames come seperated by colon
 254    $filenames = explode(':', $form_state['values']['filenames']);
 255    $cnt = count($filenames);
 256    //check the number of files.
 257    if ($imce['filenum'] && $cnt > $imce['filenum']) {
 258      return form_error($form['filenames'], t('You are not allowed to operate on more than %num files.', array('%num' => $imce['filenum'])));
 259    }
 260  
 261    //check if there is any illegal choice
 262    for ($i = 0; $i < $cnt; $i++) {
 263      $filenames[$i] = $filename = rawurldecode($filenames[$i]);
 264      if (!isset($imce['files'][$filename])) {
 265        watchdog('imce', 'Illegal choice %choice in !name element.', array('%choice' => $filename, '!name' => t('directory (%dir)', array('%dir' => file_directory_path() . ($imce['dir'] == '.' ? '' : '/'. $imce['dir'])))), WATCHDOG_ERROR);
 266        return form_error($form['filenames'], t('An illegal choice has been detected. Please contact the site administrator.'));
 267      }
 268    }
 269  
 270    $form_state['values']['filenames'] = $filenames;
 271  }
 272  
 273  /**
 274   * Submit upload form.
 275   */
 276  function imce_upload_submit($form, &$form_state) {
 277    $form_state['redirect'] = FALSE;
 278    $imce =& $form['#parameters'][2]['imce'];
 279    $validators = array('imce_validate_all' => array(&$imce));
 280    $dirpath = file_directory_path() . ($imce['dir'] == '.' ? '' : '/'. $imce['dir']);
 281  
 282    //save uploaded file.
 283    $replace = variable_get('imce_settings_replace', FILE_EXISTS_RENAME);
 284    if ($file = file_save_upload('imce', $validators, $dirpath, $replace)) {
 285  
 286      //core bug #203204.
 287      @chmod($file->filepath, 0664);
 288  
 289      //core bug #54223.
 290      if ($replace == FILE_EXISTS_RENAME) {
 291        $name = basename($file->filepath);
 292        if ($name != $file->filename) {
 293          $file->filename = $name;
 294          drupal_set_message(t('The file has been renamed to %filename.', array('%filename' => $file->filename)));
 295        }
 296      }
 297      elseif ($replace == FILE_EXISTS_REPLACE) {//check duplicates
 298        if ($_file = db_fetch_object(db_query("SELECT fid FROM {files} WHERE filepath = '%s' AND fid <> %d", $file->filepath, $file->fid))) {
 299          db_query("DELETE FROM {files} WHERE fid = %d", $file->fid);
 300          $file->fid = $_file->fid;
 301        }
 302      }
 303  
 304      $file->uid = $imce['uid'];//global user may not be the owner.
 305      $file->status = FILE_STATUS_PERMANENT;//make permanent
 306      drupal_write_record('files', $file, array('fid'));//update
 307      imce_file_register($file);
 308      drupal_set_message(t('%filename has been uploaded.', array('%filename' => $file->filename)));
 309  
 310      //update file list
 311      $img = imce_image_info($file->filepath);
 312      $file->width = $img ? $img['width'] : 0;
 313      $file->height = $img ? $img['height'] : 0;
 314      imce_add_file($file, $imce);
 315  
 316      //create thumbnails
 317      if (isset($form_state['values']['thumbnails']) && $img) {
 318        imce_create_thumbnails($file->filename, $imce, $form_state['values']['thumbnails']);
 319      }
 320    }
 321    else {
 322      drupal_set_message(t('Upload failed.'), 'error');
 323    }
 324  }
 325  
 326  /**
 327   * Submit thumbnail form.
 328   */
 329  function imce_thumb_submit($form, &$form_state) {
 330    $form_state['redirect'] = FALSE;
 331    $imce =& $form['#parameters'][2]['imce'];
 332    //create thumbnails
 333    imce_process_files($form_state['values']['filenames'], $imce, 'imce_create_thumbnails', array($form_state['values']['thumbnails']));
 334  }
 335  
 336  /**
 337   * Submit delete form.
 338   */
 339  function imce_delete_submit($form, &$form_state) {
 340    $form_state['redirect'] = FALSE;
 341    $imce =& $form['#parameters'][2]['imce'];
 342  
 343    $deleted = imce_process_files($form_state['values']['filenames'], $imce, 'imce_delete_file');
 344  
 345    if (!empty($deleted)) {
 346      drupal_set_message(t('File deletion successful: %files.', array('%files' => utf8_encode(implode(', ', $deleted)))));
 347    }
 348  
 349  }
 350  
 351  /**
 352   * Submit resize form.
 353   */
 354  function imce_resize_submit($form, &$form_state) {
 355    $form_state['redirect'] = FALSE;
 356    $imce =& $form['#parameters'][2]['imce'];
 357  
 358    //check dimensions
 359    $width = (int) $form_state['values']['width'];
 360    $height = (int) $form_state['values']['height'];
 361    list($maxw, $maxh) = explode('x', $imce['dimensions']);
 362    if ($width < 1 || $height < 1 || ($maxw && ($width > $maxw || $height > $maxh))) {
 363      drupal_set_message(t('Please specify dimensions within the allowed range that is from 1x1 to @dimensions.', array('@dimensions' => $imce['dimensions'] ? $imce['dimensions'] : t('unlimited'))), 'error');
 364      return;
 365    }
 366  
 367    $resized = imce_process_files($form_state['values']['filenames'], $imce, 'imce_resize_image', array($width, $height, $form_state['values']['copy']));
 368  
 369    if (!empty($resized)) {
 370      drupal_set_message(t('File resizing successful: %files.', array('%files' => utf8_encode(implode(', ', $resized)))));
 371    }
 372  
 373  }
 374  
 375  /**
 376   * Do batch operations on files.
 377   * Used by delete, resize, create thumbnail submissions.
 378   */
 379  function imce_process_files($filenames, &$imce, $function, $args = array()) {
 380    $args = array_merge(array('', &$imce), $args);
 381    $processed = array();
 382  
 383    foreach ($filenames as $filename) {
 384      $args[0] = $filename;
 385      if (call_user_func_array($function, $args)) {
 386        $processed[] = $filename;
 387      }
 388    }
 389  
 390    return $processed;
 391  }
 392  
 393  /**
 394   * Delete a file in the file list.
 395   */
 396  function imce_delete_file($filename, &$imce) {
 397    $filepath = file_directory_path() . ($imce['dir'] == '.' ? '' : '/'. $imce['dir']) .'/'. $filename;
 398    if (!imce_delete_filepath($filepath)) {
 399      return FALSE;
 400    }
 401    imce_remove_file($filename, $imce);
 402    return TRUE;
 403  }
 404  
 405  /**
 406   * Delete a file by path.
 407   */
 408  function imce_delete_filepath($filepath) {
 409    $file = db_fetch_object(db_query("SELECT * FROM {files} WHERE filepath = '%s'", $filepath));
 410  
 411    //file exists in database
 412    if ($file) {
 413      //prevent imce returning ref count
 414      $file->imce_noref = TRUE;
 415      //check references
 416      $refs = array_filter(module_invoke_all('file_references', $file));
 417      //file is in use
 418      if (!empty($refs)) {
 419        drupal_set_message(t('%filename is in use by another application.', array('%filename' => $file->filename)), 'error');
 420        return FALSE;
 421      }
 422      //prepare deletion
 423      module_invoke_all('file_delete', $file);
 424      if (!file_delete($file->filepath)) {
 425        return FALSE;
 426      }
 427      db_query('DELETE FROM {files} WHERE fid = %d', $file->fid);
 428    }
 429    //not in db. probably loaded via ftp.
 430    elseif (!file_delete($filepath)) {
 431      return FALSE;
 432    }
 433  
 434    return TRUE;
 435  }
 436  
 437  /**
 438   * Create all selected thumbnails.
 439   */
 440  function imce_create_thumbnails($filename, &$imce, $values) {
 441    $created = array();
 442    foreach ($imce['thumbnails'] as $thumbnail) {
 443      if ($values[$thumbnail['name']] && imce_create_thumbnail($filename, $imce, $thumbnail)) {
 444        $created[] = $thumbnail['name'];
 445      }
 446    }
 447    if (!empty($created)) {
 448    drupal_set_message(t('Thumbnail creation (%thumbnames) successful for %filename.', array('%thumbnames' => implode(', ', $created), '%filename' => utf8_encode($filename))));
 449    }
 450    return $created;
 451  }
 452  
 453  /**
 454   * Create a thumbnail.
 455   */
 456  function imce_create_thumbnail($filename, &$imce, $thumbnail) {
 457    //generate thumbnail name
 458    $name = $thumbnail['prefix'];
 459    if ($thumbnail['suffix'] != '' && $dot = strrpos($filename, '.')) {
 460      $name .= substr($filename, 0, $dot);
 461      $name .= $thumbnail['suffix'];
 462      $name .= substr($filename, $dot);
 463    }
 464    else {
 465      $name .= $filename;
 466    }
 467    //scale the image
 468    list($width, $height) = explode('x', $thumbnail['dimensions']);
 469    return imce_resize_image($filename, $imce, $width, $height, TRUE, $name, variable_get('imce_settings_thumb_method', 'scale_and_crop'));
 470  }
 471  
 472  /**
 473   * Resize an image in the file list. Also used for thumbnail creation.
 474   */
 475  function imce_resize_image($filename, &$imce, $width, $height, $copy = TRUE, $dest = FALSE, $op = 'resize') {
 476    $dirpath = file_directory_path() . ($imce['dir'] == '.' ? '' : '/'. $imce['dir']);
 477    $filepath = $dirpath .'/'. $filename;
 478  
 479    //check if the file is an image
 480    if (!$imce['files'][$filename]['width'] || !$img = imce_image_info($filepath)) {
 481      drupal_set_message(t('%filename is not an image.', array('%filename' => utf8_encode($filename))), 'error', FALSE);
 482      return FALSE;
 483    }
 484  
 485    if (substr($op, 0, 5) == 'scale' && !($width < $img['width'] || $height < $img['height'])) {
 486      drupal_set_message(t('Scaling up is not allowed.'), 'error', FALSE);
 487      return FALSE;
 488    }
 489  
 490    //create file object
 491    $file = new stdClass();
 492    $file->filepath = $dirpath .'/'. $dest;
 493    if (!$dest || $dest == $filename) {
 494      $file->filepath = $copy ? file_create_filename($filename, $dirpath) : $filepath;
 495    }
 496    $file->filename = basename($file->filepath);
 497  
 498    //check if a file having the same properties exists already.
 499    if (isset($imce['files'][$file->filename])) {
 500      if (($f = $imce['files'][$file->filename]) && $f['width'] == $width && $f['height'] == $height) {
 501        drupal_set_message(t('%filename(%dimensions) already exists.', array('%filename' => utf8_encode($file->filename), '%dimensions' => $width .'x'. $height)), 'error');
 502        return FALSE;
 503      }
 504    }
 505  
 506    //validate file name
 507    $errors = file_validate_name_length($file);
 508    if (!empty($errors)) {
 509      drupal_set_message($errors[0], 'error');
 510      return FALSE;
 511    }
 512  
 513    //resize image to a temp file
 514    $temp = tempnam(realpath(file_directory_temp()), 'imc');
 515    register_shutdown_function('file_delete', $temp);
 516    $function = 'image_'. $op;
 517    if (!$function($filepath, $temp, $width, $height)) {
 518      drupal_set_message(t('%filename cannot be resized to %dimensions', array('%filename' => utf8_encode($filename), '%dimensions' => $width .'x'. $height)), 'error', FALSE);
 519      return FALSE;
 520    }
 521  
 522    //validate quota
 523    $file->filesize = filesize($temp);
 524    $overwrite = $file->filename == $filename;
 525    if (!imce_validate_quotas($file, $imce, $overwrite ? -$imce['files'][$filename]['size'] : 0)) {
 526      return FALSE;
 527    }
 528  
 529    //copy from temp to filepath
 530    if (!@copy($temp, $file->filepath)) {
 531      drupal_set_message(t('The selected file %file could not be copied.', array('%file' => utf8_encode($file->filename))), 'error', FALSE);
 532      return FALSE;
 533    }
 534    @chmod($file->filepath, 0664);
 535  
 536    //build the rest of the file object
 537    $file->uid = $imce['uid'];
 538    $file->filemime = $img['mime'];
 539    $file->status = FILE_STATUS_PERMANENT;
 540    $file->timestamp = time();
 541  
 542    //if we are overwriting the file and it is already in database.
 543    $update = array();
 544    if ($overwrite && $_file = db_fetch_object(db_query("SELECT f.* FROM {files} f WHERE f.filepath = '%s'", $file->filepath))) {
 545      $file->fid = $_file->fid;
 546      $file->uid = $_file->uid;
 547      $update[] = 'fid';
 548    }
 549  
 550    //save the file
 551    drupal_write_record('files', $file, $update);
 552    imce_file_register($file);
 553  
 554    //update file list
 555    //if the file was scaled get the new dimensions
 556    if ($op == 'scale') {
 557      $img = imce_image_info($file->filepath);
 558      $width = $img['width'];
 559      $height = $img['height'];
 560    }
 561    $file->width = $width;
 562    $file->height = $height;
 563    imce_add_file($file, $imce);
 564  
 565    return $file;
 566  }
 567  
 568  /**
 569   * Add a new file to the file list.
 570   */
 571  function imce_add_file($file, &$imce) {
 572    $imce['dirsize'] += $file->filesize;
 573    if (isset($imce['files'][$file->filename])) {
 574      $imce['dirsize'] -= $imce['files'][$file->filename]['size'];
 575    }
 576    $imce['files'][$file->filename] = array(
 577      'name' => $file->filename,
 578      'size' => $file->filesize,
 579      'width' => $file->width,
 580      'height' => $file->height,
 581      'date' => $file->timestamp
 582    );
 583    if (isset($_GET['jsop'])) {
 584      $add = $imce['files'][$file->filename];
 585      $add['name'] = rawurlencode($file->filename);
 586      $add['fsize'] = format_size($file->filesize);
 587      $add['fdate'] = format_date($file->timestamp, 'small');
 588      $add['id'] = $file->fid;
 589      $imce['added'][] = $add;
 590    }
 591  }
 592  
 593  /**
 594   * Remove a file from the file list.
 595   */
 596  function imce_remove_file($filename, &$imce) {
 597    if (isset($imce['files'][$filename])) {
 598      $imce['dirsize'] -= $imce['files'][$filename]['size'];
 599      unset($imce['files'][$filename]);
 600      if (isset($_GET['jsop'])) {
 601        $imce['removed'][] = rawurlencode($filename);
 602      }
 603    }
 604  }
 605  
 606  /**
 607   * Validate uploaded file.
 608   */
 609  function imce_validate_all(&$file, $imce) {
 610  
 611    //fix FILE_EXISTS_ERROR bug. core bug #54223.
 612    if (!$file->destination && variable_get('imce_settings_replace', FILE_EXISTS_RENAME) == FILE_EXISTS_ERROR) {
 613      return array(t('File browser is set to reject the upload of existing files.'));
 614    }
 615  
 616    //validate image resolution only if filesize validation passes.
 617    //because user might have uploaded a very big image
 618    //and scaling it may exploit system memory.
 619    $errors = imce_validate_filesize($file, $imce['filesize']);
 620    //image resolution validation
 621    if (empty($errors) && preg_match('/\.(png|gif|jpe?g)$/i', $file->filename)) {
 622      $errors = array_merge($errors, file_validate_image_resolution($file, $imce['dimensions']));
 623    }
 624    //directory quota validation
 625    if ($imce['quota']) {
 626      $errors = array_merge($errors, imce_validate_quota($file, $imce['quota'], $imce['dirsize']));
 627    }
 628    //file extension validation
 629    if ($imce['extensions'] != '*') {
 630      $errors = array_merge($errors, file_validate_extensions($file, $imce['extensions']));
 631    }
 632    //user quota validation. check it if no errors were thrown.
 633    if (empty($errors) && $imce['tuquota']) {
 634      $errors = imce_validate_tuquota($file, $imce['tuquota'], file_space_used($imce['uid']));
 635    }
 636    return $errors;
 637  }
 638  
 639  /**
 640   * Validate filesize for maximum allowed file size.
 641   */
 642  function imce_validate_filesize($file, $maxsize = 0) {
 643    $errors = array();
 644    if ($maxsize && $file->filesize > $maxsize) {
 645      $errors[] = t('The file is %filesize exceeding the maximum file size of %maxsize.', array('%filesize' => format_size($file->filesize), '%maxsize' => format_size($maxsize)));
 646    }
 647    return $errors;
 648  }
 649  
 650  /**
 651   * Validate filesize for directory quota.
 652   */
 653  function imce_validate_quota($file, $quota = 0, $currentsize = 0) {
 654    $errors = array();
 655    if ($quota && ($currentsize + $file->filesize) > $quota) {
 656      $errors[] = t('%filename is %filesize which would exceed your directory quota. You are currently using %size of %total_quota.', array('%size' => format_size($currentsize), '%total_quota' => format_size($quota), '%filesize' => format_size($file->filesize), '%filename' => utf8_encode($file->filename)));
 657    }
 658    return $errors;
 659  }
 660  
 661  /**
 662   * Validate filesize for total user quota.
 663   */
 664  function imce_validate_tuquota($file, $quota = 0, $currentsize = 0) {
 665    $errors = array();
 666    if ($quota && ($currentsize + $file->filesize) > $quota) {
 667      $errors[] = t('%filename is %filesize which would exceed your total user quota. You are currently using %size of %total_quota.', array('%size' => format_size($currentsize), '%total_quota' => format_size($quota), '%filesize' => format_size($file->filesize), '%filename' => utf8_encode($file->filename)));
 668    }
 669    return $errors;
 670  }
 671  
 672  /**
 673   * Validate both directory and total user quota. Returns true/false not errors.
 674   */
 675  function imce_validate_quotas($file, &$imce, $add = 0) {
 676    $errors = imce_validate_quota($file, $imce['quota'], $imce['dirsize'] + $add);
 677    if (empty($errors) && $imce['tuquota']) {
 678      $errors = imce_validate_tuquota($file, $imce['tuquota'], file_space_used($imce['uid']) + $add);
 679    }
 680    if (!empty($errors)) {
 681      drupal_set_message($errors[0], 'error');
 682      return FALSE;
 683    }
 684    return TRUE;
 685  }
 686  
 687  /**
 688   * Check if the file is an image and return info.
 689   */
 690  function imce_image_info($file) {
 691    if (is_file($file) && ($dot = strrpos($file, '.')) && in_array(strtolower(substr($file, $dot+1)), array('jpg', 'jpeg', 'gif', 'png')) && ($info = @getimagesize($file)) && in_array($info[2], array(IMAGETYPE_JPEG, IMAGETYPE_GIF, IMAGETYPE_PNG)) ) {
 692      return array('width' => $info[0], 'height' => $info[1], 'type' => $info[2], 'mime' => $info['mime']);
 693    }
 694    return FALSE;
 695  }
 696  
 697  /**
 698   * Return thumbnails as options to be used in upload form.
 699   */
 700  function imce_thumbnail_options($thumbs = array()) {
 701    $options = array();
 702    foreach ($thumbs as $thumb) {
 703      $options[$thumb['name']] = $thumb['name'] .' ('. $thumb['dimensions'] .')';
 704    }
 705    return $options;
 706  }
 707  
 708  /**
 709   * Initiate and return configuration profile for the $user.
 710   */
 711  function imce_initiate_profile($user) {
 712  
 713    //check user profile and translate tokens in directory paths and evaluate php paths.
 714    if ($imce = imce_user_profile($user)) {
 715      imce_process_directories($imce, $user);
 716      if (!empty($imce['directories'])) {
 717        $imce['uid'] = (int) $user->uid;
 718        $imce['url'] = url($_GET['q']);
 719        $imce['clean'] = variable_get('clean_url', 0) == 1;
 720        $imce['absurls'] = variable_get('imce_settings_absurls', 0) == 1;
 721        $private = variable_get('file_downloads', '') == FILE_DOWNLOADS_PRIVATE;
 722        $imce['furl'] = $private ? url('system/files') : base_path() . file_directory_path();
 723        $imce['filesize'] *= 1048576;//convert from Mb to byte
 724        $imce['quota'] *= 1048576;
 725        $imce['tuquota'] *= 1048576;
 726        $imce['filenum'] = (int) $imce['filenum'];
 727        //check and set the active directory
 728        if ($info = imce_working_directory($imce)) {
 729          $imce['direct'] = isset($imce['directories'][$info['name']]);
 730          $imce['directories'][$info['name']] = $info;
 731          $imce['dir'] = $info['name'];
 732          $imce['perm'] = $info;//copy permissions of the active directory.
 733          unset($imce['perm']['name']);
 734        }
 735        else {
 736          drupal_set_message(t('Unable to get a working directory for the file browser!'), 'error');
 737          $imce['dir'] = FALSE;
 738          $imce['error'] = TRUE;
 739        }
 740        return $imce;
 741      }
 742      drupal_set_message(t('There is no valid directory specified for the file browser!'), 'error');
 743    }
 744    else {
 745      drupal_set_message(t('You do not have access to any configuration profile to use the file browser!'), 'error');
 746    }
 747  
 748    return FALSE;
 749  }
 750  
 751  /**
 752   * Get files and folders of the actve directory. Do custom processing.
 753   */
 754  function imce_process_profile(&$imce) {
 755    //get directory content. do a custom scan if it is set
 756    $scan = ($scan = variable_get('imce_custom_scan', '')) && function_exists($scan) ? $scan : 'imce_scan_directory';
 757    $imce += $scan($imce['dir'], $imce);
 758  
 759    //run custom process functions
 760    foreach (variable_get('imce_custom_process', array()) as $func => $state) {
 761      if ($state && function_exists($func)) {
 762        $func($imce);
 763      }
 764    }
 765  
 766    //set subdirectories
 767    if (!$imce['error'] && !imce_subdirectories_accessible($imce)) {
 768      $imce['subdirectories'] = array();
 769    }
 770  }
 771  
 772  /**
 773   * Translate tokens and evaluate php in directory names.
 774   * Convert directories into an associative array (dirname => info)
 775   */
 776  function imce_process_directories(&$imce, $user) {
 777    $directories = $imce['directories'];
 778    $paths = array();
 779    $translate = array('%uid' => $user->uid);
 780  
 781    foreach ($directories as $directory) {
 782      if (substr($directory['name'], 0, 4) == 'php:') {
 783        $directory['name'] = eval(substr($directory['name'], 4));
 784       //php may return an array of directories
 785        if (is_array($directory['name'])) {
 786          foreach ($directory['name'] as $name) {
 787            $paths[$name] = array('name' => $name) + $directory;
 788          }
 789          continue;
 790        }
 791      }
 792      else {
 793        $directory['name'] = strtr($directory['name'], $translate);
 794      }
 795      if ($directory['name']) {
 796        $paths[$directory['name']] = $directory;
 797      }
 798    }
 799  
 800    $imce['directories'] = $paths;
 801  }
 802  
 803  /**
 804   * Return an avaliable directory for the profile.
 805   */
 806  function imce_working_directory(&$imce) {
 807    //Do not use session if there is only one directory assigned.
 808    $sess = TRUE;
 809    if (count($imce['directories']) < 2) {
 810      $perms = reset($imce['directories']);
 811      if (!isset($perms['subnav']) || !$perms['subnav']) {
 812        $sess = FALSE;
 813      }
 814    }
 815    //check GET.
 816    if (isset($_GET['dir'])) {
 817      if ($info = imce_directory_info($_GET['dir'], $imce)) {
 818        if (imce_check_directory($_GET['dir'], $imce)) {
 819          if ($sess) {
 820            $_SESSION['imce_directory'] = rawurlencode($info['name']);
 821          }
 822        }
 823        else {
 824          $info = FALSE;
 825        }
 826      }
 827      else {
 828        imce_inaccessible_directory($_GET['dir'], $imce);
 829      }
 830      return $info;
 831    }
 832  
 833    //check session
 834    if ($sess && isset($_SESSION['imce_directory'])) {
 835      $dirname = rawurldecode($_SESSION['imce_directory']);
 836      if ($info = imce_directory_info($dirname, $imce)) {
 837        if (imce_check_directory($dirname, $imce)) {
 838          return $info;
 839        }
 840      }
 841    }
 842  
 843    //or the whole list.
 844    foreach ($imce['directories'] as $dirname => $info) {
 845      if (imce_check_directory($dirname, $imce)) {
 846        if ($sess) {
 847          $_SESSION['imce_directory'] = rawurlencode($dirname);
 848        }
 849        return $info;
 850      }
 851    }
 852  
 853    return FALSE;
 854  }
 855  
 856  /**
 857   * Create a writable directory(any level) under file system directory.
 858   */
 859  function imce_check_directory($dirname, $imce = array()) {
 860  
 861    $root = file_directory_path();
 862    $dirpath = $root .'/'. $dirname;
 863  
 864    if (!file_check_directory($dirpath)) {//directory does not exist. try to create it.
 865      $path = $root;
 866      foreach (explode('/', $dirname) as $arg) {
 867        $path .= '/'. $arg;
 868        if (!file_check_location($path, $root) || !file_check_directory($path, FILE_CREATE_DIRECTORY)) {
 869          return imce_inaccessible_directory($dirname, $imce);
 870        }
 871      }
 872    }
 873    elseif (!file_check_location($dirpath, $root)) {//directory exists outside of root.
 874      return imce_inaccessible_directory($dirname, $imce);
 875    }
 876  
 877    return TRUE;
 878  }
 879  
 880  /**
 881   * Generate and log a directory access error.
 882   */
 883  function imce_inaccessible_directory($dirname, $imce = array()) {
 884    if (is_string($dirname)) {
 885      $dirname = utf8_encode($dirname);
 886      drupal_set_message(t('Directory %dirname is not accessible.', array('%dirname' => $dirname)), 'error');
 887      watchdog('imce', 'Access to %directory was denied.', array('%directory' => $dirname), WATCHDOG_ERROR);
 888    }
 889    return FALSE;
 890  }
 891  
 892  /**
 893   * Return the permissions for a directory that is accessed directly or indirectly.
 894   * A child of a predefined directory in the directory list takes its parent's properties.
 895   * If it has multiple parents, it gets the properties of the latter in the list.
 896   */
 897  function imce_directory_info($dirname, $imce) {
 898  
 899    if (isset($imce['directories'][$dirname])) {
 900      return $imce['directories'][$dirname];
 901    }
 902  
 903    $info = FALSE;
 904    $root = file_directory_path();
 905    $dirpath = $root .'/'. $dirname;
 906    if (imce_reg_dir($dirname) && file_check_directory($dirpath)) {
 907      foreach ($imce['directories'] as $name => $prop) {
 908        if ($prop['subnav'] && file_check_location($dirpath, $root .'/'. $name)) {
 909          $info = $prop;
 910          $info['name'] = $dirname;
 911        }
 912      }
 913    }
 914  
 915    return $info;
 916  }
 917  
 918  /**
 919   * Detect if the subdirectories are accessible through any directory(not just the current one) in the list.
 920   */
 921  function imce_subdirectories_accessible(&$imce) {
 922  
 923    if (!empty($imce['subdirectories'])) {
 924      $root = file_directory_path() .'/';
 925      //checking only the first one is sufficient.
 926      $dirname = ($imce['dir'] == '.' ? '' : $imce['dir'] .'/') . $imce['subdirectories'][0];
 927      $dirpath = $root . $dirname;
 928  
 929      //check if any setting is applicable for this subdirectory through any directory in the list.
 930      foreach ($imce['directories'] as $name => $info) {
 931        if ($info['subnav'] && $dirname != $name && file_check_location($dirpath, $root . $name)) {
 932          return TRUE;
 933        }
 934      }
 935    }
 936  
 937    return FALSE;
 938  }
 939  
 940  /**
 941   * Check if a permission is given to at least one directory in the list.
 942   */
 943  function imce_perm_exists(&$imce, $perm) {
 944    static $perms = array();
 945  
 946    if (isset($perms[$perm])) {
 947      return $perms[$perm];
 948    }
 949  
 950    if (isset($imce['perm'][$perm]) && $imce['perm'][$perm]) {
 951      return $perms[$perm] = TRUE;
 952    }
 953  
 954    foreach ($imce['directories'] as $name => $info) {
 955      if (isset($info[$perm]) && $info[$perm]) {
 956        return $perms[$perm] = TRUE;
 957      }
 958    }
 959  
 960    return $perms[$perm] = FALSE;
 961  }
 962  
 963  /**
 964   * Scan directory and return file list, subdirectories, and total size.
 965   */
 966  function imce_scan_directory($dirname, $imce = array()) {
 967  
 968    $directory = array('dirsize' => 0, 'files' => array(), 'subdirectories' => array(), 'error' => FALSE);
 969    $dirpath = file_directory_path() .'/'. $dirname;
 970  
 971    if (!is_string($dirname) || $dirname == '' || !$handle = opendir($dirpath)) {
 972      imce_inaccessible_directory($dirname, $imce);
 973      $directory['error'] = TRUE;
 974      return $directory;
 975    }
 976  
 977    $exclude = array('.' => 1, '..' => 1, 'CVS' => 1, '.svn' => 1, '.htaccess' => 1);
 978    while (($file = readdir($handle)) !== FALSE) {
 979      if (isset($exclude[$file])) {
 980        continue;
 981      }
 982  
 983      $path = $dirpath .'/'. $file;
 984  
 985      if (is_dir($path)) {
 986        $directory['subdirectories'][] = $file;
 987        continue;
 988      }
 989  
 990      $width = $height = 0;
 991      if ($img = imce_image_info($path)) {
 992        $width = $img['width'];
 993        $height = $img['height'];
 994      }
 995      $size = filesize($path);
 996      $date = filemtime($path);
 997      $directory['files'][$file] = array(
 998        'name' => $file,
 999        'size' => $size,
1000        'width' => $width,
1001        'height' => $height,
1002        'date' => $date
1003      );
1004      $directory['dirsize'] += $size;
1005    }
1006  
1007    closedir($handle);
1008    sort($directory['subdirectories']);
1009    return $directory;
1010  }
1011  
1012  /**
1013   * Create directory tree.
1014   */
1015  function imce_create_tree(&$imce) {
1016    $paths = array();
1017    //rearrange paths as arg0=>arg1=>...
1018    foreach ($imce['directories'] as $path => $arr) {
1019      $tmp =& $paths;
1020      if ($path != '.') {
1021        $args = explode('/', $path);
1022        foreach ($args as $arg) {
1023          if (!isset($tmp[$arg])) {
1024            $tmp[$arg] = array();
1025          }
1026          $tmp =& $tmp[$arg];
1027        }
1028        $tmp[':access:'] = TRUE;
1029      }
1030      if ("$path" == $imce['dir']) {
1031        $tmp[':active:'] = TRUE;
1032        foreach ($imce['subdirectories'] as $arg) {
1033          $tmp[$arg][':access:'] = TRUE;
1034        }
1035      }
1036    }
1037    //set root branch
1038    $root = theme('imce_root_text', array('imce' => &$imce));
1039    $q = $imce['clean'] ? '?' : '&';
1040    if (isset($imce['directories']['.'])) {
1041      $root = '<a href="'. $imce['url'] . $q .'dir=." title="." class="folder'. ($imce['dir'] == '.' ? ' active' : '') .'">'. $root .'</a>';
1042    }
1043    else {
1044      $root = '<a title="." class="folder disabled">'. $root .'</a>';
1045    }
1046  
1047    return $root . imce_tree_html($imce, $paths, $q);
1048  }
1049  
1050  /**
1051   * Return tree html.
1052   * This is not themable because it is complex and needs to be in a proper format for js processing.
1053   */
1054  function imce_tree_html(&$imce, $paths, $q = '?', $prefix = '', $eprefix = '') {
1055    unset($paths[':access:'], $paths[':active:']);
1056    $html = '';
1057    foreach ($paths as $arg => $children) {
1058      $path = $prefix . $arg;
1059      $earg = rawurlencode($arg);
1060      $epath = $eprefix . $earg;
1061      if (isset($children[':access:']) || imce_directory_info($path, $imce)) {
1062        $a = '<a href="'. $imce['url'] . $q .'dir='. $epath .'" title="'. $epath .'" class="folder'. (isset($children[':active:']) ? ' active' : '') .'">'. $earg .'</a>';
1063      }
1064      else {
1065        $a = '<a title="'. $epath .'" class="folder disabled">'. $earg .'</a>';
1066      }
1067      $ul = imce_tree_html($imce, $children, $q, $path .'/', $epath .'/');
1068      $class = $ul ? ' class="expanded"' : (isset($children[':active:']) ? ' class="leaf"' : '');
1069      $html .= '<li'. $class .'>'. $a . $ul .'</li>';
1070    }
1071    if ($html) {
1072      $html = '<ul>'. $html .'</ul>';
1073    }
1074    return $html;
1075  }
1076  
1077  /**
1078   * Returns the text for the root directory in a directory tree.
1079   */
1080  function theme_imce_root_text($imce_ref) {
1081    //$imce = &$imce_ref['imce'];
1082    return '&lt;' . t('root') . '&gt;';
1083  }
1084  
1085  /**
1086   * Returns the html for user's file browser tab.
1087   */
1088  function theme_imce_user_page($account) {
1089    global $user;
1090    $options = array();
1091    //switch to account's active folder
1092    if ($user->uid == 1 && $account->uid != 1) {
1093      $imce = imce_initiate_profile($account);
1094      $options['query'] = array('dir' => $imce['dir']);
1095    }
1096    return '<iframe src="' . url('imce', $options) . '" frameborder="0" style="border: 1px solid #eee; width: 99%; height: 520px" class="imce-frame"></iframe>';
1097  }
1098  
1099  /**
1100   * Registers the file as an IMCE file.
1101   */
1102  function imce_file_register($file) {
1103    return $file->fid && @db_query('INSERT INTO {imce_files} (fid) VALUES(%d)', $file->fid);
1104  }


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