web/drupal/modules/upload/upload.module
branchdrupal
changeset 74 0ff3ba646492
equal deleted inserted replaced
73:fcf75e232c5b 74:0ff3ba646492
       
     1 <?php
       
     2 // $Id: upload.module,v 1.197.2.4 2009/01/12 15:30:23 goba Exp $
       
     3 
       
     4 /**
       
     5  * @file
       
     6  * File-handling and attaching files to nodes.
       
     7  *
       
     8  */
       
     9 
       
    10 /**
       
    11  * Implementation of hook_help().
       
    12  */
       
    13 function upload_help($path, $arg) {
       
    14   switch ($path) {
       
    15     case 'admin/help#upload':
       
    16       $output = '<p>'. t('The upload module allows users to upload files to the site. The ability to upload files is important for members of a community who want to share work. It is also useful to administrators who want to keep uploaded files connected to posts.') .'</p>';
       
    17       $output .= '<p>'. t('Users with the upload files permission can upload attachments to posts. Uploads may be enabled for specific content types on the content types settings page. Each user role can be customized to limit or control the file size of uploads, or the maximum dimension of image files.') .'</p>';
       
    18       $output .= '<p>'. t('For more information, see the online handbook entry for <a href="@upload">Upload module</a>.', array('@upload' => 'http://drupal.org/handbook/modules/upload/')) .'</p>';
       
    19       return $output;
       
    20     case 'admin/settings/upload':
       
    21       return '<p>'. t('Users with the <a href="@permissions">upload files permission</a> can upload attachments. Users with the <a href="@permissions">view uploaded files permission</a> can view uploaded attachments. You can choose which post types can take attachments on the <a href="@types">content types settings</a> page.', array('@permissions' => url('admin/user/permissions'), '@types' => url('admin/settings/types'))) .'</p>';
       
    22   }
       
    23 }
       
    24 
       
    25 /**
       
    26  * Implementation of hook_theme()
       
    27  */
       
    28 function upload_theme() {
       
    29   return array(
       
    30     'upload_attachments' => array(
       
    31       'arguments' => array('files' => NULL),
       
    32     ),
       
    33     'upload_form_current' => array(
       
    34       'arguments' => array('form' => NULL),
       
    35     ),
       
    36     'upload_form_new' => array(
       
    37       'arguments' => array('form' => NULL),
       
    38     ),
       
    39   );
       
    40 }
       
    41 
       
    42 /**
       
    43  * Implementation of hook_perm().
       
    44  */
       
    45 function upload_perm() {
       
    46   return array('upload files', 'view uploaded files');
       
    47 }
       
    48 
       
    49 /**
       
    50  * Implementation of hook_link().
       
    51  */
       
    52 function upload_link($type, $node = NULL, $teaser = FALSE) {
       
    53   $links = array();
       
    54 
       
    55   // Display a link with the number of attachments
       
    56   if ($teaser && $type == 'node' && isset($node->files) && user_access('view uploaded files')) {
       
    57     $num_files = 0;
       
    58     foreach ($node->files as $file) {
       
    59       if ($file->list) {
       
    60         $num_files++;
       
    61       }
       
    62     }
       
    63     if ($num_files) {
       
    64       $links['upload_attachments'] = array(
       
    65         'title' => format_plural($num_files, '1 attachment', '@count attachments'),
       
    66         'href' => "node/$node->nid",
       
    67         'attributes' => array('title' => t('Read full article to view attachments.')),
       
    68         'fragment' => 'attachments'
       
    69       );
       
    70     }
       
    71   }
       
    72 
       
    73   return $links;
       
    74 }
       
    75 
       
    76 /**
       
    77  * Implementation of hook_menu().
       
    78  */
       
    79 function upload_menu() {
       
    80   $items['upload/js'] = array(
       
    81     'page callback' => 'upload_js',
       
    82     'access arguments' => array('upload files'),
       
    83     'type' => MENU_CALLBACK,
       
    84   );
       
    85   $items['admin/settings/uploads'] = array(
       
    86     'title' => 'File uploads',
       
    87     'description' => 'Control how files may be attached to content.',
       
    88     'page callback' => 'drupal_get_form',
       
    89     'page arguments' => array('upload_admin_settings'),
       
    90     'access arguments' => array('administer site configuration'),
       
    91     'type' => MENU_NORMAL_ITEM,
       
    92     'file' => 'upload.admin.inc',
       
    93   );
       
    94   return $items;
       
    95 }
       
    96 
       
    97 function upload_menu_alter(&$items) {
       
    98   $items['system/files']['access arguments'] = array('view uploaded files');
       
    99 }
       
   100 
       
   101 /**
       
   102  * Determine the limitations on files that a given user may upload. The user
       
   103  * may be in multiple roles so we select the most permissive limitations from
       
   104  * all of their roles.
       
   105  *
       
   106  * @param $user
       
   107  *   A Drupal user object.
       
   108  * @return
       
   109  *   An associative array with the following keys:
       
   110  *     'extensions'
       
   111  *       A white space separated string containing all the file extensions this
       
   112  *       user may upload.
       
   113  *     'file_size'
       
   114  *       The maximum size of a file upload in bytes.
       
   115  *     'user_size'
       
   116  *       The total number of bytes for all for a user's files.
       
   117  *     'resolution'
       
   118  *       A string specifying the maximum resolution of images.
       
   119  */
       
   120 function _upload_file_limits($user) {
       
   121   $file_limit = variable_get('upload_uploadsize_default', 1);
       
   122   $user_limit = variable_get('upload_usersize_default', 1);
       
   123   $all_extensions = explode(' ', variable_get('upload_extensions_default', 'jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp'));
       
   124   foreach ($user->roles as $rid => $name) {
       
   125     $extensions = variable_get("upload_extensions_$rid", variable_get('upload_extensions_default', 'jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp'));
       
   126     $all_extensions = array_merge($all_extensions, explode(' ', $extensions));
       
   127 
       
   128     // A zero value indicates no limit, take the least restrictive limit.
       
   129     $file_size = variable_get("upload_uploadsize_$rid", variable_get('upload_uploadsize_default', 1)) * 1024 * 1024;
       
   130     $file_limit = ($file_limit && $file_size) ? max($file_limit, $file_size) : 0;
       
   131 
       
   132     $user_size = variable_get("upload_usersize_$rid", variable_get('upload_usersize_default', 1)) * 1024 * 1024;
       
   133     $user_limit = ($user_limit && $user_size) ? max($user_limit, $user_size) : 0;
       
   134   }
       
   135   $all_extensions = implode(' ', array_unique($all_extensions));
       
   136   return array(
       
   137     'extensions' => $all_extensions,
       
   138     'file_size' => $file_limit,
       
   139     'user_size' => $user_limit,
       
   140     'resolution' => variable_get('upload_max_resolution', 0),
       
   141   );
       
   142 }
       
   143 
       
   144 /**
       
   145  * Implementation of hook_file_download().
       
   146  */
       
   147 function upload_file_download($filepath) {
       
   148   $filepath = file_create_path($filepath);
       
   149   $result = db_query("SELECT f.*, u.nid FROM {files} f INNER JOIN {upload} u ON f.fid = u.fid WHERE filepath = '%s'", $filepath);
       
   150   if ($file = db_fetch_object($result)) {
       
   151     if (user_access('view uploaded files') && ($node = node_load($file->nid)) && node_access('view', $node)) {
       
   152       return array(
       
   153         'Content-Type: ' . $file->filemime,
       
   154         'Content-Length: ' . $file->filesize,
       
   155       );
       
   156     }
       
   157     else {
       
   158       return -1;
       
   159     }
       
   160   }
       
   161 }
       
   162 
       
   163 /**
       
   164  * Save new uploads and store them in the session to be associated to the node
       
   165  * on upload_save.
       
   166  *
       
   167  * @param $node
       
   168  *   A node object to associate with uploaded files.
       
   169  */
       
   170 function upload_node_form_submit(&$form, &$form_state) {
       
   171   global $user;
       
   172 
       
   173   $limits = _upload_file_limits($user);
       
   174   $validators = array(
       
   175     'file_validate_extensions' => array($limits['extensions']),
       
   176     'file_validate_image_resolution' => array($limits['resolution']),
       
   177     'file_validate_size' => array($limits['file_size'], $limits['user_size']),
       
   178   );
       
   179 
       
   180   // Save new file uploads.
       
   181   if (user_access('upload files') && ($file = file_save_upload('upload', $validators, file_directory_path()))) {
       
   182     $file->list = variable_get('upload_list_default', 1);
       
   183     $file->description = $file->filename;
       
   184     $file->weight = 0;
       
   185     $file->new = TRUE;
       
   186     $form['#node']->files[$file->fid] = $file;
       
   187     $form_state['values']['files'][$file->fid] = (array)$file;
       
   188   }
       
   189 
       
   190   if (isset($form_state['values']['files'])) {
       
   191     foreach ($form_state['values']['files'] as $fid => $file) {
       
   192       $form_state['values']['files'][$fid]['new'] = !empty($form['#node']->files[$fid]->new);
       
   193     }
       
   194   }
       
   195 
       
   196   // Order the form according to the set file weight values.
       
   197   if (!empty($form_state['values']['files'])) {
       
   198     $microweight = 0.001;
       
   199     foreach ($form_state['values']['files'] as $fid => $file) {
       
   200       if (is_numeric($fid)) {
       
   201         $form_state['values']['files'][$fid]['#weight'] = $file['weight'] + $microweight;
       
   202         $microweight += 0.001;
       
   203       }
       
   204     }
       
   205     uasort($form_state['values']['files'], 'element_sort');
       
   206   }
       
   207 }
       
   208 
       
   209 function upload_form_alter(&$form, $form_state, $form_id) {
       
   210   if ($form_id == 'node_type_form' && isset($form['identity']['type'])) {
       
   211     $form['workflow']['upload'] = array(
       
   212       '#type' => 'radios',
       
   213       '#title' => t('Attachments'),
       
   214       '#default_value' => variable_get('upload_'. $form['#node_type']->type, 1),
       
   215       '#options' => array(t('Disabled'), t('Enabled')),
       
   216     );
       
   217   }
       
   218 
       
   219   if (isset($form['type']) && isset($form['#node'])) {
       
   220     $node = $form['#node'];
       
   221     if ($form['type']['#value'] .'_node_form' == $form_id && variable_get("upload_$node->type", TRUE)) {
       
   222       // Attachments fieldset
       
   223       $form['attachments'] = array(
       
   224         '#type' => 'fieldset',
       
   225         '#access' => user_access('upload files'),
       
   226         '#title' => t('File attachments'),
       
   227         '#collapsible' => TRUE,
       
   228         '#collapsed' => empty($node->files),
       
   229         '#description' => t('Changes made to the attachments are not permanent until you save this post. The first "listed" file will be included in RSS feeds.'),
       
   230         '#prefix' => '<div class="attachments">',
       
   231         '#suffix' => '</div>',
       
   232         '#weight' => 30,
       
   233       );
       
   234 
       
   235       // Wrapper for fieldset contents (used by ahah.js).
       
   236       $form['attachments']['wrapper'] = array(
       
   237         '#prefix' => '<div id="attach-wrapper">',
       
   238         '#suffix' => '</div>',
       
   239       );
       
   240 
       
   241       // Make sure necessary directories for upload.module exist and are
       
   242       // writable before displaying the attachment form.
       
   243       $path = file_directory_path();
       
   244       $temp = file_directory_temp();
       
   245       // Note: pass by reference
       
   246       if (!file_check_directory($path, FILE_CREATE_DIRECTORY) || !file_check_directory($temp, FILE_CREATE_DIRECTORY)) {
       
   247         $form['attachments']['#description'] =  t('File attachments are disabled. The file directories have not been properly configured.');
       
   248         if (user_access('administer site configuration')) {
       
   249           $form['attachments']['#description'] .= ' '. t('Please visit the <a href="@admin-file-system">file system configuration page</a>.', array('@admin-file-system' => url('admin/settings/file-system')));
       
   250         }
       
   251         else {
       
   252           $form['attachments']['#description'] .= ' '. t('Please contact the site administrator.');
       
   253         }
       
   254       }
       
   255       else {
       
   256         $form['attachments']['wrapper'] += _upload_form($node);
       
   257         $form['#attributes']['enctype'] = 'multipart/form-data';
       
   258       }
       
   259       $form['#submit'][] = 'upload_node_form_submit';
       
   260     }
       
   261   }
       
   262 }
       
   263 
       
   264 /**
       
   265  * Implementation of hook_nodeapi().
       
   266  */
       
   267 function upload_nodeapi(&$node, $op, $teaser) {
       
   268   switch ($op) {
       
   269 
       
   270     case 'load':
       
   271       $output = '';
       
   272       if (variable_get("upload_$node->type", 1) == 1) {
       
   273         $output['files'] = upload_load($node);
       
   274         return $output;
       
   275       }
       
   276       break;
       
   277 
       
   278     case 'view':
       
   279       if (isset($node->files) && user_access('view uploaded files')) {
       
   280         // Add the attachments list to node body with a heavy
       
   281         // weight to ensure they're below other elements
       
   282         if (count($node->files)) {
       
   283           if (!$teaser && user_access('view uploaded files')) {
       
   284             $node->content['files'] = array(
       
   285               '#value' => theme('upload_attachments', $node->files),
       
   286               '#weight' => 50,
       
   287             );
       
   288           }
       
   289         }
       
   290       }
       
   291       break;
       
   292 
       
   293     case 'insert':
       
   294     case 'update':
       
   295       if (user_access('upload files')) {
       
   296         upload_save($node);
       
   297       }
       
   298       break;
       
   299 
       
   300     case 'delete':
       
   301       upload_delete($node);
       
   302       break;
       
   303 
       
   304     case 'delete revision':
       
   305       upload_delete_revision($node);
       
   306       break;
       
   307 
       
   308     case 'search result':
       
   309       return isset($node->files) && is_array($node->files) ? format_plural(count($node->files), '1 attachment', '@count attachments') : NULL;
       
   310 
       
   311     case 'rss item':
       
   312       if (is_array($node->files)) {
       
   313         $files = array();
       
   314         foreach ($node->files as $file) {
       
   315           if ($file->list) {
       
   316             $files[] = $file;
       
   317           }
       
   318         }
       
   319         if (count($files) > 0) {
       
   320           // RSS only allows one enclosure per item
       
   321           $file = array_shift($files);
       
   322           return array(
       
   323             array(
       
   324               'key' => 'enclosure',
       
   325               'attributes' => array(
       
   326                 'url' => file_create_url($file->filepath),
       
   327                 'length' => $file->filesize,
       
   328                 'type' => $file->filemime
       
   329               )
       
   330             )
       
   331           );
       
   332         }
       
   333       }
       
   334       return array();
       
   335   }
       
   336 }
       
   337 
       
   338 /**
       
   339  * Displays file attachments in table
       
   340  *
       
   341  * @ingroup themeable
       
   342  */
       
   343 function theme_upload_attachments($files) {
       
   344   $header = array(t('Attachment'), t('Size'));
       
   345   $rows = array();
       
   346   foreach ($files as $file) {
       
   347     $file = (object)$file;
       
   348     if ($file->list && empty($file->remove)) {
       
   349       $href = file_create_url($file->filepath);
       
   350       $text = $file->description ? $file->description : $file->filename;
       
   351       $rows[] = array(l($text, $href), format_size($file->filesize));
       
   352     }
       
   353   }
       
   354   if (count($rows)) {
       
   355     return theme('table', $header, $rows, array('id' => 'attachments'));
       
   356   }
       
   357 }
       
   358 
       
   359 /**
       
   360  * Determine how much disk space is occupied by a user's uploaded files.
       
   361  *
       
   362  * @param $uid
       
   363  *   The integer user id of a user.
       
   364  * @return
       
   365  *   The amount of disk space used by the user in bytes.
       
   366  */
       
   367 function upload_space_used($uid) {
       
   368   return file_space_used($uid);
       
   369 }
       
   370 
       
   371 /**
       
   372  * Determine how much disk space is occupied by uploaded files.
       
   373  *
       
   374  * @return
       
   375  *   The amount of disk space used by uploaded files in bytes.
       
   376  */
       
   377 function upload_total_space_used() {
       
   378   return db_result(db_query('SELECT SUM(f.filesize) FROM {files} f INNER JOIN {upload} u ON f.fid = u.fid'));
       
   379 }
       
   380 
       
   381 function upload_save(&$node) {
       
   382   if (empty($node->files) || !is_array($node->files)) {
       
   383     return;
       
   384   }
       
   385 
       
   386   foreach ($node->files as $fid => $file) {
       
   387     // Convert file to object for compatibility
       
   388     $file = (object)$file;
       
   389 
       
   390     // Remove file. Process removals first since no further processing
       
   391     // will be required.
       
   392     if (!empty($file->remove)) {
       
   393       db_query('DELETE FROM {upload} WHERE fid = %d AND vid = %d', $fid, $node->vid);
       
   394 
       
   395       // If the file isn't used by any other revisions delete it.
       
   396       $count = db_result(db_query('SELECT COUNT(fid) FROM {upload} WHERE fid = %d', $fid));
       
   397       if ($count < 1) {
       
   398         file_delete($file->filepath);
       
   399         db_query('DELETE FROM {files} WHERE fid = %d', $fid);
       
   400       }
       
   401 
       
   402       // Remove it from the session in the case of new uploads,
       
   403       // that you want to disassociate before node submission.
       
   404       unset($node->files[$fid]);
       
   405       // Move on, so the removed file won't be added to new revisions.
       
   406       continue;
       
   407     }
       
   408 
       
   409     // Create a new revision, or associate a new file needed.
       
   410     if (!empty($node->old_vid) || $file->new) {
       
   411       db_query("INSERT INTO {upload} (fid, nid, vid, list, description, weight) VALUES (%d, %d, %d, %d, '%s', %d)", $file->fid, $node->nid, $node->vid, $file->list, $file->description, $file->weight);
       
   412       file_set_status($file, FILE_STATUS_PERMANENT);
       
   413     }
       
   414     // Update existing revision.
       
   415     else {
       
   416       db_query("UPDATE {upload} SET list = %d, description = '%s', weight = %d WHERE fid = %d AND vid = %d", $file->list, $file->description, $file->weight, $file->fid, $node->vid);
       
   417       file_set_status($file, FILE_STATUS_PERMANENT);
       
   418     }
       
   419   }
       
   420 }
       
   421 
       
   422 function upload_delete($node) {
       
   423   $files = array();
       
   424   $result = db_query('SELECT DISTINCT f.* FROM {upload} u INNER JOIN {files} f ON u.fid = f.fid WHERE u.nid = %d', $node->nid);
       
   425   while ($file = db_fetch_object($result)) {
       
   426     $files[$file->fid] = $file;
       
   427   }
       
   428 
       
   429   foreach ($files as $fid => $file) {
       
   430     // Delete all files associated with the node
       
   431     db_query('DELETE FROM {files} WHERE fid = %d', $fid);
       
   432     file_delete($file->filepath);
       
   433   }
       
   434 
       
   435   // Delete all file revision information associated with the node
       
   436   db_query('DELETE FROM {upload} WHERE nid = %d', $node->nid);
       
   437 }
       
   438 
       
   439 function upload_delete_revision($node) {
       
   440   if (is_array($node->files)) {
       
   441     foreach ($node->files as $file) {
       
   442       // Check if the file will be used after this revision is deleted
       
   443       $count = db_result(db_query('SELECT COUNT(fid) FROM {upload} WHERE fid = %d', $file->fid));
       
   444 
       
   445       // if the file won't be used, delete it
       
   446       if ($count < 2) {
       
   447         db_query('DELETE FROM {files} WHERE fid = %d', $file->fid);
       
   448         file_delete($file->filepath);
       
   449       }
       
   450     }
       
   451   }
       
   452 
       
   453   // delete the revision
       
   454   db_query('DELETE FROM {upload} WHERE vid = %d', $node->vid);
       
   455 }
       
   456 
       
   457 function _upload_form($node) {
       
   458   global $user;
       
   459 
       
   460   $form = array(
       
   461     '#theme' => 'upload_form_new',
       
   462     '#cache' => TRUE,
       
   463   );
       
   464 
       
   465   if (!empty($node->files) && is_array($node->files)) {
       
   466     $form['files']['#theme'] = 'upload_form_current';
       
   467     $form['files']['#tree'] = TRUE;
       
   468     foreach ($node->files as $key => $file) {
       
   469       $file = (object)$file;
       
   470       $description = file_create_url($file->filepath);
       
   471       $description = "<small>". check_plain($description) ."</small>";
       
   472       $form['files'][$key]['description'] = array('#type' => 'textfield', '#default_value' => !empty($file->description) ? $file->description : $file->filename, '#maxlength' => 256, '#description' => $description );
       
   473       $form['files'][$key]['size'] = array('#value' => format_size($file->filesize));
       
   474       $form['files'][$key]['remove'] = array('#type' => 'checkbox', '#default_value' => !empty($file->remove));
       
   475       $form['files'][$key]['list'] = array('#type' => 'checkbox',  '#default_value' => $file->list);
       
   476       $form['files'][$key]['weight'] = array('#type' => 'weight', '#delta' => count($node->files), '#default_value' => $file->weight);
       
   477       $form['files'][$key]['filename'] = array('#type' => 'value',  '#value' => $file->filename);
       
   478       $form['files'][$key]['filepath'] = array('#type' => 'value',  '#value' => $file->filepath);
       
   479       $form['files'][$key]['filemime'] = array('#type' => 'value',  '#value' => $file->filemime);
       
   480       $form['files'][$key]['filesize'] = array('#type' => 'value',  '#value' => $file->filesize);
       
   481       $form['files'][$key]['fid'] = array('#type' => 'value',  '#value' => $file->fid);
       
   482       $form['files'][$key]['new'] = array('#type' => 'value', '#value' => FALSE);
       
   483     }
       
   484   }
       
   485 
       
   486   if (user_access('upload files')) {
       
   487     $limits = _upload_file_limits($user);
       
   488     $form['new']['#weight'] = 10;
       
   489     $form['new']['upload'] = array(
       
   490       '#type' => 'file',
       
   491       '#title' => t('Attach new file'),
       
   492       '#size' => 40,
       
   493       '#description' => ($limits['resolution'] ? t('Images are larger than %resolution will be resized. ', array('%resolution' => $limits['resolution'])) : '') . t('The maximum upload size is %filesize. Only files with the following extensions may be uploaded: %extensions. ', array('%extensions' => $limits['extensions'], '%filesize' => format_size($limits['file_size']))),
       
   494     );
       
   495     $form['new']['attach'] = array(
       
   496       '#type' => 'submit',
       
   497       '#value' => t('Attach'),
       
   498       '#name' => 'attach',
       
   499       '#ahah' => array(
       
   500         'path' => 'upload/js',
       
   501         'wrapper' => 'attach-wrapper',
       
   502         'progress' => array('type' => 'bar', 'message' => t('Please wait...')),
       
   503       ),
       
   504       '#submit' => array('node_form_submit_build_node'),
       
   505     );
       
   506   }
       
   507 
       
   508   return $form;
       
   509 }
       
   510 
       
   511 /**
       
   512  * Theme the attachments list.
       
   513  *
       
   514  * @ingroup themeable
       
   515  */
       
   516 function theme_upload_form_current(&$form) {
       
   517   $header = array('', t('Delete'), t('List'), t('Description'), t('Weight'), t('Size'));
       
   518   drupal_add_tabledrag('upload-attachments', 'order', 'sibling', 'upload-weight');
       
   519 
       
   520   foreach (element_children($form) as $key) {
       
   521     // Add class to group weight fields for drag and drop.
       
   522     $form[$key]['weight']['#attributes']['class'] = 'upload-weight';
       
   523 
       
   524     $row = array('');
       
   525     $row[] = drupal_render($form[$key]['remove']);
       
   526     $row[] = drupal_render($form[$key]['list']);
       
   527     $row[] = drupal_render($form[$key]['description']);
       
   528     $row[] = drupal_render($form[$key]['weight']);
       
   529     $row[] = drupal_render($form[$key]['size']);
       
   530     $rows[] = array('data' => $row, 'class' => 'draggable');
       
   531   }
       
   532   $output = theme('table', $header, $rows, array('id' => 'upload-attachments'));
       
   533   $output .= drupal_render($form);
       
   534   return $output;
       
   535 }
       
   536 
       
   537 /**
       
   538  * Theme the attachment form.
       
   539  * Note: required to output prefix/suffix.
       
   540  *
       
   541  * @ingroup themeable
       
   542  */
       
   543 function theme_upload_form_new($form) {
       
   544   drupal_add_tabledrag('upload-attachments', 'order', 'sibling', 'upload-weight');
       
   545   $output = drupal_render($form);
       
   546   return $output;
       
   547 }
       
   548 
       
   549 function upload_load($node) {
       
   550   $files = array();
       
   551 
       
   552   if ($node->vid) {
       
   553     $result = db_query('SELECT * FROM {files} f INNER JOIN {upload} r ON f.fid = r.fid WHERE r.vid = %d ORDER BY r.weight, f.fid', $node->vid);
       
   554     while ($file = db_fetch_object($result)) {
       
   555       $files[$file->fid] = $file;
       
   556     }
       
   557   }
       
   558 
       
   559   return $files;
       
   560 }
       
   561 
       
   562 /**
       
   563  * Menu-callback for JavaScript-based uploads.
       
   564  */
       
   565 function upload_js() {
       
   566   $cached_form_state = array();
       
   567   $files = array();
       
   568 
       
   569   // Load the form from the Form API cache.
       
   570   if (!($cached_form = form_get_cache($_POST['form_build_id'], $cached_form_state)) || !isset($cached_form['#node']) || !isset($cached_form['attachments'])) {
       
   571     form_set_error('form_token', t('Validation error, please try again. If this error persists, please contact the site administrator.'));
       
   572     $output = theme('status_messages');
       
   573     print drupal_to_js(array('status' => TRUE, 'data' => $output));
       
   574     exit();
       
   575   }
       
   576 
       
   577   $form_state = array('values' => $_POST);
       
   578 
       
   579   // Handle new uploads, and merge tmp files into node-files.
       
   580   upload_node_form_submit($cached_form, $form_state);
       
   581 
       
   582   if(!empty($form_state['values']['files'])) {
       
   583     foreach ($form_state['values']['files'] as $fid => $file) {
       
   584       if (isset($cached_form['#node']->files[$fid])) {
       
   585         $files[$fid] = $cached_form['#node']->files[$fid];
       
   586       }
       
   587     }
       
   588   }
       
   589 
       
   590   $node = $cached_form['#node'];
       
   591 
       
   592   $node->files = $files;
       
   593 
       
   594   $form = _upload_form($node);
       
   595 
       
   596   unset($cached_form['attachments']['wrapper']['new']);
       
   597   $cached_form['attachments']['wrapper'] = array_merge($cached_form['attachments']['wrapper'], $form);
       
   598 
       
   599   $cached_form['attachments']['#collapsed'] = FALSE;
       
   600 
       
   601   form_set_cache($_POST['form_build_id'], $cached_form, $cached_form_state);
       
   602 
       
   603   foreach ($files as $fid => $file) {
       
   604     if (is_numeric($fid)) {
       
   605       $form['files'][$fid]['description']['#default_value'] = $form_state['values']['files'][$fid]['description'];
       
   606       $form['files'][$fid]['list']['#default_value'] = !empty($form_state['values']['files'][$fid]['list']);
       
   607       $form['files'][$fid]['remove']['#default_value'] = !empty($form_state['values']['files'][$fid]['remove']);
       
   608       $form['files'][$fid]['weight']['#default_value'] = $form_state['values']['files'][$fid]['weight'];
       
   609     }
       
   610   }
       
   611 
       
   612   // Render the form for output.
       
   613   $form += array(
       
   614     '#post' => $_POST,
       
   615     '#programmed' => FALSE,
       
   616     '#tree' => FALSE,
       
   617     '#parents' => array(),
       
   618   );
       
   619   drupal_alter('form', $form, array(), 'upload_js');
       
   620   $form_state = array('submitted' => FALSE);
       
   621   $form = form_builder('upload_js', $form, $form_state);
       
   622   $output = theme('status_messages') . drupal_render($form);
       
   623 
       
   624   // We send the updated file attachments form.
       
   625   // Don't call drupal_json(). ahah.js uses an iframe and
       
   626   // the header output by drupal_json() causes problems in some browsers.
       
   627   print drupal_to_js(array('status' => TRUE, 'data' => $output));
       
   628   exit;
       
   629 }