[ Index ]

PHP Cross Reference of Drupal 6 (yi-drupal)

title

Body

[close]

/sites/all/modules/image_fupload/image_fupload_imagefield/ -> image_fupload_imagefield.module (source)

   1  <?php
   2  // $Id: image_fupload_imagefield.module,v 1.33 2009/04/08 12:44:42 grandcat Exp $
   3  
   4  /**
   5   * Implementation of hook_help
   6   */
   7  function image_fupload_imagefield_help($path, $arg) {
   8  // will come later...
   9  }
  10  
  11  /**
  12   * Implementation of hook_menu().
  13   */
  14  function image_fupload_imagefield_menu() {
  15    $items['fupload/js/imagefield'] = array(
  16      'title' => 'Image FUpload',
  17      'page callback' => 'image_fupload_imagefield_node_create',
  18      'access arguments' => array('mass upload images'),
  19      'type' => MENU_CALLBACK,
  20      'file' => 'field_file.inc',
  21      'file path' => drupal_get_path('module', 'filefield'),
  22    );  
  23    return $items;  
  24  }
  25  
  26  function image_fupload_imagefield_theme() {  
  27    return array(
  28      // imagefield_widget form element type theme function.
  29      'image_fupload_imagefield_widget' => array(
  30        'arguments' => array('element' => null),
  31        'file' => 'image_fupload_imagefield_widget.inc',
  32      ),
  33      // theme an imagefield field item. It calls imagefied_image with the proper item properties as arguments.
  34      'image_fupload_imagefield_item' => array(
  35        'arguments' => array('item' => null),
  36      ),
  37      // use to generate a preview (admin view) of an imagefield item for use in field item forms
  38      // and filefield widgets. It is invoked by filefield_widget_process.
  39      'image_fupload_imagefield_widget_preview' => array(
  40        'arguments' => array('item' => null),
  41      ),
  42      // theme function for the field item elements. allows you to place children within the context
  43      // of the parent.
  44      'image_fupload_imagefield_widget_item' => array(
  45        'arguments' => array('element' => null),
  46      ),
  47    );
  48  }
  49  
  50  /**
  51   * Implementation of hook_form_alter() registry.
  52   **/
  53  function image_fupload_imagefield_form_alter(&$form, $form_state, $form_id) {
  54    global $user;  
  55    // load available image node types & field information
  56    $image_node_types = variable_get('image_node_types', array());
  57    $node_type = substr($form_id, 0, (strlen($form_id) - 10)); // get node type  
  58    
  59    // examine whether this node type is configured as image fupload handler (basic check = performance)
  60    if (image_node_type_load($node_type, TRUE)) {
  61      // get field information
  62      $field_name = $image_node_types[$node_type]['fieldname'];
  63      $field = content_fields($field_name, $node_type);
  64      // check whether image fupload widget is still chosen as widget and permission things
  65      if ($field['widget']['type'] == "image_fupload_imagefield_widget" && arg(3) != "noflash" && arg(3) != "list_imagefields" && user_access('mass upload images')) {
  66        // load needed JS & CSS - Files
  67        $module_path = drupal_get_path('module', 'image_fupload');
  68        drupal_add_js($module_path .'/swfupload/swfupload.js', 'module');
  69        drupal_add_js($module_path .'/swfupload/swfupload.queue.js', 'module');
  70        drupal_add_js($module_path .'/swfupload/fileprogress.js', 'module');
  71        drupal_add_js($module_path .'/swfupload/handlers.js', 'module');
  72        
  73        // provide a link for further steps (preview list with editing) if permitted
  74        $redirect_url = '';
  75        if (user_access('edit captions')) {
  76          $redirect_url = url('node/add/' .str_replace("_", "-", $node_type) .'/list_imagefields');
  77        }
  78        
  79        // number of images allowed to be uploaded
  80        switch ($field['multiple']) {
  81          case "1":
  82            $upload_limit_count = 100; // unlimited
  83            break;
  84          case "0":
  85            $upload_limit_count = 1;
  86            break;
  87          default:
  88            $upload_limit_count = $field['multiple'];
  89        }
  90        // don't observe number of fields in single storage mode
  91        if ($field['widget']['fupload_mode'] == "single")
  92          $upload_limit_count = 100; // unlimited
  93        
  94        $fupload_widget_weight = $field['widget']['weight'];
  95        $file_max_size = parse_size($field['widget']['max_filesize_per_file']); // maximal allowed file size (bytes)  
  96        drupal_add_js(theme('swfupload_settings', base_path() . $module_path, url('fupload/flash'), round($file_max_size/1024), ("*." .str_replace(" ", "; *.", $field['widget']['file_extensions'])), (!empty($user->sid) ? $user->sid : session_id()), $upload_limit_count, $node_type, $field_name, (!empty($field['required']) ? "true" : "false"), $field['widget']['fupload_mode'], $redirect_url), 'inline');
  97        drupal_add_css($module_path .'/image_fupload-style.css', 'module', 'all', FALSE);
  98        
  99        // unvisible elements, will be written in cache
 100        $form['node_type'] = array('#type' => 'value', '#value' => $node_type);
 101        $form['field_name'] = array('#type' => 'value', '#value' => $field_name);
 102        
 103        // is it a new node?
 104        if (!isset($form['#node']->nid)) {
 105          // new node; remove our imagefield and its validation, also in cache
 106          unset($form[$field_name], $form['#field_info'][$field_name], $form['#validate'][array_search('filefield_node_form_validate', $form['#validate'])]);
 107          // hide submit button; will be clicked via JS if needed
 108          $form['buttons']['submit']['#attributes'] = array('style' => 'display:none;');
 109          
 110          // we have to split up storage modes
 111          if ($field['widget']['fupload_mode'] == "single") {
 112            // one node per image - mode 
 113            
 114            if (user_access('edit captions')) { // user allowed to use preview list?
 115              // delete fields which will be shown later in preview list; cache this
 116              form_fields_destroy($form, $field['widget']['fupload_previewlist_field_settings']);
 117              form_set_cache($form['form_build_id'], $form, $form_state); // save changed data in cache, include removed fields for image preview list --> no validation
 118              unset($form['buttons']['preview']);
 119            } else {
 120              // basic form manipulations (normal mode)
 121              unset($form['title']);
 122              form_set_cache($form['form_build_id'], $form, $form_state); // save data in cache, don't include some unsets
 123              unset($form['buttons']['preview']); // only make them unvisible            
 124            }            
 125            
 126          } else {
 127            // multiple images per node - mode ...puhh...
 128            if (user_access('edit captions')) { // user allowed to use preview list?
 129              // delete fields which will be shown later in preview list; cache this
 130              form_fields_destroy($form, $field['widget']['fupload_previewlist_field_settings']);
 131              form_set_cache($form['form_build_id'], $form, $form_state); // save changed data in cache, include removed fields for image preview list --> no validation
 132              unset($form['buttons']['preview']);
 133            } else {
 134              // basic form manipulations (normal mode)
 135              form_set_cache($form['form_build_id'], $form, $form_state); // save data in cache, don't include some unsets
 136              unset($form['buttons']['preview']); // only make them unvisible            
 137            }
 138          }
 139          
 140        } else {
 141          // edit already existing node
 142          
 143          // ... already done by following form manipulations
 144        }
 145        
 146        // standard image fupload form; will be shown in the most cases (not for existing node in single mode)
 147        if (isset($form['#node']->nid) && $field['widget']['fupload_mode'] == "single") {
 148          // don't create fupload form
 149        } else {
 150          $form['fupload'] = array(
 151            '#weight' => $fupload_widget_weight - 0.1,
 152          );
 153      
 154          $form['fupload']['message'] = array(
 155            '#value' => '<div id="jsstatus"></div>',
 156            '#prefix' => '<div id="uploadform" style="visibility:hidden;"></div>', // needed to scroll to error and status messages
 157            '#weight' => -7,
 158          );
 159          $form['fupload']['image'] = array(
 160            '#type' => 'fieldset',
 161            '#title' => t('Images'),
 162            '#value' => '<span style="font-style:italic;">' .t('Click the "Select Images" icon on the left below to begin.') .'</span>',
 163            '#weight' => -6,
 164            '#attributes' => array('class' => 'flash', 'id' => 'fsUploadProgress'),          
 165            '#collapsible' => FALSE,
 166            '#collapsed' => FALSE,
 167          );
 168          $form['fupload']['upload_info'] = array(
 169            '#value' => t('0 files uploaded.') . ' ',
 170            '#prefix' => '<div id="divStatus">',
 171            '#suffix' => '</div>',
 172            '#weight' => -5,
 173          );
 174          // Drupal 6 Bug: can't use "normal" buttons, only submit buttons are possible => workaround
 175          $form['fupload']['upload_buttons'] = array(
 176            '#prefix' => '<div>',
 177            '#value' => '<span id="spanUploadButton"></span> <input id="btnCancel" type="button" value="'.t('Cancel All Uploads').'" onclick="swfu.cancelQueue();" disabled="disabled" /> ',    
 178            '#suffix' => '</div>',
 179            '#weight' => -4,
 180          );
 181          $form['fupload']['upload_buttons']['node_create'] = array(
 182            '#type' => 'submit',
 183            '#value' => t('Process queued images'),
 184            '#weight' => -3,
 185            '#ahah' => array(
 186              'path' => 'fupload/js/imagefield',
 187              'event' => 'click',
 188              'method' => 'replace',
 189              'wrapper' => 'jsstatus',
 190              'progress' => array('type' => 'bar', 'message' => t('Images in queue are processed...')),
 191            ),
 192          );
 193          $form['fupload']['upload_buttons']['delete_queue'] = array(
 194            '#type' => 'submit',
 195            '#value' => t('Delete queued images'),
 196            '#weight' => -2,
 197            '#ahah' => array(
 198              'path' => 'fupload/js/deletequeue/' .$field_name,
 199              'event' => 'click',
 200              'method' => 'append',
 201              'wrapper' => 'jsstatus',
 202            ),
 203          );
 204          if (user_access('edit captions') && !isset($form['#node']->nid)) {
 205            $form['fupload']['upload_buttons']['next_step'] = array(
 206              '#value' => '<input type="button" value="'.t('Next step').'" id="imagepreviewlistbutton" style="visibility:hidden" />',
 207              '#weight' => -1,
 208            ); 
 209          }
 210          
 211          if (isset($form['#node']->nid)) {
 212            $form['fupload']['upload_info']['#value'] .= t('Queued files will be uploaded by clicking the "Upload images" button.');
 213            $form['fupload']['upload_buttons']['submit'] = array(
 214              '#value' => '<input type="button" value="'.t('Upload images').'" id="startuploadbutton" onclick="startUploadProcess();window.location.href=\'#uploadform\'" />',
 215              '#weight' => -2,
 216            );
 217          } else {
 218            $form['fupload']['upload_info']['#value'] .=  t('Queued files will be uploaded by clicking the "Save" button at the bottom of this page.');
 219            $form['buttons']['fupload_submit'] = array(
 220              '#value' => '<input type="button" value="'.t('Save').'" id="startuploadbutton" onclick="startUploadProcess();window.location.href=\'#uploadform\'" />',
 221              '#weight' => 19,
 222              '#submit' => array('node_form_submit'),
 223            ); 
 224          }
 225          
 226          //it seems we don't need it any more, but before, some testing
 227          //if (!isset($form['#node']->nid) && !isset($form_state['redirect']))
 228          //$form['#redirect'] = FALSE; // Important that $_POST is not empty after browser submit           
 229        }
 230      }
 231    }
 232  }
 233  
 234  function image_fupload_imagefield_node_create() {
 235    global $user;
 236    
 237    // Get some POST Variables
 238    $form_build_id = $_POST['form_build_id'];
 239    $form_id = $_POST['form_id'];
 240    
 241    if (isset($form_build_id) && isset($form_id)) {
 242      $form_error = 0;
 243      $message = ''; // message which will be returned to the user via JavaScript
 244      $redirect_url = ''; // updated redirect url
 245      
 246      // Load the form from the Form API cache and check if valid
 247      $form_state = array('rebuild' => TRUE, 'values' => $_POST); // rebuild option needed to prevent that "_image_node_form_submit" gets executed by drupal_process_form
 248      if (!($form = form_get_cache($form_build_id, $form_state))) {
 249        // code based on upload.module (15/08/2008)
 250        form_set_error('form_token', t('Validation error, please try again. If this error persists, please contact the site administrator.'));
 251        $output = theme('status_messages');
 252        drupal_json(array('status' => TRUE, 'data' => $output));
 253        exit();
 254      }
 255      
 256      // some basic variables
 257      $field_name = $form['field_name']['#value']; // name of imagefield
 258      $node_type = $form['node_type']['#value']; // image node type
 259      $field = content_fields($field_name, $node_type); // imagefield widget
 260      // include node.pages.inc for some needed functions (node_form_submit_build_node)
 261      module_load_include('inc', 'node', 'node.pages');
 262      
 263      // Remove images which couldn't be processed completly (--> mostly because of memory excaustion) --> physical removal done by cron
 264      db_query("UPDATE {files} SET filename = '%s' WHERE uid = %d AND status = %d AND filename = '%s'", image_fupload_image_status($field_name, IMAGE_PROCESSED), $user->uid, FILE_STATUS_TEMPORARY, image_fupload_image_status($field_name, IMAGE_HALFPROCESSED));
 265      
 266      // Some form manipulations, if some fields are not sent
 267      $form['#post'] = $_POST;
 268      $form['#post']['form_id'] = $form['form_id']['#value']; 
 269      if (!isset($form['title'])) {      
 270        // Default Value; Title will be overwritten in the next steps
 271        $form['#post']['title'] = 'Image';         
 272        // New generated fields
 273        $form['title'] = array('#type' => 'textfield', '#title' => 'title2change', '#default_value' => ''); // Needed that validation is successful
 274      }
 275      
 276      // if we are editing already existing node, remove nid to prevent errors because node was changed before
 277      if (isset($form['nid']['#value'])) {
 278        $form['gallery_nid']['#value'] = $form['nid']['#value'];
 279        unset($form['nid']['#value'], $form_state['values']['nid']);
 280      }
 281      
 282      // Form validation
 283      drupal_process_form($form_id, $form, $form_state);
 284      if (!form_get_errors()) {
 285        // prepare array for queuing images for imagefield (multiple images per node)
 286        $imagefield_files = array();
 287      
 288        // validation passed
 289        $result = db_query_range("SELECT * FROM {files} WHERE uid = %d AND status = %d AND filename = '%s'", $user->uid, FILE_STATUS_TEMPORARY, image_fupload_image_status($field_name, IMAGE_UNMACHINED), 0, 3);
 290        while ($image = db_fetch_object($result)) {
 291          $img_cache[] = $image; // cache our images
 292          // Set status flag on image (work on picture can begin); if there are problems with this image, it will be kicked next time
 293          db_query("UPDATE {files} SET filename = '%s' WHERE fid = %d", image_fupload_image_status($field_name, IMAGE_HALFPROCESSED), $image->fid);
 294          
 295          // Create a filename out of the given image information; used a theme function so that it can be customised; mapping new title only if title field is disabled for preview list
 296          if ($form['title']['#title'] == "title2change") {
 297            $form['title']['#value'] = theme('fupload_create_filename', $image, $field['widget']['fupload_title_replacements']);
 298            $form_state['values']['title'] = $form['title']['#value'];
 299          }
 300          // import our file (uploaded in queue); code from [#292904] (thx to drewish) (D6 24/08/2008)
 301          $validators = array_merge(filefield_widget_upload_validators($field), imagefield_widget_upload_validators($field));
 302          $files_path = _fupload_import_widget_files_directory($field);
 303          //drupal_set_message($files_path);
 304          
 305          // split up storage modes
 306          if ($field['widget']['fupload_mode'] == "single") {
 307            // one node per image - mode     
 308            if ($file = field_file_save_file($image->filepath, $validators, $files_path)) {
 309              // prepare node; code partially taken from function "node_form_submit" (D6 24/08/2008 node.pages.inc)
 310              $node = node_form_submit_build_node($form, $form_state);
 311              $insert = empty($node->nid);
 312              // add new files to node
 313              $node->$field_name = array(0 => $file);  
 314              // save node
 315              node_save($node);
 316            
 317              // report to watchdog
 318              $node_link = l(t('view'), 'node/'. $node->nid);
 319              $watchdog_args = array('@type' => $node->type, '%title' => $node->title);
 320              $t_args = array('@type' => node_get_types('name', $node), '%title' => $node->title);
 321  
 322              if ($insert) {
 323                watchdog('content', '@type: added %title.', $watchdog_args, WATCHDOG_NOTICE, $node_link);
 324                drupal_set_message(t('@type %title has been created.', $t_args));
 325              }
 326              else {
 327                watchdog('content', '@type: updated %title.', $watchdog_args, WATCHDOG_NOTICE, $node_link);
 328                drupal_set_message(t('@type %title has been updated.', $t_args));
 329              }
 330              if ($node->nid) {
 331                $form_state['nid'] = $node->nid;
 332                
 333                // file inserting successful =) Prevent that same image is processed twice; deleted later by cron
 334                db_query("UPDATE {files} SET filename = '%s' WHERE fid = %d", image_fupload_image_status($field_name, IMAGE_PROCESSED), $image->fid);
 335                // mark file for preview list if necessary
 336                if (user_access('edit captions'))
 337                  db_query("INSERT INTO {fupload_previewlist} (fieldname, uid, nid, fid, created) VALUES ('%s', %d, %d, %d, %d)", $field_name, $user->uid, $node->nid, $file['fid'], time());
 338                
 339              } else {
 340                // In the unlikely case something went wrong on save, the node will be
 341                // rebuilt and node form redisplayed the same way as in preview.
 342                drupal_set_message(t('The post could not be saved.'), 'error');
 343              } 
 344            }         
 345            
 346          } else {
 347            // multiple images per node - mode          
 348            
 349            // create gallery node if it doesn't exist
 350            if (!isset($form['gallery_nid']['#value'])) {
 351              $node = _fupload_node_save($form, $form_state, $form_build_id);            
 352            } else {
 353              $node->nid = $form['gallery_nid']['#value'];
 354              // add removed node specific; in case that form is cached again
 355              $form['nid']['#value'] = $node->nid;
 356              $form_state['values']['nid'] = $node->nid;
 357            }          
 358            
 359            // add images to node 
 360  
 361            // add validation to check if some space is left for the file in our node
 362            $validators['image_fupload_validate_total_filesize'] = array($node->nid, $field_name, parse_size($field['widget']['max_filesize_per_node'])); 
 363                      
 364            if ($file = field_file_save_file($image->filepath, $validators, $files_path)) {
 365              // add images to queue to be merged into one node later --> better performance
 366              $imagefield_files[] = $file;
 367              drupal_set_message(t('Image %title added.', array('%title' => $file['filename'])));
 368              
 369              // file inserting successful =) Prevent that same image is processed twice; deleted later by cron
 370              db_query("UPDATE {files} SET filename = '%s' WHERE fid = %d", image_fupload_image_status($field_name, IMAGE_PROCESSED), $image->fid);
 371              // mark file for preview list if necessary
 372              if (user_access('edit captions'))
 373                db_query("INSERT INTO {fupload_previewlist} (fieldname, uid, nid, fid, created) VALUES ('%s', %d, %d, %d, %d)", $field_name, $user->uid, $node->nid, $file['fid'], time());
 374            
 375            } else {
 376              // some validators couldn't be satisfied --> empty queue
 377              $form_error = 2;
 378            }
 379          }
 380          
 381        }
 382        // add queued images to node gallery (multiple storage mode)
 383        if (count($imagefield_files)) {
 384          $node = node_load($node->nid);
 385          
 386          // add files to node       
 387          //$node->$field_name = array_merge((is_array($node->$field_name) ? $node->$field_name : array()), $imagefield_files);
 388          $node->$field_name = array_merge($node->$field_name, $imagefield_files);
 389          
 390          node_save($node);
 391        }  
 392        
 393        // build redirect url: multiple mode and no access to preview page
 394        if (isset($form['gallery_nid']['#value']) && !user_access('edit captions')) {         
 395           $redirect_url = 'node/' .$form['gallery_nid']['#value'];
 396        }
 397  
 398        // if alternative redirect url is provided, replace existing one
 399        if (!empty($field['widget']['fupload_previewlist_redirecturl']) && !user_access('edit captions'))
 400          $redirect_url = $field['widget']['fupload_previewlist_redirecturl'];
 401        
 402        // send updated redirect url via json_decode
 403        if (!empty($redirect_url) && $form_error == 0)
 404          $message .= '<input type="hidden" name="redirect_url" id="redirect_url" value="' .url($redirect_url) .'" />';
 405          
 406        // examine how many images are left in queue and inform JS by sending a hidden element
 407        $result = db_fetch_object(db_query("SELECT COUNT(*) AS img_count FROM {files} WHERE uid = %d AND status = %d AND filename = '%s'", $user->uid, FILE_STATUS_TEMPORARY, image_fupload_image_status($field_name, IMAGE_UNMACHINED)));
 408        $message .= '<input type="hidden" name="num_queued_images" id="num_queued_images" value="' . $result->img_count . '" />';      
 409        
 410      } else {
 411        // error in received form (for example a required field was not filled) or during process; inform JS => user
 412        if ($form_error != 2) // special case: some validators of imagefield weren't satisfied
 413          $form_error = 1;
 414        $message .= '<input type="hidden" name="num_queued_images" id="num_queued_images" value="0" />';
 415      }    
 416      
 417      // Inform JS about errors
 418      $message .= '<input type="hidden" name="form_errors" id="form_errors" value="' . $form_error . '"  />';
 419      $message .= theme('status_messages'); // Theme all messages
 420      
 421      drupal_json(array('status' => TRUE, 'data' => $message));
 422      
 423    } else {
 424      drupal_json(array('status' => FALSE, 'data' => t('Error: No or wrong POST Data')));
 425    }     
 426  }
 427  
 428  /**
 429   * CCK related stuff
 430   */
 431   
 432  /**
 433   * Implementation of hook_elements().
 434   */
 435  function image_fupload_imagefield_elements() {
 436    $elements = array();
 437    $elements_imagefield = module_invoke('imagefield', 'elements');
 438    $elements['image_fupload_imagefield_widget'] = $elements_imagefield['imagefield_widget'];
 439    
 440    return $elements;
 441  }
 442  
 443  /**
 444   * Implementation of CCK's hook_widget_info().
 445   */
 446  function image_fupload_imagefield_widget_info() {
 447    return array(
 448      'image_fupload_imagefield_widget' => array(
 449        'label' => t('Image FUpload'),
 450        'field types' => array('image', 'filefield'),
 451        'multiple values' => CONTENT_HANDLE_CORE,
 452        'callbacks' => array('default value' => CONTENT_CALLBACK_CUSTOM),      
 453        'description' => t('An edit widget for image files being uploaded via Image FUpload, including a preview of the image and editing options.'),
 454      ),
 455    );
 456  }
 457  
 458  /**
 459   * Implementation of CCK's hook_widget_settings().
 460   */
 461  function image_fupload_imagefield_widget_settings($op, $widget) {
 462    module_load_include('inc', 'image_fupload_imagefield', 'image_fupload_imagefield_widget');
 463  
 464    switch ($op) {
 465      case 'form':
 466        return image_fupload_imagefield_widget_settings_form($widget);
 467      case 'validate':
 468        return image_fupload_imagefield_widget_settings_validate($widget);
 469      case 'save':
 470        return image_fupload_imagefield_widget_settings_save($widget);
 471    }
 472  }
 473  
 474  /**
 475   * Implementation of hook_widget().
 476   *
 477   * Assign default properties to item and delegate to filefield.
 478   */
 479  function image_fupload_imagefield_widget($form, $form_state, $field, $items, $delta = 0) {
 480    $element = module_invoke('imagefield', 'widget', $form, $form_state, $field, $items, $delta);
 481    return $element;
 482  }
 483  
 484  /**
 485   * Interact on changes to CCK ImageFields.
 486   */
 487  function image_fupload_imagefield_content_fieldapi($op, $field, $new_instance = NULL) {
 488    $image_node_types = variable_get('image_node_types', array());
 489    switch ($op) {
 490      case "delete instance":
 491        // check if a image fupload related field is deleted
 492        if ($image_node_types[$field['type_name']]['fieldname'] == $field['field_name'])
 493          _fupload_imagepreview_settings('delete', $field['type_name']); // remove settings in variable image_node_types      
 494        break;
 495    }
 496  }
 497  
 498  /**
 499   * Removing a given list of fields (ckk, node, imagefield, taxonomy) of form
 500   * Validation for these fields will also be deactivated
 501   */
 502  
 503  function form_fields_destroy(&$form, $fields_to_remove = array()) {
 504    // collect information about fields being used by image preview list, if needed  
 505    $fields = array();
 506    foreach ($fields_to_remove as $key) {
 507      $elements = explode("_", $key, 2);
 508      if (!isset($fields[$elements[0]]) && $fields_to_remove[$key] != FALSE)
 509        $fields[$elements[0]] = array();
 510      if ($fields_to_remove[$key] != FALSE)
 511        array_push($fields[$elements[0]], $elements[1]);
 512    }
 513    
 514    // any node specific fields which should be removed ..argg
 515    if (isset($fields['node'])) {
 516      if (in_array("title", $fields['node']))
 517        unset($form['title']);
 518      if (in_array("description", $fields['node']))
 519        unset($form['body_field']);
 520    }
 521    
 522    if (isset($fields['taxonomy'])) {
 523      // remove taxonomy items if necessary
 524      for ($i = 0; $i < count($fields['taxonomy']); $i++) {
 525          unset($form['taxonomy'][$fields['taxonomy'][$i]]);
 526          unset($form['taxonomy']['tags'][$fields['taxonomy'][$i]]);
 527        if (!count($form['taxonomy']['tags']))
 528          unset($form['taxonomy']['tags']);      
 529      }
 530      // still anything left to render?
 531      if (count(taxonomy_get_vocabularies($form['#node']->type)) == count($fields['taxonomy']))
 532          unset($form['taxonomy']);
 533    }
 534    
 535    if (isset($fields['cck'])) {
 536      // remove cck fields if necessary
 537      for ($i = 0; $i < count($fields['cck']);$i++) {
 538        unset($form[$fields['cck'][$i]]);
 539        unset($form['#field_info'][$fields['cck'][$i]]);
 540      }
 541      if (!count($form['#field_info']))
 542        unset($form['#field_info']);
 543    }
 544  }
 545  
 546  /**
 547   * Theming related things
 548   */
 549  
 550  function theme_image_fupload_imagefield_item($item) {
 551    return theme('imagefield_item', $item);
 552  }
 553  
 554  function theme_image_fupload_imagefield_widget_preview($item = null) {
 555    return theme('imagefield_widget_preview', $item);
 556  }
 557  
 558  function theme_image_fupload_imagefield_widget_item($element) {
 559    return theme('imagefield_widget_item', $element);
 560  }
 561  
 562  /**
 563  * Determine the widget's files directory [#292904] (great thanks to drewish)
 564  *
 565  * @param $field CCK field
 566  * @return files directory path.
 567  */
 568  function _fupload_import_widget_files_directory($field) {
 569    $widget_file_path = $field['widget']['file_path'];
 570    if (module_exists('token')) {
 571      global $user;
 572      $widget_file_path = token_replace($widget_file_path, 'user', $user);
 573    }
 574    return file_directory_path() .'/'. $widget_file_path;
 575  }
 576  
 577  /*
 578  * Build a node from $form and save it to database
 579  */
 580  function _fupload_node_save(&$form, $form_state, $form_build_id) {
 581    $node = node_form_submit_build_node($form, $form_state);
 582    $insert = empty($node->nid);
 583    // save node
 584    node_save($node);
 585            
 586    // report to watchdog
 587    $node_link = l(t('view'), 'node/'. $node->nid);
 588    $watchdog_args = array('@type' => $node->type, '%title' => $node->title);
 589    $t_args = array('@type' => node_get_types('name', $node), '%title' => $node->title);
 590  
 591    if ($insert) {
 592      watchdog('content', '@type: added %title.', $watchdog_args, WATCHDOG_NOTICE, $node_link);
 593      drupal_set_message(t('@type %title has been created.', $t_args));
 594    }
 595    if ($node->nid) {
 596      // will be saved in cache so that only one gallery node will be created
 597      $form['gallery_nid']['#value'] = $node->nid; 
 598      $form_state['values']['gallery_nid'] = $node->nid;
 599                
 600      // save form to cache
 601      form_set_cache($form_build_id, $form, $form_state);               
 602      return $node;
 603      
 604    } else {
 605      // In the unlikely case something went wrong on save, the node will be
 606      // rebuilt and node form redisplayed the same way as in preview.
 607      drupal_set_message(t('The post could not be saved.'), 'error');
 608      return FALSE;
 609    }
 610  }
 611  
 612  /*
 613  * Validation function
 614  * Checkes if filesize sum of node doesn't exceed the limits
 615  */
 616  
 617  function image_fupload_validate_total_filesize($file, $nid, $field_name, $node_size = 0) {
 618    global $user;
 619    $errors = array();
 620    $total_size = 0;
 621    
 622    if ($node_size && $user->uid != 1) {
 623      $result = db_query("SELECT f.filesize FROM {content_%s} AS t JOIN {files} AS f ON t.%s_fid = f.fid WHERE t.nid = %d", $field_name, $field_name, $nid);
 624      while ($image = db_fetch_object($result)) {
 625        $total_size += $image->filesize;
 626      }    
 627      if (($total_size + $file->filesize) > $node_size)
 628        $errors[] = t('The new total filesize of this node, %tsize, would exceed field settings of %msize.', array('%tsize' => format_size($total_size + $file->filesize), '%msize' => format_size($node_size)));
 629    }
 630    return $errors;
 631  }


Generated: Mon Jul 9 18:01:44 2012 Cross-referenced by PHPXref 0.7