Plugin Directory

Changeset 2521947


Ignore:
Timestamp:
04/27/2021 09:01:29 AM (5 years ago)
Author:
pressmate
Message:

2.3.1 - Added bulk media migration

Location:
makestories-helper/trunk
Files:
5 edited

Legend:

Unmodified
Added
Removed
  • makestories-helper/trunk/api/publish.php

    r2516559 r2521947  
    3838        if( ! ( function_exists( 'wp_get_attachment_by_post_name' ) ) ) {
    3939            function wp_get_attachment_by_post_name( $post_name ) {
     40                $id = post_exists($post_name);
    4041                $args           = array(
    4142                    'posts_per_page' => 1,
    4243                    'post_type'      => 'attachment',
    43                     'name'           => trim( $post_name ),
     44                    'p'           => $id,
    4445                );
    4546
     
    7980                if($getAttachment) {
    8081                    $attach_id = $getAttachment->ID;
     82                }else{
     83                    $mediaLinksToDownload[] = [
     84                        "imageurl" => $imageurl,
     85                        "filename" => $filename,
     86                        "atta_title" => $atta_title,
     87                        "into_else" => true,
     88                        "exists" => post_exists($atta_title),
     89                        "i" => wp_get_attachment_by_post_name( $atta_title ),
     90                    ];
    8191                }
    8292
     
    138148    if(
    139149        isset($_REQUEST['imageurl']) &&
    140         isset($_REQUEST['filename']) &&
    141         isset($_REQUEST['atta_title']) &&
    142150        isset($_REQUEST['post_id'])
    143151    ){
    144152        $imageurl = $_REQUEST['imageurl'];
    145         $filename = $_REQUEST['filename'];
    146         $atta_title = $_REQUEST['atta_title'];
     153        $atta_title = basename( $imageurl );
     154
     155        if(isset($_REQUEST['atta_title'])){
     156            $atta_title = $_REQUEST['atta_title'];
     157        }
     158
     159        if(isset($_REQUEST['filename'])){
     160            $filename = $_REQUEST['filename'];
     161        }else{
     162            $name = $imageurl;
     163            $nameExploded = explode("?",$imageurl);
     164            if(count($nameExploded)){
     165                $nameExploded = $nameExploded[0];
     166            }
     167            $nameExploded = explode("/",$nameExploded);
     168            if(count($nameExploded)){
     169                $name = $nameExploded[count($nameExploded) - 1];
     170            }
     171            $filename = date('dmY').''.(int) microtime(true).basename($name);
     172        }
     173
    147174        $postId = $_REQUEST['post_id'];
    148175        include_once( ABSPATH . 'wp-admin/includes/image.php' );
    149176        if( ! ( function_exists( 'wp_get_attachment_by_post_name' ) ) ) {
    150177            function wp_get_attachment_by_post_name( $post_name ) {
     178                $id = post_exists($post_name);
    151179                $args           = array(
    152180                    'posts_per_page' => 1,
    153181                    'post_type'      => 'attachment',
    154                     'name'           => trim( $post_name ),
     182                    'p'           => $id,
    155183                );
    156184
     
    200228                "ID" => $postId,
    201229            ]);
     230
     231            //CHeck in post meta data
     232            $meta = get_post_meta($postId, "publisher_details", true);
     233            try{
     234                $meta = json_decode($meta, true);
     235                $propertiesToAdd = [
     236                    "publisher-logo-src",
     237                    "poster-portrait-src",
     238                    "poster-landscape-src",
     239                    "poster-square-src",
     240                ];
     241                foreach ($propertiesToAdd as $prop){
     242                    if(isset($meta[$prop]) && $meta[$prop] == $imageurl){
     243                        $meta[$prop] = $permalink;
     244                    }
     245                }
     246                update_post_meta( $postId, "publisher_details", json_encode($meta));
     247            }catch(Exception $e){
     248                //Do Nothing
     249            }
     250
    202251        }
    203252    }
     
    329378add_action("wp_ajax_ms_change_story_slug", "ms_change_story_slug");
    330379
     380function ms_verify_media_in_story(){
     381//    ms_protect_ajax_route();
     382    $media = [];
     383    if(isset($_REQUEST['post_id'])){
     384        $postId = $_REQUEST['post_id'];
     385        $post = get_post($postId);
     386        $content = $post->post_content;
     387        $doc = new DOMDocument();
     388        $doc->loadHTML($content);
     389        $mediaInStory = [];
     390
     391        //Gather all Image element sources
     392        $images = $doc->getElementsByTagName("amp-img");
     393        foreach ($images as $image){
     394            $mediaInStory[] = $image->getAttribute("src");
     395        }
     396
     397        //Gather all Video element sources
     398        $videos = $doc->getElementsByTagName("amp-video");
     399        foreach ($videos as $video){
     400            $mediaInStory[] = $video->getAttribute("poster");
     401            $sources = $video->getElementsByTagName("source");
     402            foreach ($sources as $source){
     403                $mediaInStory[] = $source->getAttribute("src");
     404            }
     405        }
     406
     407        //Gather all link elements
     408        $links = $doc->getElementsByTagName("link");
     409        foreach ($links as $link){
     410            $rel = $link->getAttribute("rel");
     411            if(strpos($rel, "icon") !== false){
     412                $mediaInStory[] = $link->getAttribute("href");
     413            }
     414        }
     415
     416        //Gather all meta elements
     417        $metas = $doc->getElementsByTagName("meta");
     418        foreach ($metas as $meta){
     419            $name = $meta->getAttribute("property");
     420            if(empty($name)){
     421                $name = $meta->getAttribute("name");
     422            }
     423            if($name && strpos($name, ":image")){
     424                $mediaInStory[] = $meta->getAttribute("content");
     425            }
     426        }
     427
     428        //Add images from JsonLd
     429        $scripts = $doc->getElementsByTagName("script");
     430        if(count($scripts)){
     431            foreach ($scripts as $script){
     432                $type = $script->getAttribute("type");
     433                if($type === "application/ld+json"){
     434                    try{
     435                        $json = json_decode($script->nodeValue, true);
     436                        if($json && is_array($json)){
     437                            if(isset($json['image']) && is_array($json['image'])){
     438                                foreach ($json['image'] as $url){
     439                                    $mediaInStory[] = $url;
     440                                }
     441                            }
     442                            if(
     443                                isset($json['publisher']) &&
     444                                is_array($json['publisher']) &&
     445                                isset($json['publisher']['logo']) &&
     446                                is_array($json['publisher']['logo']) &&
     447                                isset($json['publisher']['logo']["@type"]) &&
     448                                isset($json['publisher']['logo']["url"]) &&
     449                                $json['publisher']['logo']["@type"] === "ImageObject"
     450                            ){
     451                                $mediaInStory[] = $json['publisher']['logo']["url"];
     452                            }
     453                        }
     454                    }catch(Exception $e){
     455                        //Do Nothing
     456                    }
     457                }
     458            }
     459        }
     460
     461        //Posters and other details
     462        $ampStory = $doc->getElementsByTagName("amp-story");
     463        if(count($ampStory)){
     464            $ampStory = $ampStory->item(0);
     465            $propertiesToAdd = [
     466                "publisher-logo-src",
     467                "poster-portrait-src",
     468                "poster-landscape-src",
     469                "poster-square-src",
     470            ];
     471            foreach ($propertiesToAdd as $prop){
     472                $mediaInStory[] = $ampStory->getAttribute($prop);
     473            }
     474        }
     475
     476        //CHeck in post meta data
     477        $meta = get_post_meta($postId, "publisher_details", true);
     478        try{
     479            $meta = json_decode($meta, true);
     480            $propertiesToAdd = [
     481                "publisher-logo-src",
     482                "poster-portrait-src",
     483                "poster-landscape-src",
     484                "poster-square-src",
     485            ];
     486            foreach ($propertiesToAdd as $prop){
     487                if(isset($meta[$prop])){
     488                    $mediaInStory[] = $meta[$prop];
     489                }
     490            }
     491        }catch(Exception $e){
     492            //Do Nothing
     493        }
     494
     495
     496
     497        //Sanitize all the media urls to take only the MS hosted ones
     498        foreach ($mediaInStory as $imageUrl){
     499            foreach (MS_DOMAINS as $domain){
     500                if(strpos($imageUrl, $domain) !== false){
     501                    $media[] = $imageUrl;
     502                    break;
     503                }
     504            }
     505        }
     506    }
     507    header("Content-Type: application/json");
     508    print_r(json_encode($media));
     509    die();
     510}
     511
     512add_action("wp_ajax_ms_verify_media_in_story", "ms_verify_media_in_story");
     513
    331514function ms_change_story_slug(){
    332515    ms_protect_ajax_route();
  • makestories-helper/trunk/config.php

    r2516559 r2521947  
    7171    "roles" => ["editor", "author", "administrator"],
    7272]);
     73
     74define("MS_DOMAINS", [
     75    "storage.googleapis.com/makestories",
     76    "makestories.io",
     77    "images.unsplash.com",
     78    "storyasset.link",
     79]);
  • makestories-helper/trunk/helpers.php

    r2498952 r2521947  
    4040        }
    4141    }
     42    $options['forceUploadMedia'] = false;
    4243    return $defaults;
    4344}
  • makestories-helper/trunk/makestories.php

    r2516560 r2521947  
    44Plugin URI:     https://www.notion.so/MakeStories-WordPress-Plugin-Set-Up-Guide-d903e700c9204ef08f9751bb4a101068
    55Description:    Visual storytelling for WordPress. Made possible by MakeStories.
    6 Version:        2.3
     6Version:        2.3.1
    77Author:         MakeStories Team
    88Author URI:     http://makestories.io
  • makestories-helper/trunk/pages/category-structure.php

    r2498952 r2521947  
    8888            </tr>
    8989            <tr>
     90                <th scope="row"><label>Update Story Media</label></th>
     91                <td>
     92                    <p class="submit">
     93                        <input type="submit" name="submit" id="submit" class="button button-primary" value="Save Changes"/>
     94                    </p>
     95                </td>
     96            </tr>
     97        </table>
     98        </form>
     99        <table class="form-table" role="presentation">
     100
     101            <tbody>
     102            <tr>
    90103                <td colspan="2">
    91104                    <hr/>
     
    93106            </tr>
    94107            <tr>
    95                 <th scope="row"><label for="categories">Clear Media Details: </label></th>
    96                 <td>
    97                     <input type="checkbox" <?php if($options['forceUploadMedia']){ echo "checked"; } ?> id="clear-meta" name="forceUploadMedia" value="clear" />
    98                     <p class="description" id="tagline-description">In some cases of server configuration, there was an issue with media not saving correctly. And the algoritm for media saving is that it should save only once, so in order to make it work correctly, we have created this option which will ignore the current media and when publishing new images will be added to your media by MakeStories. This is done for future stories publishing to work correctly.
    99                         If you are facing such an issue, click on the above checkbox and then submit the form. Also remember to turn it off after you have published the story which was to be force updated.</p>
     108                <th scope="row"><label>Update Story Media</label></th>
     109                <td>
     110                    <p class="description">If you think that your story media is not coming from your own domain, click this button. If all the things are already set, this will not affect you.</p>
     111                    <p id="summary"></p>
     112                    <p class="submit">
     113                        <input type="submit" id="run-media-updates" name="submit" class="button button-primary" value="Run Updates"/>
     114                    </p>
    100115                </td>
    101116            </tr>
    102117        </table>
    103         <p class="submit">
    104             <input type="submit" name="submit" id="submit" class="button button-primary" value="Save Changes"/>
    105         </p>
    106         </form>
     118
    107119    </div>
    108120    <script>
    109121        $(document).ready(function(){
     122
     123            let baseApiUrl = "<?php echo admin_url('admin-ajax.php') ?>";
     124            let nonce = "<?php echo wp_create_nonce( MS_NONCE_REFERRER ) ?>";
     125            let alreadyRunning = false;
    110126            $("#clear-meta").on("change", function(e){
    111127                if($(this).prop("checked") && !confirm("Are you sure you want to force upload your media while publishing?. This will not affect the existing media but some media items may end up repeating themselves")){
    112128                    $(this).prop("checked", false);
    113129                }
     130            });
     131            $("#run-media-updates").on("click", function(){
     132                if(alreadyRunning){
     133                    return false;
     134                }
     135                alreadyRunning = true;
     136                let button = $(this);
     137                let summary = $("#summary");
     138                $.ajax({
     139                    url: baseApiUrl,
     140                    data: {
     141                        _wpnonce: nonce,
     142                        action: "ms_get_published_posts",
     143                    },
     144                    success: function(data){
     145                        if(data && data.posts){
     146                            let numOfPosts = Object.keys(data.posts).length;
     147                            let summaryPrepend = `Found ${numOfPosts} posts. Now fetching media details and updating each post.`;
     148                            summary.html(summaryPrepend);
     149                            let chain = Promise.resolve();
     150                            let index = 1;
     151                            Object.values(data.posts).map(({ post_id }) => {
     152                                chain = chain.then(() => updateMediaForStory(post_id, summaryPrepend+`<br>Processing story ${index++} out of ${numOfPosts}`));
     153                            });
     154                            chain.then(() => {
     155                                summary.html("All media updated. Thank you!")
     156                            });
     157                        }
     158                    },
     159                    error: function(){
     160                        button.html("Run Updates");
     161                        summary.html("Some error occurred while fetching story details. Please try again in some time!");
     162                    }
     163                });
     164
     165                button.html("Running Updates...");
     166                summary.html("Fetching story details. Please do not leave the page");
     167
     168
     169                function updateMediaForStory(post_id, summaryPrepend){
     170                    return new Promise(resolve => {
     171                        $.ajax({
     172                            url: baseApiUrl,
     173                            data: {
     174                                _wpnonce: nonce,
     175                                post_id,
     176                                action: "ms_verify_media_in_story",
     177                            },
     178                            success: function(media){
     179                                if(media && Array.isArray(media) && media.length){
     180                                    let chain = Promise.resolve();
     181                                    let index = 1;
     182                                    media.map((url) => {
     183                                        chain = chain.then(() => {
     184                                            summary.html(`${summaryPrepend}.<br/>Downloading media: ${index++} out of ${media.length}`);
     185                                            return replaceMediaInStory(url, post_id)
     186                                        });
     187                                    });
     188                                    chain.then(resolve);
     189                                }else{
     190                                    resolve();
     191                                }
     192                            },
     193                            error: resolve,
     194                        });
     195                    });
     196                }
     197
     198                function replaceMediaInStory(imageurl, post_id){
     199                    return new Promise(resolve => {
     200                        $.ajax({
     201                            url: baseApiUrl,
     202                            data: {
     203                                _wpnonce: nonce,
     204                                action: "ms_upload_image_to_media_library",
     205                                post_id,
     206                                imageurl,
     207                            },
     208                            success: resolve,
     209                            error: resolve,
     210                        });
     211                    })
     212                }
     213
    114214            });
    115215        })
Note: See TracChangeset for help on using the changeset viewer.