upload.module 12.2 KB
Newer Older
Dries's avatar
 
Dries committed
1 2 3
<?php
/* $Id$ */

Dries's avatar
 
Dries committed
4 5 6 7 8
/**
 * @file
 * File-handling and attaching files to nodes.
 */

Dries's avatar
 
Dries committed
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
function upload_help($section) {
  switch ($section) {
    case 'admin/modules#description':
      return t('File-handling and attaching files to nodes.');
    case 'admin/upload':
      return t('Users with the <a href="%permissions"><em>upload files</em> permission</a> can upload attachments. You can choose which node types can take attachments on the <a href="%workflow">workflow settings</a> page.', array('%permissions' => url('admin/user/configure/permission'), '%workflow' => url('admin/node/configure/defaults')));
    case 'admin/node/configure/defaults':
      return t('<p>If you want users to be able to attach files to nodes, check the <em>attachments</em> column in the appropriate column.</p>');
  }
}

function upload_perm() {
  return array('upload files');
}

function upload_menu() {
  // Add handlers for previewing new uploads.
  if ($_SESSION['file_uploads']) {
    $items = array();
    foreach ($_SESSION['file_uploads'] as $key => $file) {
      $filename = file_create_filename($file->filename, file_create_path());
      $items[] = array(
        'path' => $filename, 'title' => t('file download'),
        'callback' => 'upload_download',
        'access' => true,
        'type' => MENU_DYNAMIC_ITEM & MENU_HIDDEN
      );
      $_SESSION['file_uploads'][$key]->_filename = $filename;
    }
  }
  $items[] = array(
    'path' => 'admin/upload', 'title' => t('uploads'),
    'callback' => 'upload_admin',
42
    'access' => user_access('access administration pages'),
Dries's avatar
 
Dries committed
43 44 45 46 47 48 49 50
    'type' => MENU_NORMAL_ITEM
  );
  return $items;
}

function upload_admin() {
  system_settings_save();

Dries's avatar
Dries committed
51
  $group .= form_textfield(t('Maximum total file size'), 'upload_maxsize_total', variable_get('upload_maxsize_total', 0), 5, 5, t('The maximum size of a file a user can upload in megabytes. Enter 0 for unlimited.'));
Dries's avatar
 
Dries committed
52 53 54 55 56 57

  $output = form_group(t('General settings'), $group);

  $roles = user_roles(0, 'upload files');

  foreach ($roles as $rid => $role) {
Dries's avatar
Dries committed
58 59 60 61
    $group = form_textfield(t('Permitted file extensions'), "upload_extensions_$rid", variable_get("upload_extensions_$rid", "jpg jpeg gif png txt html doc xls pdf ppt pps"), 60, 255, t('Extensions that users in this role can upload. Separate extensions with a space and do not include the leading dot.'));
    $group .= form_textfield(t('Maximum file size per upload'), "upload_uploadsize_$rid", variable_get("upload_uploadsize_$rid", 1), 5, 5, t('The maximum size of a file a user can upload (in megabytes).'));
    $group .= form_textfield(t('Total file size per user'), "upload_usersize_$rid", variable_get("upload_usersize_$rid", 10), 5, 5, t('The maximum size of all files a user can have on the site (in megabytes).'));
    $output .= form_group(t('Settings for %role', array('%role' => "<em>$role</em>")), $group);
Dries's avatar
 
Dries committed
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
  }

  print theme('page', system_settings_form($output));
}

function upload_download() {
  foreach ($_SESSION['file_uploads'] as $file) {
    if ($file->_filename == $_GET['q']) {
      file_transfer($file->filepath, array('Content-Type: '. $file->filemime, 'Content-Length: '. $file->filesize));
    }
  }
}

function upload_file_download($file) {
  $file = file_create_path($file);
  $result = db_query("SELECT * from {files} WHERE filepath = '%s'", $file);
  if ($file = db_fetch_object($result)) {
    $name = mime_header_encode($file->filename);
    // Serve images and text inline for the browser to display rather than download.
    $disposition = ereg('^(text/|image/)', $file->filemime) ? 'inline' : 'attachment';
    return array('Content-Type: '. $file->filemime .'; name='. $name,
                 'Content-Length: '. $file->filesize,
                 'Content-Disposition: '. $disposition .'; filename='. $name);
  }
}

function upload_nodeapi(&$node, $op, $arg) {
  switch ($op) {
    case 'settings':
91
      $output[t('attachments')] = form_checkbox(NULL, "upload_$node->type", 1, variable_get("upload_$node->type", 1));
Dries's avatar
 
Dries committed
92 93
      break;
    case 'form param':
94
      if (variable_get("upload_$node->type", 1) && user_access('upload files')) {
Dries's avatar
 
Dries committed
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
        $output['options'] = array('enctype' => 'multipart/form-data');
      }
      break;
    case 'validate':
      $node->files = upload_load($node);

      // Double check existing files:
      if (is_array($node->list)) {
        foreach ($node->list as $key => $value) {
          if ($file = file_check_upload($key)) {
            $node->files[$file->source] = $file;
            $node->files[$key]->list = $node->list[$key];
            $node->files[$key]->remove = $node->remove[$key];
            if ($file->source) {
              $filesize += $file->filesize;
            }
          }
        }
      }
      else {
        foreach ($node->files as $key => $file) {
          $node->list[$key] = $file->list;
        }
      }
Dries's avatar
 
Dries committed
119

120
      if (($file = file_check_upload('upload')) && user_access('upload files')) {
Dries's avatar
 
Dries committed
121 122 123 124 125 126 127 128
        global $user;

        $max_size = variable_get("upload_maxsize_total", 0);
        $total_size = upload_count_size() + $filesize;
        $total_usersize = upload_count_size($user->uid) + $filesize;


        if ($maxsize && $total_size > $maxsize) {
Dries's avatar
Dries committed
129
          form_set_error('upload', t('Error attaching file %name: total file size exceeded', array('%name' => "<em>$file->filename</em>")));
Dries's avatar
 
Dries committed
130 131 132
          break;
        }

Steven Wittens's avatar
Steven Wittens committed
133 134 135 136 137 138 139 140 141 142 143 144 145 146
        // Don't do any checks for uid #1.
        if ($user->uid != 1) {
          // Validate file against all users roles. Only denies an upload when
          // all roles prevent it.
          foreach ($user->roles as $rid => $name) {
            $extensions = variable_get("upload_extensions_$rid", 'jpg jpeg gif png txt html doc xls pdf ppt pps');
            $uploadsize = variable_get("upload_uploadsize_$rid", 1);
            $usersize = variable_get("upload_usersize_$rid", 1);

            $regex = '/\.('. ereg_replace(' +', '|', preg_quote($extensions)) .')$/i';

            if (!preg_match($regex, $file->filename)) {
              $error['extension']++;
            }
Dries's avatar
 
Dries committed
147

Steven Wittens's avatar
Steven Wittens committed
148 149 150
            if ($file->filesize > $uploadsize * 1024 * 1024) {
              $error['uploadsize']++;
            }
Dries's avatar
 
Dries committed
151

Steven Wittens's avatar
Steven Wittens committed
152 153 154
            if ($total_usersize + $file->filesize > $usersize * 1024 * 1024) {
              $error['usersize']++;
            }
Dries's avatar
 
Dries committed
155
          }
Steven Wittens's avatar
Steven Wittens committed
156
        }
Dries's avatar
 
Dries committed
157

Steven Wittens's avatar
Steven Wittens committed
158 159 160 161 162 163
        // Rename possibly executable scripts to prevent accidental execution.
        // Uploaded files are attachments and should be shown in their original
        // form, rather than run.
        if (preg_match('/\.(php|pl|py|cgi|asp)$/i', $file->filename)) {
          $file->filename .= '.txt';
          $file->filemime = 'text/plain';
Dries's avatar
 
Dries committed
164
        }
Dries's avatar
 
Dries committed
165

166
        if ($error['extension'] == count($user->roles) && $user->uid != 1) {
Dries's avatar
Dries committed
167
          form_set_error('upload', t('Error attaching file %name: invalid extension', array('%name' => "<em>$file->filename</em>")));
Dries's avatar
 
Dries committed
168
        }
169
        elseif ($error['uploadsize'] == count($user->roles) && $user->uid != 1) {
Dries's avatar
Dries committed
170
          form_set_error('upload', t('Error attaching file %name: exceeds maximum file size', array('%name' => "<em>$file->filename</em>")));
Dries's avatar
 
Dries committed
171
        }
172
        elseif ($error['usersize'] == count($user->roles) && $user->uid != 1) {
Dries's avatar
Dries committed
173
          form_set_error('upload', t('Error attaching file %name: exceeds maximum file size', array('%name' => "<em>$file->filename</em>")));
Dries's avatar
 
Dries committed
174 175 176 177 178 179 180 181 182 183 184
        }
        else {
          $key = 'upload_'. count($_SESSION['file_uploads']);
          $file->source = $key;
          $file->list = 1;
          $file = file_save_upload($file);
          $node->files[$key] = $file;
        }
      }
      break;
    case 'form post':
185
      if (variable_get("upload_$node->type", 1) == 1 && user_access('upload files')) {
Dries's avatar
 
Dries committed
186 187 188 189
        $output = upload_form($node);
      }
      break;
    case 'load':
190
      if (variable_get("upload_$node->type", 1) == 1 && user_access('upload files')) {
Steven Wittens's avatar
Steven Wittens committed
191
        $output['files'] = upload_load($node);
Dries's avatar
 
Dries committed
192 193 194 195
      }
      break;
    case 'view':
      if ($node->files) {
Dries's avatar
 
Dries committed
196
        $header = array(t('Attachment'), t('Size'));
Dries's avatar
 
Dries committed
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
        $rows = array();
        $previews = array();

        // Build list of attached files
        foreach ($node->files as $file) {
          if ($file->list) {
            $rows[] = array(
              '<a href="'. ($file->fid ? file_create_url($file->filepath) : url(file_create_filename($file->filename, file_create_path()))) . '">'. $file->filename .'</a>',
              format_size($file->filesize)
            );
            // We save the list of files still in preview for later
            if (!$file->fid) {
              $previews[] = $file;
            }
          }
        }

        // URLs to files being previewed are actually Drupal paths. When Clean
        // URLs are disabled, the two do not match. We perform an automatic
        // replacement from temporary to permanent URLs. That way, the author
        // can use the final URL in the body before having actually saved (to
        // place inline images for example).
        if (!variable_get('clean_url', 0)) {
          foreach ($previews as $file) {
            $old = file_create_filename($file->filename, file_create_path());
            $new = url($old);
            $node->body = str_replace($old, $new, $node->body);
            $node->teaser = str_replace($old, $new, $node->teaser);
          }
        }

        $teaser = $arg;
        // Add the attachments list
        if (count($rows) && !$teaser) {
          $node->body .= theme('table', $header, $rows);
        }
      }
      break;
    case 'insert':
    case 'update':
237 238 239
      if (user_access('upload files')) {
        upload_save($node);
      }
Dries's avatar
 
Dries committed
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
      break;
    case 'delete':
      upload_delete($node);
      break;
  }

  return $output;
}

function upload_count_size($uid = 0) {
  if ($uid) {
    $result = db_query("SELECT SUM(f.filesize) FROM {files} f INNER JOIN {node} n ON f.nid = n.nid WHERE uid = %d", $uid);
  }
  else {
    $result = db_query("SELECT SUM(f.filesize) FROM {files} f INNER JOIN {node} n ON f.nid = n.nid");
  }

  return db_result($result);
}

function upload_save($node) {
261
  foreach ((array)$node->files as $key => $file) {
Dries's avatar
 
Dries committed
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
    if ($file->source && !$file->remove) {
      // Insert new files:
      $fid = db_next_id('{files}_fid');
      $file = file_save_upload($file, $file->filename);

      // Clean up the session:
      unset($_SESSION['file_uploads'][$file->source]);

      db_query("INSERT INTO {files} (fid, nid, filename, filepath, filemime, filesize, list) VALUES (%d, %d, '%s', '%s', '%s', %d, %d)",
               $fid, $node->nid, $file->filename, $file->filepath, $file->filemime, $file->filesize, $node->list[$key]);
    }
    else {
      // Remove or update existing files:
      if ($node->remove[$key]) {
        file_delete($file->filepath);
        db_query("DELETE FROM {files} WHERE fid = %d", $key);
      }
      if ($file->list != $node->list[$key]) {
        db_query("UPDATE {files} SET list = %d WHERE fid = %d", $node->list[$key], $key);
      }
    }
  }
  return;
}

function upload_delete($node) {
  $node->files = upload_load($node);
  foreach ($node->files as $file) {
    file_delete($file->filepath);
  }
  db_query("DELETE FROM {files} WHERE nid = %d", $node->nid);
}

function upload_form($node) {
Dries's avatar
 
Dries committed
296
  $header = array(t('Delete'), t('List'), t('Url'), t('Size'));
Dries's avatar
 
Dries committed
297 298 299 300 301 302 303 304 305 306 307 308 309 310
  $rows = array();

  if (is_array($node->files)) {
    foreach ($node->files as $key => $file) {
      $rows[] = array(
        form_checkbox('', "remove][$key", 1, $file->remove),
        form_checkbox('', "list][$key", 1, $file->list),
        $file->filename ."<br /><small>". file_create_url(($file->fid ? $file->filepath : file_create_filename($file->filename, file_create_path()))) ."</small>",
        format_size($file->filesize)
      );
    }
  }

  if (count($node->files)) {
Dries's avatar
 
Dries committed
311
    $output = form_item('', theme('table', $header, $rows), t('Note: changes made to the attachments are not permanent until you save this post.'));
Dries's avatar
 
Dries committed
312
  }
313 314 315 316
  if (user_access('upload files')) {
    $output .= form_file(t('Attach new file'), "upload", 40);
    $output .= form_button(t('Attach'), 'fileop');
  }
Dries's avatar
 
Dries committed
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334

  return '<div class="attachments">'. form_group(t('Attachments'), $output) . '</div>';
}

function upload_load($node) {
  $files = array();

  if ($node->nid) {
    $result = db_query("SELECT * FROM {files} WHERE nid = %d", $node->nid);
    while ($file = db_fetch_object($result)) {
      $files[$file->fid] = $file;
    }
  }

  return $files;
}

?>