Plugin Directory

Changeset 2184011


Ignore:
Timestamp:
10/31/2019 04:51:54 PM (6 years ago)
Author:
roba87
Message:

RoBa87: Added image limit hook. It allows to limit the maximal number of images which could be added.

Location:
simple-multiple-featured-images/trunk
Files:
4 edited

Legend:

Unmodified
Added
Removed
  • simple-multiple-featured-images/trunk/admin/js/jquery.smfi.js

    r1962166 r2184011  
    44 * @author Roman Bauer.
    55 * @since  1.0.0
     6 * @since  1.1.0 Added image limit check.
    67 */
    78jQuery('document').ready( function( jQuery ){
    8    
     9
    910    // Search smfi metabox,
    1011    var metaBox = jQuery( '#smfi-metabox.postbox' );
    11    
     12
    1213    if( metaBox.length ) {
    13        
     14
     15
    1416        // Get error container which will be used for error reporting.
    1517        var errorContainer = metaBox.find( '#smfi-error-container' );
    16        
     18
    1719        // Get add image button.
    1820        var addNewImgBtn = metaBox.find( '#smfi-add-new-img-btn' );
    19        
     21
    2022        // Get image container.
    2123        var imgContainer = metaBox.find( '.smfi-img-container' );
    22        
     24
     25        // Get image limit.
     26        var imgLimitContainer = metaBox.find( '#smfi-img-limit' );
     27        var imgLimit = parseInt( imgLimitContainer.attr( 'value' ), 10 );
     28
     29        // Get post id.
     30        var postID = parseInt( metaBox.find( '#smfi-post-id' ).attr( 'value' ), 10 );
     31
    2332        /*
    2433         * Open media frame as soon as the add new image button was clicked.
    2534         * This allows the user to add a new image from the media library.
    2635         */
    27         de.smfi.MediaFrameManager.openMediaFrameOnAddBtnClick( addNewImgBtn, imgContainer, errorContainer );
     36        de.smfi.MediaFrameManager.openMediaFrameOnAddBtnClick( postID, addNewImgBtn, imgContainer, imgLimit, errorContainer );
    2837
    2938        // Enable removal and modification of existing images.
    3039        imgContainer.find( '.smfi-img' ).each( function( index, element ) {
    31            
     40
    3241            /*
    3342             * Open media frame as soon as an existing image was clicked.
     
    3544             */
    3645            de.smfi.MediaFrameManager.openMediaFrameOnImgClick( jQuery( element ), errorContainer );
    37            
     46
    3847            // Remove image as soon as its remove button was clicked.
    3948            de.smfi.MediaFrameManager.removeImgOnBtnClick( jQuery( element ).siblings( '.smfi-remove-img-btn' ) );
     
    4453var de = de || {
    4554    smfi : {
    46        
     55
    4756        ImageAddedListener : [],
    48        
     57
    4958        ImageRemovedListener : [],
    50        
     59
    5160        /**
    5261         * Contains translated textes for the UI. If no translation available a default one is used.
     
    5867         */
    5968        UIText : {
    60            
     69
    6170            /**
    6271             * The title for the media frame.
     
    6877             */
    6978            mediaFrameTitle: typeof smfi_translation_object !== 'undefined' ? smfi_translation_object.media_frame_title : 'Select image',
    70            
     79
    7180            /**
    7281             * The text for the media frame add button.
     
    7988            mediaFrameAddBtnTxt: typeof smfi_translation_object !== 'undefined' ? smfi_translation_object.media_frame_add_btn_txt : 'Add image',
    8089        },
    81        
     90
    8291        /**
    8392         * Helper in context of working with images.
     
    8998         */
    9099        ImageHelper : {
    91            
     100
    92101            /**
    93102             * Compared the ID of the given image with the given id.
     
    104113                var imgWrapper = img.parent();
    105114                var hiddenInputWithImgID = imgWrapper.find( '[name="smfi-img-ids[]"]' );
    106                
     115
    107116                var parsedImgId = parseInt( hiddenInputWithImgID.attr( 'value'), 10 );
    108117                var parsedIdToCompare = parseInt( idToCompare, 10 );
    109                
     118
    110119                if( Number.isNaN( parsedImgId ) || Number.isNaN( parsedIdToCompare ) ) {
    111120                    return false;
     
    114123            }
    115124        },
    116        
     125
    117126        /**
    118127         * Handles the error handling.
     
    128137             * Returns the default error message.
    129138             *
    130              * It uses the received translated default error message from the server. If no error message was transmitted then a default one is used
    131              * which is specified inside this function.
     139             * It uses the received translated default error message from the server. If no error message was transmitted then a default one is used.
    132140             *
    133141             * @since      1.0.0
     
    137145             */
    138146            getDefaultErrorMessageTxt : function() {
    139                 if(typeof smfi_translation_object.default_error_message !== 'undefined') {
     147                if( typeof smfi_translation_object.default_error_message !== 'undefined' ) {
    140148                    return smfi_translation_object.default_error_message;
    141149                } else {
     
    143151                }
    144152            },
    145            
     153
    146154            /**
    147155             * Returns the error message for failed adding an image.
    148156             *
    149              * It uses the received translated error message from the server. If no error message was transmitted then a default one is used
    150              * which is specified inside this function.
     157             * It uses the received translated error message from the server. If no error message was transmitted then a default one is used.
    151158             *
    152159             * @since      1.0.0
     
    156163             */
    157164            getAddImageErrorMessage : function() {
    158                 if(typeof smfi_translation_object.add_image_error_message !== 'undefined') {
     165                if( typeof smfi_translation_object.add_image_error_message !== 'undefined' ) {
    159166                    return smfi_translation_object.add_image_error_message;
    160167                } else {
     
    162169                }
    163170            },
    164            
     171
    165172            /**
    166173             * Returns the error message for failed changing an image.
    167174             *
    168              * It uses the received translated error message from the server. If no error message was transmitted then a default one is used
    169              * which is specified inside this function.
     175             * It uses the received translated error message from the server. If no error message was transmitted then a default one is used.
    170176             *
    171177             * @since      1.0.0
     
    175181             */
    176182            getChangeImageErrorMessage : function() {
    177                 if(typeof smfi_translation_object.change_image_error_message !== 'undefined') {
     183                if( typeof smfi_translation_object.change_image_error_message !== 'undefined' ) {
    178184                    return smfi_translation_object.change_image_error_message;
    179185                } else {
     
    181187                }
    182188            },
    183            
     189
     190            /**
     191             * Returns the error message for an exceeded image limit.
     192             *
     193             * It uses the received translated error message from the server. If no error message was transmitted then a default one is used.
     194             *
     195             * @since      1.1.0
     196             * @access     private
     197             *
     198             * @return {string} Error message.
     199             */
     200            getImageLimitExceededErrorMessage : function() {
     201                if( typeof smfi_translation_object.image_limit_exceeded_error_message !== 'undefined' ) {
     202                    return smfi_translation_object.image_limit_exceeded_error_message;
     203                } else {
     204                    return getDefaultErrorMessageTxt();
     205                }
     206            },
     207
    184208            /**
    185209             * Shows the given error message inside the given error container.
     
    197221             */
    198222            showError : function( errorContainer, errorMessageTxt ) {
    199                
     223
    200224                // Create new error.
    201225                var newError = jQuery( document.createElement( 'div' ) );
    202226                newError.attr( 'class', 'notice notice-error is-dismissible' );
    203227                errorContainer.append( newError );
    204                
     228
    205229                // Create error message and append it to the error.
    206230                var errorMessage = jQuery( document.createElement( 'p' ) );
     
    210234                    errorMessage.text( this.getDefaultErrorMessageTxt() );
    211235                }
    212                
     236
    213237                newError.append( errorMessage );
    214                
     238
    215239                // Create close button which allows to remove the error message.
    216240                var closeBtn = jQuery( document.createElement( 'button' ) );
    217241                closeBtn.attr( 'class', 'notice-dismiss' );
    218242                newError.append( closeBtn );
    219                
     243
    220244                // Remove error message if close button was clicked.
    221245                closeBtn.click( function( event ) {
     
    227251                    } );
    228252                } );
    229                
     253
    230254                // Show error in the error container.
    231255                errorContainer.append( newError );
    232256            }
    233257        },
    234        
     258
    235259        /**
    236260         * Handles interaction with the media frame.
     
    242266         */
    243267        MediaFrameManager : {
    244                            
     268
    245269            /**
    246270             * Creates and returns a new media frame which allows to select images.
     
    252276             */
    253277            getNewMediaFrame : function() {
    254            
     278
    255279                // Accepts an optional object hash to override default values.
    256280                var mediaFrame = new wp.media.view.MediaFrame.Select( {
    257                    
     281
    258282                    // Modal title.
    259283                    title: de.smfi.UIText.mediaFrameTitle,
     
    288312                return mediaFrame;
    289313            },
    290            
     314
    291315            /**
    292316             * Adds a new image by the specified image ID.
    293317             *
    294318             * @since      1.0.0
    295              * @access     private
    296              *
    297              * @param {number} newImgID  The image ID of the new image.
    298              * @param {jQuery} imgContainer  The image container which contains all images.
    299              * @param {jQuery} errorContainer  The error container which can be used for reporting ocurred errors to the user.
    300              */
    301             addNewImg : function( newImgID, imgContainer, errorContainer) {
    302                
     319             * @since      1.1.0 Transmit also data for the image limit check on the server.
     320             * @access     private
     321             *
     322         * @param {number} newImgID  The image ID of the new image.
     323         * @param {jQuery} imgContainer  The image container which contains all images.
     324         * @param {number} postID  The ID of the current showed post.
     325         * @param {jQuery} errorContainer  The error container which can be used for reporting ocurred errors to the user.
     326             */
     327            addNewImg : function( newImgID, imgContainer, postID, errorContainer) {
     328
    303329                // Setup data for ajax request.
    304330                var requestData = {
    305                    
     331
    306332                    // Specify which ajax callback should be triggered on server side.
    307333                    'action': 'get_img_wrapper_html_by_ajax_as_json',
    308                    
     334
    309335                    // Transmit the received nonce back to server.
    310336                    'smfi_add_img_security': ajax_smfi_object.ajax_add_image_nonce,
    311                    
     337
     338                    /*
     339                    * Transmit the received post id of the current post back to server.
     340                    * It will be used on server side to check if it is possible to add more images to the current post.
     341                    */
     342                    'smfi_post_id': postID,
     343
    312344                    // ID of new image.
    313                     'smfi_img_id': newImgID
     345                    'smfi_img_id': newImgID,
     346
     347                    // Number of current images.
     348                    'smfi_number_of_images': imgContainer.children( '.smfi-img-wrapper' ).length
    314349                };
    315                
     350
    316351                // Make an ajax request and get the html of the new image.
    317352                mediaFrameManager = this;
     
    321356                    type:'POST',
    322357                    data: requestData,
    323                    
     358
    324359                    success: function( response ){
    325                        
     360
    326361                        if( response.hasOwnProperty( 'newImgHtml' ) ) {
    327362
    328363                            // Add new image wrapper into the DOM
    329364                            var newImgHtml = jQuery( response.newImgHtml ).prependTo( imgContainer );
    330                            
     365
    331366                            // Invoke all registered listener and let them do their stuff with the new image.
    332367                            for( var i = 0; i < de.smfi.ImageAddedListener.length; i++ ) {
     
    335370                                };
    336371                            }
    337                            
     372
    338373                            /*
    339374                             * Open media frame as soon as the new image was clicked.
     
    342377                            var newImg = newImgHtml.find( '.smfi-img' );
    343378                            mediaFrameManager.openMediaFrameOnImgClick( newImg, errorContainer );
    344                            
     379
    345380                            // Remove the new image as soon as its remove button was clicked.
    346381                            mediaFrameManager.removeImgOnBtnClick( newImg.siblings( '.smfi-remove-img-btn' ) );
    347382                        } else {
    348                            
     383
    349384                            var hasErrorMessage = response.hasOwnProperty( 'data' ) && response.data.hasOwnProperty( 'smfiErrorMessage' );
    350385                            if( hasErrorMessage ) {
     
    363398                });
    364399            },
    365            
     400
    366401            /**
    367402             * Updates an existing image with the new selected image by the user.
    368403             *
    369              * The user select the image via media frame. For this an ajax request is done. 
     404             * The user select the image via media frame. For this an ajax request is done.
    370405             * If the user selects the same image then no update will be executed.
    371406             *
     
    378413             */
    379414            updateImg : function( newImgID, oldImg, errorContainer) {
    380                
     415
    381416                // Setup data for ajax request.
    382417                var requestData = {
    383                    
     418
    384419                    // Specify which ajax callback should be triggered on server side.
    385420                    'action': 'get_img_html_by_ajax_as_json',
    386                    
     421
    387422                    // Transmit the received nonce back to server.
    388423                    'smfi_change_img_security': ajax_smfi_object.ajax_change_image_nonce,
    389                    
     424
    390425                    // ID of new image.
    391426                    'smfi_img_id': newImgID
    392427                };
    393                
     428
    394429                // Make an ajax request and get the html of the new image.
    395430                mediaFrameManager = this;
     
    399434                    type:'POST',
    400435                    data: requestData,
    401                    
     436
    402437                    success: function(response){
    403                        
     438
    404439                        if( response.hasOwnProperty( 'newImgHtml' ) ) {
    405                            
     440
    406441                            // Update the image ID in the hidden input.
    407442                            var imgWrapper = oldImg.parent();
    408443                            var hiddenInputWithImgID = imgWrapper.find( '[name="smfi-img-ids[]"]' );
    409444                            hiddenInputWithImgID.attr( 'value', newImgID );
    410                        
     445
    411446                            // Update image html.
    412447                            oldImg.replaceWith(response.newImgHtml);
     
    418453                            var img = imgWrapper.find( '.smfi-img' );
    419454                            mediaFrameManager.openMediaFrameOnImgClick( img, errorContainer );
    420                            
     455
    421456                        } else {
    422                            
     457
    423458                            var hasErrorMessage = response.hasOwnProperty( 'data' ) && response.data.hasOwnProperty( 'smfiErrorMessage' );
    424459                            if( hasErrorMessage ) {
     
    437472                });
    438473            },
    439                            
     474
    440475            /**
    441476             * Adds a listener which opens the media frame on clicking the add new image button.
     
    444479             *
    445480             * @since      1.0.0
     481             * @since      1.1.0 Added image limit check.
    446482             * @access     private
    447483             *
     
    449485             * @listens select
    450486             *
     487             * @param {number} postID  The ID of the current showed post.
    451488             * @param {jQuery} btn  The button.
    452489             * @param {jQuery} imgContainer  The image container.
     490             * @param {number} imgLimit  The image limit.
    453491             * @param {jQuery} errorContainer  The error container which should contain possible the error messages.
    454492             */
    455             openMediaFrameOnAddBtnClick : function( btn, imgContainer, errorContainer ) {
    456                
     493            openMediaFrameOnAddBtnClick : function( postID, btn, imgContainer, imgLimit, errorContainer ) {
     494
    457495                // Create new media frame
    458496                var mediaFrame = this.getNewMediaFrame();
    459                
     497
    460498                // Open the media frame if button was clicked.
    461499                btn.click( function( event ) {
    462500                    event.preventDefault();
    463                     mediaFrame.open();
    464                 } );
    465                
     501                    /*
     502                    * Check if the given image limit is valid.
     503                    * It is valid if it is an integer and greater than -1. -1 means that unlimited number of pictures can be added.
     504                    */
     505                    if( Number.isInteger( imgLimit ) && imgLimit >= -1 ) {
     506                        let numberOfImages = imgContainer.children( '.smfi-img-wrapper' ).length;
     507                        /*
     508                        * Allow adding another image if the image limit is set to -1 or the current number of images is below the image limit.
     509                        * A limit of -1 means that unlimited number of pictures can be added.
     510                        */
     511                        if( imgLimit === -1 || numberOfImages >= 0 && numberOfImages < imgLimit ) {
     512                            mediaFrame.open();
     513                        } else {
     514                            // Image limit is reached -> Show corresponding error message to the user.
     515                            de.smfi.ErrorHandler.showError( errorContainer, de.smfi.ErrorHandler.getImageLimitExceededErrorMessage() );
     516                        }
     517                    } else {
     518                        // Adding image failed because the image limit is invalid for some reason -> Show the default add image error.
     519                        de.smfi.ErrorHandler.showError( errorContainer, de.smfi.ErrorHandler.getAddImageErrorMessage() );
     520                    }
     521                } );
     522
    466523                // Add new image if something was selected by the user.
    467524                mediaFrameManager = this;
     
    470527                    // Get selected image
    471528                    var selectedAttachment = mediaFrame.state().get( 'selection' ).first().toJSON();
    472                    
     529
    473530                    if( typeof selectedAttachment.id !== 'undefined' ) {
    474531                        // Create new image wrapper which shows the new image.
    475                         mediaFrameManager.addNewImg( selectedAttachment.id, imgContainer, errorContainer );
     532                        mediaFrameManager.addNewImg( selectedAttachment.id, imgContainer, postID, errorContainer );
    476533                    } else {
    477                         // Show error with default error message.
     534                        // Show add image error.
    478535                        de.smfi.ErrorHandler.showError( errorContainer, de.smfi.ErrorHandler.getAddImageErrorMessage() );
    479536                    }
    480537                } );
    481                
    482             },
    483            
     538
     539            },
     540
    484541            /**
    485542             * Adds a listener which opens the media frame on clicking the given image.
     
    500557             */
    501558            openMediaFrameOnImgClick : function( img, errorContainer ) {
    502                
     559
    503560                // Create new media frame
    504561                var mediaFrame = this.getNewMediaFrame();
    505                
     562
    506563                // Open the media frame if image was clicked.
    507564                img.click( function( event ) {
     
    509566                    mediaFrame.open();
    510567                } );
    511                
     568
    512569                // Update the image if user select a new image via media frame.
    513570                mediaFrameManager = this;
    514571                mediaFrame.on( 'select', function() {
    515                    
     572
    516573                    // Get id of the new selected image
    517574                    var selectedAttachment = mediaFrame.state().get( 'selection' ).first().toJSON();
    518575                    var newImgID = selectedAttachment.id;
    519                    
     576
    520577                    if(typeof newImgID !== 'undefined') {
    521                        
     578
    522579                        // If the selected image is the same as the current image then no update is necessary.
    523580                        if(de.smfi.ImageHelper.hasImageId(img, newImgID)) {
    524581                            return;
    525582                        }
    526                        
     583
    527584                        // Update existing image by the new selected image.
    528585                        mediaFrameManager.updateImg( newImgID, img, errorContainer );
     
    532589                    }
    533590                } );
    534                
     591
    535592                // Preselect the clicked image inside the opened media frame.
    536593                mediaFrame.on( 'open',function() {
    537                    
     594
    538595                    // Get image ID from hidden input
    539596                    var imgWrapper = img.parent();
    540597                    var hiddenInputWithImgID = imgWrapper.find( '[name="smfi-img-ids[]"]' );
    541598                    var imgID = parseInt( hiddenInputWithImgID.attr( 'value' ) , 10);
    542                    
     599
    543600                    if( Number.isInteger( imgID ) && imgID > 0 ) {
    544                        
    545                         /* 
     601
     602                        /*
    546603                         *  Get/Create media frame attachment by using the image ID.
    547604                         *  The attachment can be used to set the selection inside the opened media frame properly.
     
    549606                        attachment = wp.media.attachment(imgID);
    550607                        attachment.fetch();
    551                        
     608
    552609                        // Get current media frame selection and add the image attachment to it.
    553610                        if( attachment !== 'undefined') {
     
    557614                        }
    558615                    }
    559                    
     616
    560617                    /*
    561618                     * If preselection failed then just log the error.
    562619                     * I think it does not necessary to show this error to the user because it is not critical enough.
    563620                     * The user can continue working without a preselection.
    564                      */                     
     621                     */
    565622                    console.log('SMFI Plugin: Could not preselect image in media frame.');
    566623                } );
    567624            },
    568            
     625
    569626            /**
    570627             * Adds a click listener to the given button which removes the image it belongs to.
     
    579636            removeImgOnBtnClick : function( removeBtn ) {
    580637                removeBtn.click( function( event ) {
    581                    
     638
    582639                    event.preventDefault();
    583                    
     640
    584641                    // Remove the entire image container which is the parent of the remove button.
    585642                    var removedImageWrapper = jQuery( this ).parent().remove();
    586                    
     643
    587644                    // Invoke all registered listener and let them do their stuff in context of the removed image.
    588645                    for( var i = 0; i < de.smfi.ImageRemovedListener.length; i++ ) {
  • simple-multiple-featured-images/trunk/languages/simple-multiple-featured-images-de_DE.po

    r1971107 r2184011  
    66"Project-Id-Version: SMFI Pot v1.0.0\n"
    77"Report-Msgid-Bugs-To: Translator Name <translations@example.com>\n"
    8 "POT-Creation-Date: 2018-11-08 18:33+0100\n"
     8"POT-Creation-Date: 2019-10-31 15:45+0100\n"
    99"PO-Revision-Date: \n"
    1010"Last-Translator: \n"
     
    2121"_x:1,2c;_n:1,2;_n_noop:1,2;__ngettext:1,2;__ngettext_noop:1,2;_c,_nc:4c,1,2\n"
    2222"X-Poedit-Basepath: ..\n"
    23 "X-Generator: Poedit 2.1.1\n"
     23"X-Generator: Poedit 2.2.4\n"
    2424"X-Poedit-SearchPath-0: simple-multiple-featured-images.php\n"
    2525"X-Poedit-SearchPath-1: includes/class-smfi-dnd.php\n"
    2626"X-Poedit-SearchPath-2: includes/class-smfi-shortcodes.php\n"
    2727
    28 #: includes/class-smfi-dnd.php:186
     28#: includes/class-smfi-dnd.php:191
    2929msgid "The featured images could not be saved in the correct order."
    3030msgstr ""
     
    3939msgstr "SMFI Slider einfügen"
    4040
    41 #: simple-multiple-featured-images.php:268
     41#: simple-multiple-featured-images.php:304
    4242msgid "Select image"
    4343msgstr "Bild auswählen"
    4444
    45 #: simple-multiple-featured-images.php:269
    46 #: simple-multiple-featured-images.php:891
     45#: simple-multiple-featured-images.php:305
     46#: simple-multiple-featured-images.php:1023
    4747msgid "Add image"
    4848msgstr "Bild hinzufügen"
    4949
    50 #: simple-multiple-featured-images.php:398
     50#: simple-multiple-featured-images.php:450
    5151msgid "More Featured Images"
    5252msgstr "Weitere Beitragsbilder"
    5353
    54 #: simple-multiple-featured-images.php:642
     54#: simple-multiple-featured-images.php:711
    5555msgid "Saving the featured images failed."
    5656msgstr "Das Speichern der Beitragsbilder ist fehlgeschlagen."
    5757
    58 #: simple-multiple-featured-images.php:797
     58#: simple-multiple-featured-images.php:866
    5959msgid "An error occured."
    6060msgstr "Ein Fehler ist aufgetreten."
    6161
    62 #: simple-multiple-featured-images.php:811
     62#: simple-multiple-featured-images.php:880
    6363msgid "Adding the image failed."
    6464msgstr "Das Hinzufügen des Bildes ist fehlgeschlagen."
    6565
    66 #: simple-multiple-featured-images.php:828
     66#: simple-multiple-featured-images.php:896
    6767msgid "Changing the image failed."
    6868msgstr "Das Ändern des Bildes ist fehlgeschlagen."
    6969
    70 #: simple-multiple-featured-images.php:845
     70#: simple-multiple-featured-images.php:912
     71msgid ""
     72"Adding a picture failed because the limit of the maximum possible pictures "
     73"is reached. To add more pictures, the limit must be raised. "
     74msgstr ""
     75"Das Hinzufügen des Bildes ist fehlgeschlagen, weil die maximale Anzahl an "
     76"Bildern erreicht wurde. Um weitere Bilder hinzuzufügen, muss das Limit "
     77"angehoben werden. "
     78
     79#: simple-multiple-featured-images.php:928
     80msgid "Adding picture failed because of an invalid picture id. "
     81msgstr ""
     82"Das Hinzufügen des Bildes ist wegen einer ungültigen Bild-ID fehlgeschlagen. "
     83
     84#: simple-multiple-featured-images.php:944
     85msgid "Adding picture failed because of an invalid post id. "
     86msgstr ""
     87"Das Hinzufügen des Bildes ist wegen einer ungültigen Post-ID fehlgeschlagen. "
     88
     89#: simple-multiple-featured-images.php:960
     90msgid "Adding picture failed because of a security issue. "
     91msgstr "Das Hinzufügen des Bildes ist aus Sicherheitsgründen fehlgeschlagen. "
     92
     93#: simple-multiple-featured-images.php:977
    7194msgid ""
    7295"Please contact the responsible person for your website or the plugin "
     
    7699"Entwickler."
    77100
    78 #: simple-multiple-featured-images.php:1015
     101#: simple-multiple-featured-images.php:1148
    79102msgid "Remove image"
    80103msgstr "Bild entfernen"
  • simple-multiple-featured-images/trunk/simple-multiple-featured-images.php

    r2041599 r2184011  
    44Plugin URI:   https://roman-bauer-web.de/wordpress-plugin-smfi
    55Description:  Allows to add multiple featured images.
    6 Version:      1.0.6
     6Version:      1.1.0
    77Author:       Roman Bauer
    88Author URI:   https://roman-bauer-web.de/
     
    308308                    'add_image_error_message' => $this -> get_add_image_failed_error_message(),
    309309                    'change_image_error_message' => $this -> get_change_image_failed_error_message(),
     310                    'image_limit_exceeded_error_message' => $this -> get_image_limit_exceeded_error_message_on_adding_image(),
    310311                );
    311312
     
    381382         *
    382383         * @since 1.0.0
     384         * @since 1.1.0 Added image limit check and updated exception messages.
    383385         *
    384386         * @return json JSON with 'newImgHtml' property which contains the html or 'smfiErrorMessage' property which contains the error message
     
    393395                if( ! check_ajax_referer(   $this -> nonce_manager::NONCE_ACTION_IMG_ADD, $this -> nonce_manager::NONCE_NAME_IMG_ADD, $die_if_invalid ) ) {
    394396                    // Get an invalid nonce.
    395                     throw new Exception( "Received invalid nonce during add new image request via ajax" );
    396                 }
    397 
    398                 // Get requested image by received id and response the img html to the client.
     397                    throw new Exception( $this -> get_invalid_nonce_error_message_on_adding_image() );
     398                }
     399
     400                // Check if the received post id belongs to a existing post.
     401                $post_id = isset( $_POST['smfi_post_id'] ) && is_numeric( $_POST['smfi_post_id'] ) ? intval( $_POST['smfi_post_id'], 10 ) : -1;
     402                if( get_post_status( $post_id ) === false ) {
     403                    // Received invalid post id for some reason.
     404                    throw new Exception( $this -> get_invalid_post_id_error_message_on_adding_image() );
     405                }
     406
     407                // Check if it is possible to add more images.
     408                $number_of_current_images = isset( $_POST['smfi_number_of_images'] ) && is_numeric( $_POST['smfi_number_of_images'] ) ? absint( $_POST['smfi_number_of_images'], 10 ) : -1;
     409                $number_of_maximal_images = $this -> get_image_limit(); // returns -1 if there is not image limit.
     410                $image_limit_exist = $number_of_maximal_images !== -1;
     411                if( $image_limit_exist && $number_of_current_images >= $number_of_maximal_images ) {
     412                    // It is not allowed to add more images because the limit was reached.
     413                    throw new Exception( $this -> get_image_limit_exceeded_error_message_on_adding_image() . $number_of_current_images );
     414                }
     415
     416                // Get requested image by received image id and response the img html to the client.
    399417                $img_id = isset( $_POST['smfi_img_id'] ) && is_numeric( $_POST['smfi_img_id'] ) ? intval( $_POST['smfi_img_id'], 10 ) : -1;
    400418                if( $this -> validator -> is_valid_img_id( intval( $img_id, 10 ) ) ) {
     
    410428                } else {
    411429                    // Get an invalid image id.
    412                     throw new Exception( "Received invalid image id during add new image request via ajax" );
     430                    throw new Exception( $this -> get_invalid_image_id_error_message_on_adding_image() );
    413431                }
    414432
    415433            } catch( Exception $exception ) {
    416434                    // Response error message to user.
    417                     $this -> send_ajax_error_as_json();
     435                    $this -> send_ajax_error_as_json( $exception -> getMessage() );
    418436            }
    419437        }
     
    479497         *
    480498         * @since 1.0.0
     499         * @since 1.1.0 Add hidden input field with the post id. It will be used during ajax calls to check if more images can be added to this post.
    481500         *
    482501         * @param WP_Post $post Current post object.
     
    486505            // Set nonce for this metabox.
    487506            wp_nonce_field( $this -> nonce_manager::NONCE_ACTION_METABOX  . $post->ID, $this -> nonce_manager::NONCE_NAME_METABOX );
     507
     508            /*
     509            * Transmit the ID of the current post to the client.
     510            * The ID is used on ajax calls to tell the server which specific post the call relates to.
     511            * This is necessary because by default it is not known at ajax calls which post is currently being processed.
     512            * The ID ist used, for example, to check if more images can be added to the corresponding post.
     513            */
     514            echo '<input id= "smfi-post-id" name="post-id" type="hidden" value="' . esc_attr( get_the_ID() ) . '">';
    488515
    489516            // Create and echo the html.
     
    712739
    713740        /**
    714          * Returns the public API which can be used by external programs to work with the featured images plugin.
    715          *
    716          * @since 1.0.0
    717          *
    718          * @return SMFI_Public_API The API.
     741         * Returns the meta key which is used inside the database for storing the image data.
     742         *
     743         * @since 1.0.0
     744         *
     745         * @return string Meta key.
    719746        */
    720747        public function get_db_meta_key() {
     
    860887        }
    861888
    862 
    863889        /**
    864890         * Returns the error message for the failed changing of an image.
     
    872898            $errorDesc = esc_html__(
    873899                            'Changing the image failed.' ,
     900                            'simple-multiple-featured-images' );
     901
     902            return 'Simple Multiple Featured Images Plugin: '  . $errorDesc . ' ' .  $this -> get_default_error_instruction();
     903        }
     904
     905        /**
     906         * Returns the error message for an exceeded image limit during adding a new image.
     907         *
     908         * @since 1.1.0
     909         *
     910         * @return string The escaped and translated error message.
     911        */
     912        private function get_image_limit_exceeded_error_message_on_adding_image() {
     913
     914            $errorDesc = esc_html__(
     915                            'Adding a picture failed because the limit of the maximum possible pictures is reached. To add more pictures, the limit must be raised. ' ,
     916                            'simple-multiple-featured-images' );
     917
     918            return 'Simple Multiple Featured Images Plugin: '  . $errorDesc . ' ' .  $this -> get_default_error_instruction();
     919        }
     920
     921        /**
     922         * Returns the error message for an invalid image id during adding a new image.
     923         *
     924         * @since 1.1.0
     925         *
     926         * @return string The escaped and translated error message.
     927        */
     928        private function get_invalid_image_id_error_message_on_adding_image() {
     929
     930            $errorDesc = esc_html__(
     931                            'Adding picture failed because of an invalid picture id. ' ,
     932                            'simple-multiple-featured-images' );
     933
     934            return 'Simple Multiple Featured Images Plugin: '  . $errorDesc . ' ' .  $this -> get_default_error_instruction();
     935        }
     936
     937        /**
     938         * Returns the error message for an invalid post id during adding a new image.
     939         *
     940         * @since 1.1.0
     941         *
     942         * @return string The escaped and translated error message.
     943        */
     944        private function get_invalid_post_id_error_message_on_adding_image() {
     945
     946            $errorDesc = esc_html__(
     947                            'Adding picture failed because of an invalid post id. ' ,
     948                            'simple-multiple-featured-images' );
     949
     950            return 'Simple Multiple Featured Images Plugin: '  . $errorDesc . ' ' .  $this -> get_default_error_instruction();
     951        }
     952
     953        /**
     954         * Returns the error message for an invalid nonce during adding a new image.
     955         *
     956         * @since 1.1.0
     957         *
     958         * @return string The escaped and translated error message.
     959        */
     960        private function get_invalid_nonce_error_message_on_adding_image() {
     961
     962            $errorDesc = esc_html__(
     963                            'Adding picture failed because of a security issue. ' ,
    874964                            'simple-multiple-featured-images' );
    875965
     
    9361026                $title = esc_attr__( 'Add image', 'simple-multiple-featured-images' ) . '">' . esc_html__( 'Add image', 'simple-multiple-featured-images' );
    9371027                $output .= '<button id= "smfi-add-new-img-btn" class="button" title="' . $title . '</button>';
     1028                $output .= '<input id= "smfi-img-limit" name="img-limit" type="hidden" value="' . esc_attr( $this -> get_image_limit() ) . '">';
    9381029            $output .= '</div>';
    9391030            return $output;
     
    10731164            return '<input name="' . $this -> hidden_input_name_img_ids . '[]" type="hidden" value="' . esc_attr( $img_id ) . '">';
    10741165        }
     1166
     1167        /**
     1168         * Returns the image limit. The addition of new featured images will be prevented when the limit is exceeded.
     1169         *
     1170         * @since 1.1.0
     1171         *
     1172         * @return int The image limit.
     1173        */
     1174        private function get_image_limit() {
     1175
     1176            /*
     1177            * By default there is not image limit.
     1178            * It is possible to add as many pictures as you like.
     1179            * This will is represented by -1.
     1180            */
     1181            $default_img_limit = -1;
     1182
     1183            /**
     1184             * Filters the image limit.
     1185             *
     1186             * @since 1.1.0
     1187             *
     1188             * @param array The number of featured images which should be added.
     1189             */
     1190            $img_limit = apply_filters( 'smfi_img_limit', $default_img_limit );
     1191            return is_int ( $img_limit ) && $img_limit > 0 ? $img_limit : $default_img_limit;
     1192        }
    10751193    }
    10761194
Note: See TracChangeset for help on using the changeset viewer.