JPG nach upload umbenennen

Einklappen
X
 
  • Filter
  • Zeit
  • Anzeigen
Alles löschen
neue Beiträge

  • JPG nach upload umbenennen

    Moin,

    passe gerade eine Gallerie für Buddypress an, die ich mir runtergeladen haben und bin mal wieder hängen geblieben.

    Ich möchte die JPG-Datei nach dem Upload mit der Bild-ID versehen, momentan wird das JPG mit dem normalen Dateinamen auf dem Server gespeichert.


    Hier mal der Teil der Gallerie, von dem Ich denke, das er relevant ist:

    PHP-Code:
    function bp_album_action_upload() {
        global 
    $bp;
        
        if ( 
    $bp->current_component == $bp->album->slug && $bp->album->upload_slug == $bp->current_action && isset( $_POST['submit'] )) {

            
    check_admin_referer('bp-album-upload');

            
    $error_flag false;
            
    $feedback_message = array();

            
    // check privacy
            
    if( !isset($_POST['privacy']) ){
                
    $error_flag true;
                
    $feedback_message[] = __'Please select a privacy option.''bp-album' );
            } else {
                
    $priv_lvl intval($_POST['privacy']);

                            
    // TODO: Refactor this, and the bp_album_max_privXX variable as an array.
                            
    switch ($priv_lvl) {
                                case 
    "0"$pic_limit $bp->album->bp_album_max_priv0_pictures; break;
                                case 
    "1"$pic_limit $bp->album->bp_album_max_priv1_pictures; break;
                                case 
    "2"$pic_limit $bp->album->bp_album_max_priv2_pictures; break;
                                case 
    "3"$pic_limit $bp->album->bp_album_max_priv3_pictures; break;
                                case 
    "4"$pic_limit $bp->album->bp_album_max_priv4_pictures; break;
                                case 
    "5"$pic_limit $bp->album->bp_album_max_priv5_pictures; break;
                                case 
    "6"$pic_limit $bp->album->bp_album_max_priv6_pictures; break;
                                case 
    "7"$pic_limit $bp->album->bp_album_max_priv7_pictures; break;
                                case 
    "8"$pic_limit $bp->album->bp_album_max_priv8_pictures; break;
                                case 
    "9"$pic_limit $bp->album->bp_album_max_priv9_pictures; break;
                                default: 
    $pic_limit null;
                            }


                if(
    $priv_lvl == 10 )
                    
    $pic_limit is_site_admin() ? false null;
                if( 
    $pic_limit === null){ //costant don't exist
                    
    $error_flag true;
                    
    $feedback_message[] =
     
    __'Privacy option is not correct.''bp-album' );
                }elseif( 
    $pic_limit !== false && ( $pic_limit === 0  || $pic_limit <= bp_album_get_picture_count(array('privacy'=>$priv_lvl)) ) ){
                    
    $error_flag true;
                    switch (
    $priv_lvl){
                        case 
    :
                            
    $feedback_message[] =
     
    __'You reached the limit for public pictures.''bp-album' ).' '.__'Please select another privacy option.''bp-album' );
                            break;
                        case 
    :
                            
    $feedback_message[] =
     
    __'You reached the limit for pictures visible to community members.''bp-album' ).' '.__'Please select another privacy option.''bp-album' );
                            break;
                        case 
    :
                            
    $feedback_message[] = 
    __'You reached the limit for pictures visible to friends.''bp-album' ).' '.__'Please select another privacy option.''bp-album' );
                            break;
                        case 
    :
                            
    $feedback_message[] =
     
    __'You reached the limit for private pictures.''bp-album' ).' '.__'Please select another privacy option.''bp-album' );
                            break;
                    }
                }
            }

            
    $uploadErrors = array(
                
    => __("There is no error, the file uploaded with success"'buddypress'),
                
    => __("Your image was bigger than the maximum allowed file size of: "'buddypress') . size_format(CORE_MAX_FILE_SIZE),
                
    => __("Your image was bigger than the maximum allowed file size of: "'buddypress') . size_format(CORE_MAX_FILE_SIZE),
                
    => __("The uploaded file was only partially uploaded"'buddypress'),
                
    => __("No file was uploaded"'buddypress'),
                
    => __("Missing a temporary folder"'buddypress')
            );
            if ( isset(
    $_FILES['file']) ){
            
                if ( 
    $_FILES['file']['error'] ) {
                    
    $feedback_message[] = 
    sprintf__'Your upload failed, please try again. Error was: %s''buddypress' ), $uploadErrors[$_FILES['file']['error']] );
                    
    $error_flag true;
                }

                if ( 
    $_FILES['file']['size'] > BP_AVATAR_ORIGINAL_MAX_FILESIZE ) {
                    
    $feedback_message[] = 
    sprintf__'The file you uploaded is too big. Please upload a file under %s''buddypress'), size_format(CORE_MAX_FILE_SIZE) );
                    
    $error_flag true;
                }

                if ( !
    bp_core_check_avatar_type$_FILES['file'] ) ) {
                    
    $feedback_message[] =
     
    __'Please upload only JPG, GIF or PNG photos.''buddypress' );
                    
    $error_flag true;
                }
            }else{
                
    $feedback_message[] = 
    sprintf__'Your upload failed, please try again. Error was: %s''buddypress' ), $uploadErrors[4] );
                
    $error_flag true;

            }

            if(!
    $error_flag){  // If everything is ok handle the upload and move to the directory

                
    add_filter'upload_dir''bp_album_upload_dir'10); //the upload handle get the upload dir from this filter
                

                
    $pic_org wp_handle_upload$_FILES['file'],array('action'=>'picture_upload') );

                if ( !empty( 
    $pic_org['error'] ) ) {
                    
    $feedback_message[] =
     
    sprintf__('Your upload failed, please try again. Error was: %s''buddypress' ), $pic_org['error'] );
                    
    $error_flag true;
                }
            }
            if(!
    $error_flag){  // If everything is ok resize the picture

                
    $abs_path_to_files defined'BLOGUPLOADDIR' ) ? str_replace('/files/','/',BLOGUPLOADDIR) : ABSPATH;

                
    $pic_org_path $pic_org['file'];
                
    $pic_org_url str_replace($abs_path_to_files,'/',$pic_org_path);

                
    $pic_org_size getimagesize$pic_org_path );
                
    $pic_org_size = ($pic_org_size[0]>$pic_org_size[1])?$pic_org_size[0]:$pic_org_size[1];

                if(
    $pic_org_size <= $bp->album->bp_album_middle_size){
                    
    $pic_mid_path $pic_org_path;
                    
    $pic_mid_url $pic_org_url;
                } else {
                    
    $pic_mid wp_create_thumbnail$pic_org_path$bp->album->bp_album_middle_size );
                    
    $pic_mid_path str_replace'//''/'$pic_mid );
                    
    $pic_mid_url str_replace($abs_path_to_files,'/',$pic_mid_path);
                    if (!
    $bp->album->bp_album_keep_original){
                        
    unlink($pic_org_path);
                        
    $pic_org_url=$pic_mid_url;
                        
    $pic_org_path=$pic_mid_path;
                    }
                }
                if(
    $pic_org_size <= $bp->album->bp_album_thumb_size){
                    
    $pic_thumb_path $pic_org_path;
                    
    $pic_thumb_url $pic_org_url// TN Name!
                
    } else {
                    
    $pic_thumb image_resize$pic_mid_path$bp->album->bp_album_thumb_size$bp->album->bp_album_thumb_sizetrue);
                    
    $pic_thumb_path str_replace'//''/'$pic_thumb );
                    
    $pic_thumb_url str_replace($abs_path_to_files,'/',$pic_thumb);
                }

                
    $owner_type 'user';
                
    $owner_id $bp->loggedin_user->id;
                
    $date_uploaded =  gmdate"Y-m-d H:i:s" );
                
    $title $_FILES['file']['name'];
                
    $description ' ';
                
    $privacy $priv_lvl;

                
    $id=bp_album_add_picture($owner_type,$owner_id,$title,$description,$priv_lvl,$date_uploaded,
    $pic_org_url,$pic_org_path,$pic_mid_url,$pic_mid_path,$pic_thumb_url,$pic_thumb_path);

                if(
    $id)
                    
    $feedback_message[] = __('Picture uploaded. Now you can change picture details.''bp-album');
                else {
                    
    $error_flag true;
                    
    $feedback_message[] = __('There were problems saving picture details.''bp-album');
                }
            }

            if (
    $error_flag){
                
    bp_core_add_messageimplode('&nbsp;'$feedback_message ),'error');
            } else {
                
    bp_core_add_messageimplode('&nbsp;'$feedback_message ),'success' );
                
    bp_core_redirect$bp->loggedin_user->domain $bp->
    current_component '/'.$bp->album->single_slug.'/' $id.'/'.$bp->album->edit_slug.'/');
                die;
            }

        }

    }
    add_action('wp','bp_album_action_upload',3); 
    ich habe schon an alle möglichen Variablen versucht, String-ketten anzuhängen (am ausichtsreichsten erschien mir $_FILES['file'] umzubennen), jedoch nie mit dem Ergebnis, das die hochgeladenen Datei umbenannt wurde :/

    die ganze Gallerie gibts es übrigens hier:
    WordPress › BuddyPress Album+ WordPress Plugins

    gruss,
    Alex
    Zuletzt geändert von xserio; 03.07.2010, 02:02.

  • #2
    Hallo,

    der Code ist zu breit, bitte sinnvoll umbrechen. Poste bitte mal den Inhalt der Funktion wp_handle_upload, da ich dort die relevante Stelle vermute. Zu deinen bisherigen Versuchen: Das wird an der Stelle nichts bringen, also erstmal rückgängig machen.

    Gruß,

    Amica
    [COLOR="DarkSlateGray"]Hast du die [COLOR="DarkSlateGray"]Grundlagen zur Fehlersuche[/color] gelesen? Hast du Code-Tags benutzt?
    Hast du als URL oder Domain-Beispiele example.com, example.net oder example.org benutzt?
    Super, danke!
    [/COLOR]

    Kommentar


    • #3
      hi,

      die wp_handle_upload funktion ist eine in Wordpress integrierte, auf die das Script zugreift:

      PHP-Code:
      function wp_handle_upload( &$file$overrides false$time null ) {
          
      // The default error handler.
          
      if ( ! function_exists'wp_handle_upload_error' ) ) {
              function 
      wp_handle_upload_error( &$file$message ) {
                  return array( 
      'error'=>$message );
              }
          }

          
      $file apply_filters'wp_handle_upload_prefilter'$file );

          
      // You may define your own function and pass the name in $overrides['upload_error_handler']
          
      $upload_error_handler 'wp_handle_upload_error';

          
      // You may have had one or more 'wp_handle_upload_prefilter' functions error out the file.  
      Handle that gracefully.
          if ( isset( 
      $file['error'] ) && !is_numeric$file['error'] ) && $file['error'] )
              return 
      $upload_error_handler$file$file['error'] );

          
      // You may define your own function and pass the name in $overrides['unique_filename_callback']
          
      $unique_filename_callback null;

          
      // $_POST['action'] must be set and its value must equal $overrides['action'] or this:
          
      $action 'wp_handle_upload';

          
      // Courtesy of php.net, the strings that describe the error indicated in $_FILES[{form field}]['error'].
          
      $upload_error_strings = array( false,
              
      __"The uploaded file exceeds the <code>upload_max_filesize</code> directive in <code>php.ini</code>." ),
              
      __"The uploaded file exceeds the <em>MAX_FILE_SIZE</em> directive that was specified in the HTML form." ),
              
      __"The uploaded file was only partially uploaded." ),
              
      __"No file was uploaded." ),
              
      '',
              
      __"Missing a temporary folder." ),
              
      __"Failed to write file to disk." ),
              
      __"File upload stopped by extension." ));

          
      // All tests are on by default. Most can be turned off by $override[{test_name}] = false;
          
      $test_form true;
          
      $test_size true;
          
      $test_upload true;

          
      // If you override this, you must provide $ext and $type!!!!
          
      $test_type true;
          
      $mimes false;

          
      // Install user overrides. Did we mention that this voids your warranty?
          
      if ( is_array$overrides ) )
              
      extract$overridesEXTR_OVERWRITE );

          
      // A correct form post will pass this test.
          
      if ( $test_form && (!isset( $_POST['action'] ) || ($_POST['action'] != $action ) ) )
              return 
      call_user_func($upload_error_handler$file__'Invalid form submission.' ));

          
      // A successful upload will pass this test. It makes no sense to override this one.
          
      if ( $file['error'] > )
              return 
      call_user_func($upload_error_handler$file$upload_error_strings[$file['error']] );

          
      // A non-empty file will pass this test.
          
      if ( $test_size && !($file['size'] > ) ) {
              if ( 
      is_multisite() )
                  
      $error_msg __'File is empty. Please upload something more substantial.' );
              else
                  
      $error_msg __'File is empty. Please upload something more substantial. 
      This error could also be caused by uploads being disabled in your php.ini or by post_max_size being defined 
      as smaller than upload_max_filesize in php.ini.' 
      );
              return 
      call_user_func($upload_error_handler$file$error_msg);
          }

          
      // A properly uploaded file will pass this test. There should be no reason to override this one.
          
      if ( $test_upload && ! @ is_uploaded_file$file['tmp_name'] ) )
              return 
      call_user_func($upload_error_handler$file__'Specified file failed upload test.' ));

          
      // A correct MIME type will pass this test. Override $mimes or use the upload_mimes filter.
          
      if ( $test_type ) {
              
      $wp_filetype wp_check_filetype_and_ext$file['tmp_name'], $file['name'], $mimes );

              
      extract$wp_filetype );

              
      // Check to see if wp_check_filetype_and_ext() determined the filename was incorrect
              
      if ( $proper_filename )
                  
      $file['name'] = $proper_filename;

              if ( ( !
      $type || !$ext ) && !current_user_can'unfiltered_upload' ) )
                  return 
      call_user_func($upload_error_handler$file__'File type does not meet security guidelines. Try another.' ));

              if ( !
      $ext )
                  
      $ext ltrim(strrchr($file['name'], '.'), '.');

              if ( !
      $type )
                  
      $type $file['type'];
          } else {
              
      $type '';
          }

          
      // A writable uploads dir will pass this test. Again, there's no point overriding this one.
          
      if ( ! ( ( $uploads wp_upload_dir($time) ) && false === $uploads['error'] ) )
              return 
      call_user_func($upload_error_handler$file$uploads['error'] );

          
      $filename wp_unique_filename$uploads['path'], $file['name'], $unique_filename_callback );

          
      // Move the file to the uploads dir
          
      $new_file $uploads['path'] . "/$filename";
          if ( 
      false === @ move_uploaded_file$file['tmp_name'], $new_file ) )
              return 
      $upload_error_handler$filesprintf__('The uploaded file could not be moved to %s.' ), $uploads['path'] ) );

          
      // Set correct file permissions
          
      $stat statdirname$new_file ));
          
      $perms $stat['mode'] & 0000666;
          @ 
      chmod$new_file$perms );

          
      // Compute the URL
          
      $url $uploads['url'] . "/$filename";

          if ( 
      is_multisite() )
              
      delete_transient'dirsize_cache' );

          return 
      apply_filters'wp_handle_upload', array( 'file' => $new_file'url' => $url'type' => $type ), 'upload' );

      Kommentar


      • #4
        Dort passiert die Magie, in die du eingreifen willst:

        PHP-Code:
        098|     $filename wp_unique_filename$uploads['path'], $file['name'], $unique_filename_callback );
        099|
        100|     // Move the file to the uploads dir
        101|     $new_file $uploads['path'] . "/$filename";
        102|     if ( false === @ move_uploaded_file$file['tmp_name'], $new_file ) )
        103|         return $upload_error_handler$filesprintf__('The uploaded file could not be moved to %s.' ), $uploads['path'] ) ); 
        Die Zeilennummern beziehen sich auf den Code, so wie du ihn im letzten Beitrag gepostet hast.
        Zuletzt geändert von AmicaNoctis; 03.07.2010, 02:11.
        [COLOR="DarkSlateGray"]Hast du die [COLOR="DarkSlateGray"]Grundlagen zur Fehlersuche[/color] gelesen? Hast du Code-Tags benutzt?
        Hast du als URL oder Domain-Beispiele example.com, example.net oder example.org benutzt?
        Super, danke!
        [/COLOR]

        Kommentar


        • #5
          ah super, viele dank schonmal! das mit dem umbennen klappt, aber nur für die Originaldatei. Das Script generiert noch ein Thumbnail und ein Mittelgroßes Bild, welche allerdings immernoch den ursprünglichen Namen behalten :/ (werden im gleichen Ordner abgelegt.)

          Und die ID anzuhängen habe ich auch noch nicht geschafft.

          hab so versucht:
          PHP-Code:
          $test bp_album_picture_id();
              
              
          // Move the file to the uploads dir
              
          $new_file $uploads['path'] . "/$test$filename";
              if ( 
          false === @ move_uploaded_file$file['tmp_name'], $new_file ) ) 
          die funktion sieht so aus und liegt in einer anderen datei:

          PHP-Code:
          function bp_album_picture_id() {
              echo 
          bp_album_get_picture_id();
          }
              function 
          bp_album_get_picture_id() {
                  global 
          $pictures_template;
                  return 
          apply_filters'bp_album_get_picture_id'$pictures_template->picture->id );
              } 

          Kommentar


          • #6
            Damit willst du mich aber sicher nicht weiter belasten und suchst selbst nach den entsprechenden Stellen, oder?

            Schlüsselworte für die Volltext-Codesuche: imagecopyresampled oder imagecopyresized
            [COLOR="DarkSlateGray"]Hast du die [COLOR="DarkSlateGray"]Grundlagen zur Fehlersuche[/color] gelesen? Hast du Code-Tags benutzt?
            Hast du als URL oder Domain-Beispiele example.com, example.net oder example.org benutzt?
            Super, danke!
            [/COLOR]

            Kommentar


            • #7
              alles klar, ich versuche mir da mal was zurecht zu basteln. Hast mir schon sehr viel weiter geholfen, danke!

              Kommentar


              • #8
                so, jetzt klappt das alles mit dem umbennen der dateien, sehr schön. Allerdings kriege ich die ID des Bildes noch nicht abgefangen.

                mit der funktion bp_album_picture_id(); kann ich die ID von einem hochgeladenen Bild auslesen. Ich habe das so versucht:

                PHP-Code:
                $filename wp_unique_filename$uploads['path'], $file['name'], $unique_filename_callback );

                $test bp_album_picture_id();
                    
                // Move the file to the uploads dir
                $new_file $uploads['path'] . "/$test.$filename";
                    
                if ( 
                false === @ move_uploaded_file$file['tmp_name'], $new_file ) )
                return 
                $upload_error_handler$filesprintf__('The uploaded file could 
                not be moved to %s.' 
                ), $uploads['path'] ) ); 
                kann ja aber garnicht gehen, da das Bild vor dem upload noch keine ID hat, oder liege ich falsch? Hab versucht mit rename und move_uploaded file hinzubekommen, das nach dem upload nochmal ne umbennenung stattfindet (dann sollte die ID ja vorhanden sein) aber das geht irgendwie auch nicht wirklich...

                Kommentar


                • #9
                  Liefert dir die Funktion in der ersten Zeile denn nicht schon die „ID“?
                  Was für eine ID soll das sein? Eine Datenbank o.ä. sehe ich nicht im Spiel, also kann es sich doch eigentlich nur um den unique gewählten Dateinamen handeln ... oder?
                  I don't believe in rebirth. Actually, I never did in my whole lives.

                  Kommentar


                  • #10
                    hi!
                    die funktion liefer glaub ich keine ID, das ist die Wordpress Standard-Funktion und hat so eigentlich nichts mit der galerie zu tun...
                    Eine datenbank gibt es tatsächlich, die hat ein ID feld, welches per auto-increment gefüllt wird. Momentan ist das mein Stand:

                    PHP-Code:
                    $user "root"
                        
                    $passwort ""
                        
                    $host "localhost"
                        
                    $database "becksfiles"
                        
                    $table "wp_bp_album"

                        
                    // Verbindung zu MySQL-Datenbank herstellen oder sterben.
                        
                    @mysql_connect($host,$user,$passwort) or die("Abbruch: Verbindung zu '$host'"." konnte nicht hergestellt werden.");

                        
                    // Benötigte Datenbank auswählen oder sterben.
                        
                    @mysql_select_db($database) or die("Abbruch: Datenbank '$database' konnte nicht"." selektiert werden.<br><br>MySQL sagt: ".mysql_error());
                        
                        
                    $result mysql_query ('SELECT MAX(id) AS last_id FROM wp_bp_album');
                        
                    $result mysql_fetch_assoc ($result);
                        
                    $id $result['last_id'] + 1;  

                        
                    // Move the file to the uploads dir
                        
                    $new_file $uploads['path'] . "/$id.$filename"
                    So bekomme ich die ID in den Dateinamen, allerdings noch fehlerbehaftet:
                    Wenn ich ein Bild aus der Datenbank lösche verschwindet ja auch die ID. Der Auto-Increment läuft allerdings weiter, Beispiel:

                    Das letzte Bild in der DB hat die ID 133, ich lade eins hoch, das bekommt 134 mit dem richtigen Dateinamen. Wenn ich allerdings 134 jetzt lösche und wieder ein neues hochlade bekommt das wieder die 134 in den Dateinamen, obwohl die korrekte ID jetzt 135 wäre, weil der Increment weiter läuft... Ich hoffe ich hab mich klar ausgedrückt

                    Ich schau mich gerade um, ob ich den aktuellen increment-wert besser abfangen kann, wenn du ein tip hast, her damit

                    gruss

                    // EDIT

                    Ich habs!

                    so wird immer die korrekte ID vergeben:

                    PHP-Code:

                        $user 
                    "root"
                        
                    $passwort ""
                        
                    $host "localhost"
                        
                    $database "becksfiles"
                        
                    $table "wp_bp_album"

                        
                    // Verbindung zu MySQL-Datenbank herstellen oder sterben.
                        
                    @mysql_connect($host,$user,$passwort) or die("Abbruch: Verbindung zu '$host'"." konnte nicht hergestellt werden.");

                        
                    // Benötigte Datenbank auswählen oder sterben.
                        
                    @mysql_select_db($database) or die("Abbruch: Datenbank '$database' konnte nicht"." selektiert werden.<br><br>MySQL sagt: ".mysql_error());
                        

                       
                    mysql_query("LOCK TABLES wp_bp_album WRITE");  

                    $result mysql_query("SHOW TABLE STATUS LIKE 'wp_bp_album' "); //ACHTUNG nur für aktuelle Phpversion.sonst : SHOW  TABLE  STATUS  FROM 'tabellenname' verwenden!!!!!! 
                    $daten mysql_fetch_array($result);
                    $current_id "$daten[Auto_increment]"


                        
                    // Move the file to the uploads dir
                        
                    $new_file $uploads['path'] . "/$current_id.$filename"
                    was ne schwere geburt...
                    Zuletzt geändert von xserio; 04.07.2010, 01:19.

                    Kommentar

                    Lädt...
                    X