Plugin Directory

Changeset 1276630


Ignore:
Timestamp:
10/30/2015 09:12:21 PM (10 years ago)
Author:
motaword
Message:

Releasing new version! MUST UPGRADE. Also tagging 1.1.0 and 1.1.0 versions.

Location:
motaword/trunk
Files:
8 edited

Legend:

Unmodified
Added
Removed
  • motaword/trunk/README.txt

    r1273964 r1276630  
    55Requires at least: 3.0.1
    66Tested up to: 4.3.1
    7 Stable tag: 1.0
     7Stable tag: 1.1.0
    88License: GPLv2 or later
    99License URI: http://www.gnu.org/licenses/gpl-2.0.html
     
    6565== Changelog ==
    6666
    67 = 1.0 =
     67= 1.1.0 =
     68* Improved content handling by switching from JSON-only to JSON and HTML files. This allows better quotes and TM management for complex post contents.
     69* Various stability improvements in API access and WordPress cache management.
     70
     71= 1.0.0 =
    6872* Initial version.
    6973
    7074== Upgrade Notice ==
    7175
    72     .
    73 
    74    
    75  
     76= 1.1.0 =
     77Upgrading to version 1.1.0 is HIGHLY RECOMMENDED. It provides fundamental changes with API interaction.
  • motaword/trunk/admin/class-motaword-admin.php

    r1271940 r1276630  
    6464     *      to this:
    6565     *          http://prntscr.com/8o10kd
     66     *
    6667     * @var array
    6768     */
     
    7071    /**
    7172     * Should we exit when an error occurs? If we exit, we will out print our logo image.
     73     *
    7274     * @var bool
    7375     */
     
    7577    /**
    7678     * When true, we will show an error icon instead of a message. This icon will have the message as a title.
     79     *
    7780     * @var bool
    7881     */
     
    105108     *
    106109     * @param      string $motaword The name of this plugin.
    107      * @param      string $version The version of this plugin.
     110     * @param      string $version  The version of this plugin.
    108111     */
    109112    public function __construct( $motaword, $version ) {
     
    119122        }
    120123
    121         if(!!get_option( static::$options['sandbox'] ) || !!get_site_option( static::$options['sandbox'] )) {
    122             MotaWord_DB::$meta_prefix = MotaWord_DB::$meta_prefix.'sandbox_';
     124        if ( ! ! get_option( static::$options['sandbox'] ) || ! ! get_site_option( static::$options['sandbox'] ) ) {
     125            MotaWord_DB::$meta_prefix = MotaWord_DB::$meta_prefix . 'sandbox_';
    123126        }
    124127    }
     
    128131     */
    129132    public function enqueue_styles() {
    130         wp_enqueue_style( $this->motaword, plugin_dir_url( __FILE__ ) . 'css/motaword-admin.css', array(), $this->version, 'all' );
     133        wp_enqueue_style( $this->motaword, plugin_dir_url( __FILE__ ) . 'css/motaword-admin.css', array(),
     134            $this->version, 'all' );
    131135    }
    132136
     
    135139     */
    136140    public function enqueue_scripts() {
    137         wp_enqueue_script( $this->motaword, plugin_dir_url( __FILE__ ) . 'js/motaword-admin.js', array('jquery'), $this->version, false );
     141        wp_enqueue_script( $this->motaword, plugin_dir_url( __FILE__ ) . 'js/motaword-admin.js', array( 'jquery' ),
     142            $this->version, false );
    138143    }
    139144
     
    213218        if ( ! ! isset( $progress['languages'] ) ) {
    214219            $targetLanguages = array_filter( $targetLanguages, function ( $language ) use ( $progress ) {
    215                 if ( ( in_array( $language->code, $progress['languages'] )
    216                     || @$progress['projects'][0]->source_language === $language->code )
     220                if ( ( in_array( $language->code,
     221                        $progress['languages'] ) || @$progress['projects'][0]->source_language === $language->code )
    217222                ) {
    218223                    return false;
     
    240245            $pll_mw_languages   = array_map( array( $this, 'mapLanguageCode' ), $pll_languages );
    241246
    242             $targetLanguages = array_filter( $targetLanguages, function ( $language ) use ( $progress, $pll_mw_languages ) {
    243                 if ( ! in_array( $language->code, $pll_mw_languages ) ) {
    244                     return false;
    245                 }
    246 
    247                 return true;
    248             } );
     247            $targetLanguages = array_filter( $targetLanguages,
     248                function ( $language ) use ( $progress, $pll_mw_languages ) {
     249                    if ( ! in_array( $language->code, $pll_mw_languages ) ) {
     250                        return false;
     251                    }
     252
     253                    return true;
     254                } );
    249255
    250256            // If there is left no other languages supported by Polylang configuration to translate...
     
    252258
    253259                if ( ! $progress ) {
    254                     echo '<div class="mw_warning">' . __( 'Save this post in order to send to MotaWord for translation.', 'motaword' ) . '</div>';
     260                    echo '<div class="mw_warning">' . __( 'Save this post in order to send to MotaWord for translation.',
     261                            'motaword' ) . '</div>';
    255262                } else {
    256263                    echo $progress['html'];
     
    273280            echo '<input type="hidden" name="post_ids" id="post_ids" value="' . $wpPostId . '"/>';
    274281
    275             $targetBox      = '<select id="mw_target_language" name="target_language" style="' . ( $this->showSourceLanguage ? 'width:115px;' : 'width: 100%;' ) . '">';
     282            $targetBox      = '<select id="mw_target_language" name="target_language" style="' . ( $this->showSourceLanguage
     283                    ? 'width:115px;' : 'width: 100%;' ) . '">';
    276284            $targetSelected = false;
    277285
     
    285293
    286294                if ( ! $targetSelected && $code !== $mainSourceLanguage ) {
    287                     $targetBox .= '<option value="' . $code . '" selected="selected">' . __( $name, 'motaword' ) . '</option>';
     295                    $targetBox .= '<option value="' . $code . '" selected="selected">' . __( $name,
     296                            'motaword' ) . '</option>';
    288297                    $targetSelected = true;
    289298                } else {
     
    305314
    306315                    if ( ! ! $mainSourceLanguage && $code === $mainSourceLanguage ) {
    307                         $sourceBox .= '<option value="' . $code . '" selected="selected">' . __( $name, 'motaword' ) . '</option>';
     316                        $sourceBox .= '<option value="' . $code . '" selected="selected">' . __( $name,
     317                                'motaword' ) . '</option>';
    308318                    } else {
    309319                        $sourceBox .= '<option value="' . $code . '">' . __( $name, 'motaword' ) . '</option>';
     
    319329            }
    320330
    321             echo '<p style="text-align: center;"><a id="mw_start_link" href="' . plugin_dir_url( __FILE__ ) . 'get_quote.php" class="thickbox button button-primary button-large">' . __( 'Send to MotaWord', 'motaword' ) . '</a></p>';
     331            echo '<p style="text-align: center;"><a id="mw_start_link" href="' . plugin_dir_url( __FILE__ ) . 'get_quote.php" class="thickbox button button-primary button-large">' . __( 'Send to MotaWord',
     332                    'motaword' ) . '</a></p>';
    322333
    323334            if ( ! ! $progress && isset( $progress['html'] ) && ! ! $progress['html'] ) {
     
    350361            echo '<input name="pllMainPostTitle" id="pllMainPostTitle" type="hidden" value="' . $originalTitle . '" />';
    351362            echo '<input name="pllNewPostTitle" id="pllNewPostTitle" type="hidden" value="' . $newTitle . '" />';
    352             echo '<div class="mw_warning">' . __( 'Save this post in order to send to MotaWord for translation.', 'motaword' ) . '</div>';
     363            echo '<div class="mw_warning">' . __( 'Save this post in order to send to MotaWord for translation.',
     364                    'motaword' ) . '</div>';
    353365        } else {
    354366            // ===> New Post Page
    355             echo '<div class="mw_warning">' . __( 'Save this post in order to send to MotaWord for translation.', 'motaword' ) . '</div>';
     367            echo '<div class="mw_warning">' . __( 'Save this post in order to send to MotaWord for translation.',
     368                    'motaword' ) . '</div>';
    356369        }
    357370
     
    365378
    366379    protected function credentials_error() {
    367         $this->issue_error( sprintf(
    368             __( 'MotaWord API credentials that you provided are wrong. Please check them on <a href="%s">settings page</a>.', 'motaword' ),
    369             admin_url( 'options-general.php?page=motaword' )
    370         ) );
     380        $this->issue_error( sprintf( __( 'MotaWord API credentials that you provided are wrong. Please check them on <a href="%s">settings page</a>.',
     381            'motaword' ), admin_url( 'options-general.php?page=motaword' ) ) );
    371382    }
    372383
    373384    protected function issue_error( $message = null ) {
    374385        if ( ! $message ) {
    375             $message = __( 'We encountered an error while processing your request. Please try again or contact us at [email protected].', 'motaword' );
     386            $message = __( 'We encountered an error while processing your request. Please try again or contact us at [email protected].',
     387                'motaword' );
    376388        }
    377389
     
    416428        }
    417429
    418         $this->api = new MotaWord_API( $motawordPlugin->getOption( static::$options['client_id'] ), $motawordPlugin->getOption( static::$options['client_secret'] ),
     430        $this->api = new MotaWord_API( $motawordPlugin->getOption( static::$options['client_id'] ),
     431            $motawordPlugin->getOption( static::$options['client_secret'] ),
    419432            $motawordPlugin->getOption( static::$options['sandbox'] ) );
    420433
     
    495508            $htmlProgress .= '
    496509                <div class="mwProgress">
    497                     <p style="text-align: center; font-weight: bold;">' .
    498                 sprintf(
    499                     __( 'From %1$s to %2$s', 'motaword' ),
    500                     __( MotaWord_i18n::getLanguage( $projectDetail->source_language ), 'motaword' ),
    501                     implode( ', ', $targetLanguages )
    502                 ) . '
     510                    <p style="text-align: center; font-weight: bold;">' . sprintf( __( 'From %1$s to %2$s',
     511                    'motaword' ), __( MotaWord_i18n::getLanguage( $projectDetail->source_language ), 'motaword' ),
     512                    implode( ', ', $targetLanguages ) ) . '
    503513                </p>';
    504514
     
    507517            } else {
    508518                if ( (int) $projectProgress->translation < 100 ) {
    509                     $htmlProgress .= '<p>' . sprintf(
    510                             __( 'Translation progress: <strong>%d</strong>%%', 'motaword' ),
    511                             $projectProgress->translation
    512                         ) . '</p>';
     519                    $htmlProgress .= '<p>' . sprintf( __( 'Translation progress: <strong>%d</strong>%%', 'motaword' ),
     520                            $projectProgress->translation ) . '</p>';
    513521                } else {
    514522                    if ( (int) $projectProgress->proofreading < 100 ) {
    515                         $htmlProgress .= '<div class="mwProgress">' . sprintf(
    516                                 __( 'Translated and currently being proofread: <strong>%d</strong>%% completed.', 'motaword' ),
    517                                 $projectProgress->proofreading
    518                             ) . '</div>';
     523                        $htmlProgress .= '<div class="mwProgress">' . sprintf( __( 'Translated and currently being proofread: <strong>%d</strong>%% completed.',
     524                                'motaword' ), $projectProgress->proofreading ) . '</div>';
    519525                    } else {
    520                         $htmlProgress .= '<div class="mwProgress">' . __( 'Completed. Waiting to be finalized.', 'motaword' ) . '</div>';
     526                        $htmlProgress .= '<div class="mwProgress">' . __( 'Completed. Waiting to be finalized.',
     527                                'motaword' ) . '</div>';
    521528                    }
    522529                }
    523530            }
    524531
    525             $htmlProgress .= '<p style="text-align: right;"><em><small>' .
    526                 sprintf(
    527                     __( 'Translation by <a href="%s" target="_blank">MotaWord</a>', 'motaword' ),
    528                     'https://www.motaword.com'
    529                 )
    530                 . '</small></em></p></div>';
     532            $htmlProgress .= '<p style="text-align: right;"><em><small>' . sprintf( __( 'Translation by <a href="%s" target="_blank">MotaWord</a>',
     533                    'motaword' ), 'https://www.motaword.com' ) . '</small></em></p></div>';
    531534
    532535            if ( ( $i + 1 ) < count( $projects ) ) {
     
    586589     */
    587590    protected function get_cache( $category, $identifier = null ) {
    588         if ( ! isset( $category ) || ! $category
    589             || ! isset( $this->cache[ $category ] )
    590             || ( isset( $identifier )
    591                 && ( ! $identifier || ! isset( $this->cache[ $category ][ $identifier ] ) ) )
    592         ) {
     591        if ( ! isset( $category ) || ! $category || ! isset( $this->cache[ $category ] ) || ( isset( $identifier ) && ( ! $identifier || ! isset( $this->cache[ $category ][ $identifier ] ) ) ) ) {
    593592            return false;
    594593        }
     
    607606     *
    608607     * @param string $category
    609      * @param mixed $identifier
    610      * @param mixed $value
     608     * @param mixed  $identifier
     609     * @param mixed  $value
    611610     *
    612611     * @return bool
     
    640639            include_once __DIR__ . "/../includes/language-map.php";
    641640
    642             if( isset( $map ) ) {
    643                 $this->languages         = $map;
    644             }
    645 
    646             if( isset( $reversedMap ) ) {
     641            if ( isset( $map ) ) {
     642                $this->languages = $map;
     643            }
     644
     645            if ( isset( $reversedMap ) ) {
    647646                $this->reversedLanguages = $reversedMap;
    648647            }
     
    662661
    663662    public function register_network_settings() {
    664         add_submenu_page( 'settings.php', __('MotaWord Settings', 'motaword'), 'MotaWord', 'manage_network_plugins', 'motaword', array($this, 'network_settings'));
     663        add_submenu_page( 'settings.php', __( 'MotaWord Settings', 'motaword' ), 'MotaWord', 'manage_network_plugins',
     664            'motaword', array( $this, 'network_settings' ) );
    665665    }
    666666
     
    679679
    680680        $defaultType   = 'json';
    681         $wpPostIds     = isset($_REQUEST['post_ids']) ? $_REQUEST['post_ids'] : array();
    682         $sourceLang    = isset($_REQUEST['source_language']) ? sanitize_text_field( $_REQUEST['source_language'] ) : null;
    683         $targetLang    = isset($_REQUEST['target_language']) ? sanitize_text_field( $_REQUEST['target_language'] ) : null;
    684         $pllMainPostID = isset($_REQUEST['pllMainPostID']) ? sanitize_text_field( $_REQUEST['pllMainPostID'] ) : null;
     681        $wpPostIds     = isset( $_REQUEST['post_ids'] ) ? $_REQUEST['post_ids'] : array();
     682        $sourceLang    = isset( $_REQUEST['source_language'] ) ? sanitize_text_field( $_REQUEST['source_language'] )
     683            : null;
     684        $targetLang    = isset( $_REQUEST['target_language'] ) ? sanitize_text_field( $_REQUEST['target_language'] )
     685            : null;
     686        $pllMainPostID = isset( $_REQUEST['pllMainPostID'] ) ? sanitize_text_field( $_REQUEST['pllMainPostID'] ) : null;
    685687
    686688        $mwApiHelper = $this->getAPI();
     
    708710            $wpPostId = sanitize_text_field( $wpPostId );
    709711            // Get from main post
    710             if ( $this->isPolylang && ! empty( $pllMainPostID ) && (int)$pllMainPostID > 0 ) {
     712            if ( $this->isPolylang && ! empty( $pllMainPostID ) && (int) $pllMainPostID > 0 ) {
    711713                $wpPostTitle  = get_the_title( $pllMainPostID );
    712714                $content_post = get_post( $pllMainPostID );
     
    719721            $wpPostContent  = $content_post->post_content;
    720722            $thePostExcerpt = $content_post->post_excerpt;
    721             $wpPostContent  = apply_filters( 'the_content', $wpPostContent );
    722723            $wpPostContent  = str_replace( ']]>', ']]&gt;', $wpPostContent );
    723724
    724             $temp = tmpfile();
    725 
    726             $data = array(
    727                 'TITLE'   => $wpPostTitle,
    728                 'CONTENT' => $wpPostContent,
    729                 'EXCERPT' => $thePostExcerpt
    730             );
    731 
    732             // Handle Custom Fields
     725            // HTML files that are sent as individual files.
     726            $files = array();
     727            // Value fields that are gathered together in a single value=>key file.
     728            $fields = array();
     729
     730            // Title
     731            if ( strlen( $wpPostTitle ) > 0 ) {
     732                $fields['TITLE'] = $wpPostTitle;
     733            }
     734
     735            // Excerpt
     736            if ( strlen( $thePostExcerpt ) > 0 ) {
     737                if ( $thePostExcerpt === strip_tags( $thePostExcerpt ) ) {
     738                    $fields['EXCERPT'] = $thePostExcerpt;
     739                } else {
     740                    $files['EXCERPT'] = $this->createHTMLFile( $thePostExcerpt );
     741                }
     742            }
     743
     744            // Content
     745            if ( strlen( $wpPostContent ) > 0 ) {
     746                if ( $wpPostContent === strip_tags( $wpPostContent ) ) {
     747                    $fields['CONTENT'] = $wpPostContent;
     748                } else {
     749                    $files['CONTENT'] = $this->createHTMLFile( $wpPostContent );
     750                }
     751            }
     752
     753            // Custom fields
    733754            $wpPostCustomFields = get_post_meta( $thePostId, false );
    734755
    735756            foreach ( $wpPostCustomFields as $key => $value ) {
    736                 if ( $key != "_edit_lock" && $key != "_edit_last" ) {
    737                     $data[ 'CUSTOMFIELD_' . $key ] = $value[0];
    738                 }
    739             }
    740 
    741             // Handle Attached Media
    742             $attachments = get_posts( array(
    743                 'post_parent'    => $thePostId,
    744                 'post_type'      => 'attachment',
    745                 'posts_per_page' => - 1,
    746                 'orderby'        => 'menu_order',
    747                 'order'          => 'ASC',
    748             ) );
    749 
    750             if ( ! ! $attachments ) {
    751                 foreach ( $attachments as $attachment ) {
    752                     $alt = get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true );
    753 
    754                     $data[ 'ATTACHMENT_' . $attachment->ID . '_TITLE' ]   = $attachment->post_title;
    755                     $data[ 'ATTACHMENT_' . $attachment->ID . '_EXCERPT' ] = $attachment->post_excerpt;
    756 
    757                     if ( ! ! $alt ) {
    758                         $data[ 'ATTACHMENT_' . $attachment->ID . '_ALT' ] = $alt;
     757                if ( ! isset( $value[0] ) || strlen( $value[0] ) < 1 ) {
     758                    continue;
     759                }
     760
     761                $value = $value[0];
     762
     763                if ( $key != "_edit_lock" && $key != "_edit_last"
     764                     && isset( $value )
     765                     && ! is_numeric( $value ) && strtolower( $value ) !== 'true'
     766                     && strtolower( $value ) !== 'false'
     767                     && is_serialized( $value ) === false ) {
     768                    if ( $value === strip_tags( $value ) ) {
     769                        $fields[ 'CUSTOMFIELD_' . $key ] = $value;
     770                    } else {
     771                        $files[ 'CUSTOMFIELD_' . $key ] = $this->createHTMLFile( $value );
    759772                    }
    760773                }
    761774            }
    762775
    763             fwrite( $temp, json_encode( $data ) );
    764 
    765             $metaData     = stream_get_meta_data( $temp );
     776            /**
     777             * // Attachments and media
     778             *
     779             *
     780             * $attachments = get_posts( array(
     781             * 'post_parent'    => $thePostId,
     782             * 'post_type'      => 'attachment',
     783             * 'posts_per_page' => - 1,
     784             * 'orderby'        => 'menu_order',
     785             * 'order'          => 'ASC',
     786             * ) );
     787             *
     788             * if ( ! ! $attachments ) {
     789             * foreach ( $attachments as $attachment ) {
     790             * $id = $attachment->ID;
     791             * $title = $attachment->post_title;
     792             * $excerpt = $attachment->post_excerpt;
     793             *
     794             * $alt = get_post_meta( $id, '_wp_attachment_image_alt', true );
     795             *
     796             * if(strlen($title) > 0) {
     797             * if ($title === strip_tags($title)) {
     798             * $fields['ATTACHMENT_' . $attachment->ID . '_TITLE'] = $title;
     799             * } else {
     800             * $files['ATTACHMENT_' . $attachment->ID . '_TITLE'] = $this->createHTMLFile($title);
     801             * }
     802             * }
     803             *
     804             * if(strlen($excerpt) > 0) {
     805             * if ($excerpt === strip_tags($excerpt)) {
     806             * $fields['ATTACHMENT_' . $attachment->ID . '_EXCERPT'] = $excerpt;
     807             * } else {
     808             * $files['ATTACHMENT_' . $attachment->ID . '_EXCERPT'] = $this->createHTMLFile($excerpt);
     809             * }
     810             * }
     811             *
     812             * if ( strlen($alt) > 1 ) {
     813             * if($alt === strip_tags($alt)) {
     814             * $fields[ 'ATTACHMENT_' . $attachment->ID . '_ALT' ]   = $alt;
     815             * } else {
     816             * $files['ATTACHMENT_' . $attachment->ID . '_ALT'] = $this->createHTMLFile($alt);
     817             * }
     818             * }
     819             * }
     820             * }
     821             */
     822
    766823            $callbackEndpoint = ! ! $motawordPlugin ? $motawordPlugin->getCallbackEndpoint() : 'mw-callback';
    767             $callback_url = get_home_url() . '?'.$callbackEndpoint.'=1';
    768 
    769             $project = $mwApiHelper->submitProject( array(
     824            $callback_url     = get_home_url() . '?' . $callbackEndpoint . '=1';
     825
     826            $params = array(
    770827                'source_language'    => $sourceLang,
    771828                'target_languages[]' => $targetLang,
    772                 'documents'          => array(
    773                     '@' . $metaData['uri'] . ';filename=' . $wpPostId . '.' . $defaultType
    774                 ),
     829                'documents'          => array(),
    775830                'callback_url'       => $callback_url,
    776831                'custom[wp_post_id]' => $wpPostId
    777             ) );
     832            );
     833
     834            $documents = array();
     835
     836            if ( count( $fields ) > 0 ) {
     837                $fieldsFile = tmpfile();
     838                fwrite( $fieldsFile, json_encode( $fields ) );
     839                $fieldsMeta  = stream_get_meta_data( $fieldsFile );
     840                $documents[] = '@' . $fieldsMeta['uri'] . ';filename=' . $wpPostId . '.' . $defaultType;
     841            }
     842
     843            if ( count( $files ) ) {
     844                foreach ( $files as $name => $file ) {
     845                    $fileMeta    = stream_get_meta_data( $file );
     846                    $documents[] = '@' . $fileMeta['uri'] . ';filename=' . $name . '.html';
     847                }
     848            }
     849
     850            $params['documents'] = $documents;
     851
     852            $project = $mwApiHelper->submitProject( $params );
    778853
    779854            if ( ! $project || ! isset( $project->id ) ) {
    780                 $this->issue_error( sprintf(
    781                         __( 'An error occurred while submitting your posts to MotaWord for a quote: %s', 'motaword' ),
    782                         '<br><br><pre>' . json_encode( $project, JSON_PRETTY_PRINT ) . '</pre>' )
    783                 );
     855                $this->issue_error( sprintf( __( 'An error occurred while submitting your posts to MotaWord for a quote: %s',
     856                        'motaword' ), '<br><br><pre>' . json_encode( $project, JSON_PRETTY_PRINT ) . '</pre>' ) );
    784857            }
    785858
     
    797870        }
    798871
    799         $title = sprintf(
    800             _n(
    801                 'We can translate this WordPress post for just <strong>%1$s%2$s</strong>.',
    802                 'We can translate these WordPress posts for just <strong>%1$s%2$s</strong>.',
    803                 count( $projects ),
    804                 'motaword'
    805             ),
    806             MotaWord_i18n::getCurrency( $currency ),
    807             $totalCost
    808         );
    809 
    810         $subTitle = sprintf(
    811             _n(
    812                 'OUR QUOTE IS BASED ON <strong>%1$d</strong> WORDS.',
    813                 'OUR QUOTE IS BASED ON <strong>%1$d</strong> WORDS FOR %2$d POSTS.',
    814                 count( $projects ),
    815                 'motaword'
    816             ),
    817             $totalWordCount,
    818             count( $projects )
    819         );
     872        $title = sprintf( _n( 'We can translate this WordPress post for just <strong>%1$s%2$s</strong>.',
     873            'We can translate these WordPress posts for just <strong>%1$s%2$s</strong>.', count( $projects ),
     874            'motaword' ), MotaWord_i18n::getCurrency( $currency ), $totalCost );
     875
     876        $subTitle = sprintf( _n( 'OUR QUOTE IS BASED ON <strong>%1$d</strong> WORDS.',
     877            'OUR QUOTE IS BASED ON <strong>%1$d</strong> WORDS FOR %2$d POSTS.', count( $projects ), 'motaword' ),
     878            $totalWordCount, count( $projects ) );
    820879
    821880        echo '
     
    829888
    830889<p class="submit" style="text-align: center;">
    831     <input type="submit" name="submit" id="submit" class="button button-primary button-large" value="' . __( 'Start Project', 'motaword' ) . '">
     890    <input type="submit" name="submit" id="submit" class="button button-primary button-large" value="' . __( 'Start Project',
     891                'motaword' ) . '">
    832892</p>
    833893<p>
    834     <em>' . __( 'Have questions? <a href="https://www.motaword.com/contact" target="_blank">We are one email away.</a>', 'motaword' ) . '</em>
     894    <em>' . __( 'Have questions? <a href="https://www.motaword.com/contact" target="_blank">We are one email away.</a>',
     895                'motaword' ) . '</em>
    835896</p>
    836897
     
    838899
    839900        exit();
     901    }
     902
     903    protected function createHTMLFile( $content ) {
     904        $temp = tmpfile();
     905        fwrite( $temp, (string) $content );
     906
     907        return $temp;
    840908    }
    841909
     
    900968
    901969            if ( count( $uniqueLangs ) > 1 || count( $uniqueLangs ) < 1 ) {
    902                 $this->issue_error( __( 'Source languages of the posts you selected don\'t match. Please select the posts with the same language.', 'motaword' ) );
     970                $this->issue_error( __( 'Source languages of the posts you selected don\'t match. Please select the posts with the same language.',
     971                    'motaword' ) );
    903972            }
    904973
     
    9311000    </div>';
    9321001
    933         echo '<h4>' . sprintf(
    934                 _n(
    935                     'You have selected %d post.',
    936                     'You have selected %d posts.',
    937                     count( $wpPostIds ),
    938                     'motaword'
    939                 ),
    940                 count( $wpPostIds )
    941             ) . '</h4>';
    942 
    943         echo '<p>' . __( 'To get your quote, please select your translation languages and continue.', 'motaword' ) . '</p>';
     1002        echo '<h4>' . sprintf( _n( 'You have selected %d post.', 'You have selected %d posts.', count( $wpPostIds ),
     1003                'motaword' ), count( $wpPostIds ) ) . '</h4>';
     1004
     1005        echo '<p>' . __( 'To get your quote, please select your translation languages and continue.',
     1006                'motaword' ) . '</p>';
    9441007
    9451008        echo '<form method="get" action="' . admin_url( 'admin-ajax.php' ) . '" id="mw_quote_form">';
     
    9611024            $name = $language->name;
    9621025            if ( $code === $mainSourceLanguage ) {
    963                 $sourceBox .= '<option value="' . $code . '" selected="selected">' . __( $name, 'motaword' ) . '</option>';
     1026                $sourceBox .= '<option value="' . $code . '" selected="selected">' . __( $name,
     1027                        'motaword' ) . '</option>';
    9641028            } else {
    9651029                $sourceBox .= '<option value="' . $code . '">' . __( $name, 'motaword' ) . '</option>';
     
    9781042
    9791043            if ( $targetSelected === false && $code !== $mainSourceLanguage ) {
    980                 $targetBox .= '<option value="' . $code . '" selected="selected">' . __( $name, 'motaword' ) . '</option>';
     1044                $targetBox .= '<option value="' . $code . '" selected="selected">' . __( $name,
     1045                        'motaword' ) . '</option>';
    9811046                $targetSelected = true;
    9821047            } else {
     
    9931058        echo '<div>
    9941059        <p class="submit" style="text-align: center;">
    995             <input type="submit" name="submit" id="submit" class="button button-primary button-large" value="' . __( 'Continue to get a quote', 'motaword' ) . '">
     1060            <input type="submit" name="submit" id="submit" class="button button-primary button-large" value="' . __( 'Continue to get a quote',
     1061                'motaword' ) . '">
    9961062        </p>
    9971063        <p>
    998             <em>' . __( 'Have questions? <a href="https://www.motaword.com/contact" target="_blank">We are one email away.</a>', 'motaword' ) . '</em>
     1064            <em>' . __( 'Have questions? <a href="https://www.motaword.com/contact" target="_blank">We are one email away.</a>',
     1065                'motaword' ) . '</em>
    9991066        </p>
    10001067        </div></form>';
     
    11051172
    11061173        if ( (int) $success > 0 ) {
    1107             $title = _n(
    1108                 'Your post has been submitted for translation!',
    1109                 'Your posts have been submitted for translation!',
    1110                 $success,
    1111                 'motaword'
    1112             );
    1113 
    1114             $subTitle = _n(
    1115                 'You can track its progress on post editing screen or <a href="https://www.motaword.com/projects" target="_blank">your MotaWord dashboard</a>.',
     1174            $title = _n( 'Your post has been submitted for translation!',
     1175                'Your posts have been submitted for translation!', $success, 'motaword' );
     1176
     1177            $subTitle = _n( 'You can track its progress on post editing screen or <a href="https://www.motaword.com/projects" target="_blank">your MotaWord dashboard</a>.',
    11161178                'You can track their progress on post editing screen or <a href="https://www.motaword.com/projects" target="_blank">your MotaWord dashboard</a>.',
    1117                 $success,
    1118                 'motaword'
    1119             );
     1179                $success, 'motaword' );
    11201180
    11211181            echo '<h2 style="font-weight: normal;">' . $title . '</h2>
     
    11251185        if ( $rejected || ! $success ) {
    11261186            echo '<br/>';
    1127             $this->issue_error( __( 'Your job(s) has been rejected.' . ( $errorResponse ? '<br/><br/><pre style="text-align: left;">' . json_encode( $errorResponse, JSON_PRETTY_PRINT ) . '</pre>' : '' ), 'motaword' ) );
    1128         }
    1129 
    1130         echo '<p><em>' . __( 'Have questions? <a href="https://www.motaword.com/contact" target="_blank">We are one email away.</a>', 'motaword' ) . '</em></p></div>';
     1187            $this->issue_error( __( 'Your job(s) has been rejected.' . ( $errorResponse
     1188                    ? '<br/><br/><pre style="text-align: left;">' . json_encode( $errorResponse,
     1189                        JSON_PRETTY_PRINT ) . '</pre>' : '' ), 'motaword' ) );
     1190        }
     1191
     1192        echo '<p><em>' . __( 'Have questions? <a href="https://www.motaword.com/contact" target="_blank">We are one email away.</a>',
     1193                'motaword' ) . '</em></p></div>';
    11311194
    11321195        exit();
     
    11451208     */
    11461209    public function register_my_custom_menu_page() {
    1147         add_options_page( __( 'MotaWord', 'motaword' ), __( 'MotaWord', 'motaword' ), 'manage_options', 'motaword', array(
    1148             $this,
    1149             'settings'
    1150         ) );
     1210        add_options_page( __( 'MotaWord', 'motaword' ), __( 'MotaWord', 'motaword' ), 'manage_options', 'motaword',
     1211            array(
     1212                $this,
     1213                'settings'
     1214            ) );
    11511215    }
    11521216
    11531217    public function network_settings() {
    1154         $this->settings(true);
     1218        $this->settings( true );
    11551219    }
    11561220
     
    11601224     * @param bool|false $network
    11611225     */
    1162     public function settings($network = false) {
     1226    public function settings( $network = false ) {
    11631227        global $motawordPlugin;
    11641228
    1165         $network = (bool)$network;
     1229        $network = (bool) $network;
    11661230
    11671231        $this->exitOnError = true;
    11681232
    11691233        if ( $_POST ) {
    1170             $this->save_settings($network);
     1234            $this->save_settings( $network );
    11711235        }
    11721236
    11731237        $options = array(
    1174             'id'      => $motawordPlugin->getOption(static::$options['client_id'], $network ),
     1238            'id'      => $motawordPlugin->getOption( static::$options['client_id'], $network ),
    11751239            'secret'  => $motawordPlugin->getOption( static::$options['client_secret'], $network ),
    11761240            'sandbox' => (bool) $motawordPlugin->getOption( static::$options['sandbox'], $network ),
     
    11841248            <?php if ( isset( $_GET['activated'] ) ): ?>
    11851249                <div class="updated"><p>
    1186                         <?php _e('Let\'s make sure you put your API client ID and secret here. If you have any
    1187                         questions, just head to <a href="https://www.motaword.com/developer" target="_blank">documentation</a>.', 'motaword'); ?>
    1188 
    1189                         <?php if($network): ?>
    1190                             <?php _e('Remember, you can also specify different API clients for your sites by visiting MotaWord settings page in each site\'s admin section.', 'motaword'); ?>
     1250                        <?php _e( 'Let\'s make sure you put your API client ID and secret here. If you have any
     1251                        questions, just head to <a href="https://www.motaword.com/developer" target="_blank">documentation</a>.',
     1252                            'motaword' ); ?>
     1253
     1254                        <?php if ( $network ): ?>
     1255                            <?php _e( 'Remember, you can also specify different API clients for your sites by visiting MotaWord settings page in each site\'s admin section.',
     1256                                'motaword' ); ?>
    11911257                        <?php endif; ?>
    11921258                    </p></div>
     
    12001266                        <th scope="row"><?php _e( 'API Client ID:', 'motaword' ); ?></th>
    12011267                        <td><input type="text" name="<?php echo MotaWord::getOptionsKey() ?>[api_client_id]"
    1202                                    value="<?php echo $options['id']; ?>"/></td>
     1268                                   value="<?php echo $options['id']; ?>"/></td>
    12031269                    </tr>
    12041270                    <tr valign="top">
    12051271                        <th scope="row"><?php _e( 'API Client Secret:', 'motaword' ); ?></th>
    12061272                        <td><input type="text" name="<?php echo MotaWord::getOptionsKey() ?>[api_client_secret]"
    1207                                    value="<?php echo $options['secret']; ?>"/></td>
     1273                                   value="<?php echo $options['secret']; ?>"/></td>
    12081274                    </tr>
    12091275                    <tr valign="top">
    12101276                        <th scope="row"><?php _e( 'Sandbox mode:', 'motaword' ); ?></th>
    12111277                        <td><input type="checkbox" value="1"
    1212                                    name="<?php echo MotaWord::getOptionsKey() ?>[is_sandbox]" <?php echo isset( $options['sandbox'] ) && ! ! $options['sandbox'] ? 'checked="checked"' : ''; ?> />
     1278                                   name="<?php echo MotaWord::getOptionsKey() ?>[is_sandbox]" <?php echo isset( $options['sandbox'] ) && ! ! $options['sandbox']
     1279                                ? 'checked="checked"' : ''; ?> />
    12131280                        </td>
    12141281                    </tr>
     
    12271294     * @param bool|false $network
    12281295     */
    1229     public function save_settings($network = false) {
     1296    public function save_settings( $network = false ) {
    12301297        global $motawordPlugin;
    12311298
     
    12581325            }
    12591326
    1260             if ( (int) $motawordPlugin->getOption( static::$options['sandbox'], $network ) !== (int) $newSandboxValue ) {
     1327            if ( (int) $motawordPlugin->getOption( static::$options['sandbox'],
     1328                    $network ) !== (int) $newSandboxValue
     1329            ) {
    12611330                // Clear the API caches as we are changing the environment here.
    12621331                $api = $this->getAPI();
     
    13511420            $icon                   = 'icon_ongoing';
    13521421
    1353             $message = sprintf(
    1354                 __( "We are still working on the translation of this post.\n\nTranslation: %1\$d%%\nProofreading: %2\$d%%", 'motaword' ),
    1355                 $translationPercentage,
    1356                 $proofreadingPercentage
    1357             );
     1422            $message = sprintf( __( "We are still working on the translation of this post.\n\nTranslation: %1\$d%%\nProofreading: %2\$d%%",
     1423                'motaword' ), $translationPercentage, $proofreadingPercentage );
    13581424        }
    13591425
     
    13711437        $type = $current_screen->post_type;
    13721438
    1373         if ( is_plugin_active( 'polylang/polylang.php' )
    1374             && ( function_exists( 'pll_is_translated_post_type' ) && pll_is_translated_post_type( $type ) )
    1375         ) {
     1439        if ( is_plugin_active( 'polylang/polylang.php' ) && ( function_exists( 'pll_is_translated_post_type' ) && pll_is_translated_post_type( $type ) ) ) {
    13761440            return $columns;
    13771441        }
     
    13831447        }
    13841448
    1385         $columns['motaword'] = '<img src="' . plugin_dir_url( __FILE__ ) . '/css/icon.png" style="width: 20px; height: 20px;" title="' . __( 'MotaWord Summary', 'motaword' ) . '" alt="' . __( 'MotaWord Summary', 'motaword' ) . '"/>';
     1449        $columns['motaword'] = '<img src="' . plugin_dir_url( __FILE__ ) . '/css/icon.png" style="width: 20px; height: 20px;" title="' . __( 'MotaWord Summary',
     1450                'motaword' ) . '" alt="' . __( 'MotaWord Summary', 'motaword' ) . '"/>';
    13861451
    13871452        return isset( $end ) ? array_merge( $columns, $end ) : $columns;
  • motaword/trunk/admin/js/motaword-admin.js

    r1265215 r1276630  
    192192    });
    193193
     194    // To prevent successive quote submissions (which triggers errors because of multiple
     195    // payment trial and well, why would you want to submit twice?)
     196    var submittedQuote = false;
     197
    194198    jQuery(document).ready(function () {
    195199        var body = jQuery('body');
     
    264268        e.preventDefault();
    265269
     270        if(submittedQuote === true) {
     271            return false;
     272        }
     273
     274        submittedQuote = true;
     275        jQuery('#submit').val('Loading...').attr('disabled', true);
     276
    266277        jQuery.post(ajaxurl, jQuery('#mw_quote_form').serialize(), function (result) {
     278            submittedQuote = false;
     279
    267280            jQuery('#TB_ajaxContent').html(result);
    268281            jQuery('#motaword_box').find('.inside').html('<div class="mw_warning">Refresh the page to get latest translation updates.</div>');
  • motaword/trunk/includes/class-motaword-api.php

    r1265236 r1276630  
    5757     * @param string $clientId
    5858     * @param string $clientSecret
    59      * @param bool $useSandbox
    60      * @param bool $isCached
     59     * @param bool   $useSandbox
     60     * @param bool   $isCached
    6161     * @param string $cachePrefix
    62      * @param int $cacheExpiration
    63      */
    64     function __construct( $clientId, $clientSecret, $useSandbox = false, $isCached = true, $cachePrefix = 'motaword_', $cacheExpiration = 300 ) {
     62     * @param int    $cacheExpiration
     63     */
     64    function __construct(
     65        $clientId,
     66        $clientSecret,
     67        $useSandbox = false,
     68        $isCached = true,
     69        $cachePrefix = 'motaword_',
     70        $cacheExpiration = 300
     71    ) {
    6572        $this->useSandbox        = (bool) $useSandbox;
    6673        $this->clientId          = $clientId;
     
    7077        static::$cacheExpiration = $cacheExpiration;
    7178
    72         if((bool)$useSandbox) {
    73             static::$cachePrefix = static::$cachePrefix.'sandbox_';
    74         }
    75     }
    76 
    77     public static function setEndpoint($production, $sandbox) {
     79        if ( (bool) $useSandbox ) {
     80            static::$cachePrefix = static::$cachePrefix . 'sandbox_';
     81        }
     82    }
     83
     84    public static function setEndpoint( $production, $sandbox ) {
    7885        self::$PRODUCTION_URL = $production;
    79         self::$SANDBOX_URL = $sandbox;
     86        self::$SANDBOX_URL    = $sandbox;
    8087    }
    8188
     
    9198            if ( ( $result = get_site_transient( static::$cachePrefix . 'languages' ) ) === false ) {
    9299                $result = $this->get( 'languages' );
    93                 set_site_transient( static::$cachePrefix . 'languages', $result );
     100
     101                if ( ! ! $result && ! isset( $result->error ) ) {
     102                    set_site_transient( static::$cachePrefix . 'languages', $result );
     103                }
    94104            }
    95105        } else {
     
    119129
    120130                if ( ! ! $result && ! isset( $result->error ) ) {
    121                     set_site_transient( static::$cachePrefix . 'project_' . $projectId, $result, static::$cacheExpiration );
     131                    set_site_transient( static::$cachePrefix . 'project_' . $projectId, $result,
     132                        static::$cacheExpiration );
    122133                }
    123134            }
     
    148159
    149160                if ( ! ! $result && ! isset( $result->error ) ) {
    150                     set_site_transient( static::$cachePrefix . 'progress_' . $projectId, $result, static::$cacheExpiration );
     161                    set_site_transient( static::$cachePrefix . 'progress_' . $projectId, $result,
     162                        static::$cacheExpiration );
    151163                }
    152164            }
     
    181193     */
    182194    public function downloadProject( $projectId ) {
    183         $response = $this->post(
    184             'projects/' . $projectId . '/package',
    185             array( 'async' => 0 )
    186         );
     195        $response = $this->post( 'projects/' . $projectId . '/package', array( 'async' => 0 ) );
    187196
    188197        return $response;
     
    193202     *
    194203     * @param integer $projectId
    195      * @param array $data
     204     * @param array   $data
    196205     *
    197206     * @return object
     
    205214     * to prevent unnecessary calls.
    206215     *
    207      * @param bool $forceNew When true, we'll retrieve a new access token even though the previous one was not
     216     * @param bool $forceNew    When true, we'll retrieve a new access token even though the previous one was not
    208217     *                          expired yet.
    209218     *
     
    219228                    'User-Agent'    => $this->getUserAgent(),
    220229                    'Accept'        => 'application/json',
    221                     'Authorization' => 'Basic ' . base64_encode(
    222                             $this->clientId . ':' . $this->clientSecret
    223                         ),
     230                    'Authorization' => 'Basic ' . base64_encode( $this->clientId . ':' . $this->clientSecret ),
    224231                    'Content-Type'  => 'application/x-www-form-urlencoded'
    225232                ),
     
    236243            $response = wp_remote_post( $url, $options );
    237244
    238             if(!$response || $response instanceof WP_Error) {
     245            if ( ! $response || $response instanceof WP_Error ) {
    239246                return null;
    240247            }
     
    245252            if ( isset( $response['access_token'] ) ) {
    246253                $accessToken = $response['access_token'];
    247                 set_site_transient( static::$cachePrefix . 'access_token', $accessToken, ( $response['expires_in'] - 300 ) );
     254                set_site_transient( static::$cachePrefix . 'access_token', $accessToken,
     255                    ( $response['expires_in'] - 300 ) );
    248256            }
    249257        }
     
    324332     * Regular form body.
    325333     *
    326      * @param string $name Form input name
     334     * @param string $name  Form input name
    327335     * @param string $value Form input value
    328336     *
     
    336344     * File upload form body.
    337345     *
    338      * @param string $key Form input name
     346     * @param string $key  Form input name
    339347     * @param string $path File path
    340348     *
     
    377385                if ( is_array( $datum ) ) {
    378386                    foreach ( $datum as $i => $datuman ) {
    379                         $result[ $key . '[' . '' . ']' ] = $datuman;
     387                        $result[ $key . '[' . $i . ']' ] = $datuman;
    380388                    }
    381389                } else {
     
    406414     *
    407415     * @param string $path Relative API resource path
    408      * @param array $data Query parameters
     416     * @param array  $data Query parameters
    409417     *
    410418     * @return object
     
    417425     * HTTP POST
    418426     *
    419      * @param string $path Relative API resource path
    420      * @param array $data Post form data
     427     * @param string  $path  Relative API resource path
     428     * @param array   $data  Post form data
    421429     * @param boolean $upload Is this a file upload?
    422430     *
     
    431439     *
    432440     * @param string $path Relative API resource path
    433      * @param array $data Put body parameters
     441     * @param array  $data Put body parameters
    434442     *
    435443     * @return object
     
    442450     * HTTP request base
    443451     *
    444      * @param string $path Relative API resource path
    445      * @param string $method HTTP method: GET, POST, PUT, DELETE
    446      * @param array $data Request parameters
     452     * @param string  $path  Relative API resource path
     453     * @param string  $method HTTP method: GET, POST, PUT, DELETE
     454     * @param array   $data  Request parameters
    447455     * @param boolean $upload Is this a file upload?
    448456     *
     
    490498        }
    491499
    492         if(!$response || $response instanceof WP_Error) {
     500        if ( ! $response || $response instanceof WP_Error ) {
    493501            return null;
    494502        }
    495503
    496         $response = json_decode( trim( $response['body'] ) );
     504        // If this is not a document/style guide/glossary/translation download request,
     505        // it must be in JSON.
     506        if ( strpos( $path, 'download' ) > - 1
     507             || ( strpos( $path, 'package' ) > - 1
     508                  && isset( $data['async'] ) && (bool) $data['async'] === false )
     509        ) {
     510            $response = $response['body'];
     511        } else {
     512            $response = json_decode( trim( $response['body'] ) );
     513        }
    497514
    498515        return $response;
  • motaword/trunk/includes/class-motaword-db.php

    r1265236 r1276630  
    6969            return array( (object) $result );
    7070        } else {
    71             return static::getDB()->get_results( "SELECT * FROM " . $this->table_name . " WHERE post_wp_id = " . $wpPostId );
     71            return static::getDB()
     72                         ->get_results( "SELECT * FROM " . $this->table_name . " WHERE post_wp_id = " . $wpPostId );
    7273        }
    7374    }
     
    8182                'meta_value'  => $projectId,
    8283                'post_status' => $status,
     84                'post_type'   => 'any',
    8385                'fields'      => 'ids'
    8486            );
     
    9496            return null;
    9597        } else {
    96             return static::getDB()->get_var( "SELECT post_wp_id FROM " . $this->table_name . " WHERE mw_project_id = " . $projectId );
     98            return static::getDB()
     99                         ->get_var( "SELECT post_wp_id FROM " . $this->table_name . " WHERE mw_project_id = " . $projectId );
    97100        }
    98101    }
     
    101104     * add new lanched project in to local db
    102105     *
    103      * @param integer $postId WP post ID.
     106     * @param integer $postId      WP post ID.
    104107     * @param integer $mwProjectId MotaWord project ID.
    105      * @param string $status started, completed.
     108     * @param string  $status      started, completed.
    106109     *
    107110     * @return mixed
     
    114117        if ( static::$use_meta ) {
    115118            update_post_meta( $postId, static::$meta_prefix . 'project_id', $mwProjectId );
     119
    116120            return $this->updateProject( $postId, $status, 0, 0 );
    117121        } else {
  • motaword/trunk/motaword.php

    r1271940 r1276630  
    1616 * Plugin URI:        https://www.motaword.com/developer
    1717 * Description:       MotaWord plugin allows you to seamlessly submit your posts for translation to MotaWord.
    18  * Version:           1.0.0
     18 * Version:           1.1.0
    1919 * Author:            Oytun Tez <[email protected]>
    2020 * Author URI:        https://www.motaword.com/developer
  • motaword/trunk/public/class-motaword-public.php

    r1265236 r1276630  
    4747     *
    4848     * @param      string $motaword The name of the plugin.
    49      * @param      string $version The version of this plugin.
     49     * @param      string $version  The version of this plugin.
    5050     */
    5151    public function __construct( $motaword, $version ) {
     
    6969        include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
    7070
    71         if ( !function_exists('is_plugin_active')
    72              || ! is_plugin_active( !!$motawordPlugin ? $motawordPlugin->getPluginFile() : 'motaword/motaword.php' ) ) {
     71        if ( ! function_exists( 'is_plugin_active' ) || ! is_plugin_active( ! ! $motawordPlugin
     72                ? $motawordPlugin->getPluginFile() : 'motaword/motaword.php' )
     73        ) {
    7374            return false;
    7475        }
     
    7778
    7879        if ( isset( $_GET[ $callbackEndpoint ] ) ) {
    79             if ( isset( $_POST['type'] )
    80                  && isset( $_POST['project'] )
    81                  && isset( $_POST['action'] )
    82                  && $this->process_callback( sanitize_text_field($_POST['action']), $_POST['project'] )
     80            if ( isset( $_POST['type'] ) && isset( $_POST['project'] ) && isset( $_POST['action'] ) && $this->process_callback( sanitize_text_field( $_POST['action'] ),
     81                    $_POST['project'] )
    8382            ) {
    8483                echo json_encode( array( 'status' => 'success' ) );
     
    9493        }
    9594
    96         $mwProjectId = intval(sanitize_text_field($project['id']));
    97 
    98         if(!$mwProjectId) {
     95        $mwProjectId = intval( sanitize_text_field( $project['id'] ) );
     96
     97        if ( ! $mwProjectId ) {
    9998            return false;
    10099        }
    101100
    102         $mwApiHelper = new MotaWord_API(
    103             get_option( MotaWord_Admin::$options['client_id'] ),
     101        $mwApiHelper = new MotaWord_API( get_option( MotaWord_Admin::$options['client_id'] ),
    104102            get_option( MotaWord_Admin::$options['client_secret'] ),
    105             (bool) get_option( MotaWord_Admin::$options['sandbox'] )
    106         );
     103            (bool) get_option( MotaWord_Admin::$options['sandbox'] ) );
    107104
    108105        //$wpPostId = $project['custom']['wp_post_id'];
     
    110107        $wpPostId = $DBHelper->getPostIDByProjectID( $mwProjectId, 'any' );
    111108
    112         $translatedProject = $mwApiHelper->downloadProject( $mwProjectId );
    113 
    114         // Update Post
    115         $updated_post = array(
    116             'ID'           => $wpPostId,
    117             'post_title'   => $translatedProject->TITLE,
    118             'post_content' => $translatedProject->CONTENT,
    119             'post_excerpt' => $translatedProject->EXCERPT
     109        // Post data
     110        $updateData = array(
     111            'ID' => $wpPostId
     112            // Other data to be updated will be added below.
    120113        );
    121 
    122         $translatedArray = (array) $translatedProject;
    123 
    124         foreach ( $translatedArray as $key => $val ) {
    125             // Update Meta Value
    126             if ( strpos( $key, 'CUSTOMFIELD_' ) ) {
    127                 $metakeyArr = explode( "CUSTOMFIELD_", $key );
    128                 update_post_meta( $wpPostId, $metakeyArr[1], $val );
    129             }
     114        // Custom fields data
     115        $customFieldData = array();
     116
     117        // @var Array       Incoming data from MotaWord to be updated on the WP post.
     118        $incomingData = array();
     119
     120        $zipFileBody = $mwApiHelper->downloadProject( $mwProjectId );
     121
     122        $zipFile = tmpfile();
     123        fwrite( $zipFile, $zipFileBody );
     124        $zipFilePath = stream_get_meta_data( $zipFile );
     125        $zipFilePath = $zipFilePath['uri'];
     126
     127        $baseFolder = wp_upload_dir();
     128        $baseFolder = $baseFolder['path'];
     129        $baseFolder = trailingslashit( $baseFolder ) . '' . rand();
     130
     131        if ( ! mkdir( $baseFolder ) ) {
     132            throw new \Exception( 'Could not create a temporary folder for translated files. Make sure you have required permissions.' );
     133        }
     134
     135        $zip = new \ZipArchive;
     136
     137        if ( $zip->open( $zipFilePath ) === true ) {
     138            if ( ! $zip->extractTo( $baseFolder ) ) {
     139                throw new \Exception( 'Could not extract the translation ZIP file.' );
     140            }
     141
     142            $zip->close();
     143        } else {
     144            throw new \Exception( 'Could not open the translation ZIP file.' );
     145        }
     146
     147        // MW is sending files in a subfolder, per language.
     148        $languageFolders = glob( $baseFolder . '/*' );
     149
     150        // Folder is the actual inner folder which contains .json and .html files. It can be a language folder.
     151        $folder = $baseFolder;
     152
     153        if ( is_array( $languageFolders ) && count( $languageFolders ) > 0 ) {
     154            $folder = $languageFolders[0];
     155        }
     156
     157        // If a 123.json file exists, which keeps non-html key-value content.
     158        // We are merging all incoming data, from json or html, in one array (or two, with custom fields).
     159        // We will apply the update later altogether.
     160        $jsonFiles = glob( $folder . "/*.json" );
     161
     162        if(is_Array($jsonFiles) && isset($jsonFiles[0])) {
     163            $jsonFile = $jsonFiles[0];
     164
     165            $fields = file_get_contents( $jsonFile );
     166            $fields = json_decode( $fields, true );
     167
     168            if ( ! ! $fields && is_array( $fields ) ) {
     169                $incomingData = array_merge( $incomingData, $fields );
     170            }
     171
     172            unset( $fields );
     173        }
     174
     175        // Get remaining html files, if any.
     176        // We are merging all incoming data, from json or html, in one array (or two, with custom fields).
     177        // We will apply the update later altogether.
     178        foreach ( glob( $folder . "/*.html" ) as $file ) {
     179            $fileName = basename( $file );
     180            $key      = str_replace( '.html', '', $fileName );
     181
     182            if ( ! $key ) {
     183                continue;
     184            }
     185
     186            $value = file_get_contents( $file );
     187
     188            if ( strlen( $value ) < 1 ) {
     189                continue;
     190            }
     191
     192            $incomingData[ $key ] = $value;
     193
     194            // $value can be large.
     195            unset( $value );
     196        }
     197
     198        // We don't need downloaded files any more. All data in memory at the moment.
     199        $this->recursive_rmdir( $baseFolder );
     200        // tmpfile Resource will be deleted here.
     201        fclose( $zipFile );
     202
     203        foreach ( $incomingData as $key => $value ) {
     204            if ( strlen( $value ) < 1 ) {
     205                continue;
     206            }
     207
     208            switch ( $key ) {
     209                case 'TITLE':
     210                    $updateData['post_title'] = $value;
     211                    break;
     212                case 'CONTENT':
     213                    $updateData['post_content'] = $value;
     214                    break;
     215                case 'EXCERPT':
     216                    $updateData['post_excerpt'] = $value;
     217                    break;
     218                default:
     219                    if ( strpos( $key, 'CUSTOMFIELD_' ) > - 1 ) {
     220                        $key = str_replace( 'CUSTOMFIELD_', '', $key );
     221
     222                        if ( strlen( $key ) > 0 ) {
     223                            $customFieldData[ $key ] = $value;
     224                        }
     225                    }
     226
     227                    break;
     228            }
     229        }
     230
     231        foreach ( $customFieldData as $key => $value ) {
     232            update_post_meta( $wpPostId, $key, $value );
    130233
    131234            // Update Media Posts
    132235            /*
    133             if(strpos($key,'ATTACHMENT_'))
    134             {
    135                 $mediakeyArr = explode("_",$key);
    136 
    137                 // Update Post
    138                 $updated_post = array(
    139                     'ID'           => $$mediakeyArr[1],
    140                     'post_title'   => $translatedProject->title,
    141                     'post_content' => $translatedProject->content,
    142                     'post_excerpt' => $translatedProject->excerpt
    143                 );
    144 
    145                 update_post_meta($wpPostId, $metakeyArr[1], $val);
    146             }
    147             */
    148         }
    149 
    150         $result = wp_update_post( $updated_post, true );
     236            if(strpos($key,'ATTACHMENT_'))
     237            {
     238                $mediakeyArr = explode("_",$key);
     239
     240                // Update Post
     241                $updated_post = array(
     242                    'ID'           => $$mediakeyArr[1],
     243                    'post_title'   => $translatedProject->title,
     244                    'post_content' => $translatedProject->content,
     245                    'post_excerpt' => $translatedProject->excerpt
     246                );
     247
     248                update_post_meta($wpPostId, $metakeyArr[1], $val);
     249            }
     250            */
     251        }
     252
     253        $result = wp_update_post( $updateData, true );
    151254
    152255        $DBHelper->updateProject( $wpPostId, 'completed', 100, 100 );
     
    159262    }
    160263
     264    function recursive_rmdir( $dir ) {
     265        if ( is_dir( $dir ) ) {
     266            $objects = array_diff( scandir( $dir ), array( '..', '.' ) );
     267            foreach ( $objects as $object ) {
     268                $objectPath = $dir . "/" . $object;
     269                if ( is_dir( $objectPath ) ) {
     270                    $this->recursive_rmdir( $objectPath );
     271                } else {
     272                    unlink( $objectPath );
     273                }
     274            }
     275            rmdir( $dir );
     276        }
     277    }
     278
    161279}
  • motaword/trunk/uninstall.php

    r1265236 r1276630  
    1111}
    1212
    13 if ( ! current_user_can( 'activate_plugins' ) )
     13if ( ! current_user_can( 'activate_plugins' ) ) {
    1414    exit;
     15}
    1516
    1617check_admin_referer( 'bulk-plugins' );
     
    1819// Important: Check if the file is the one
    1920// that was registered during the uninstall hook.
    20 if ( strpos(WP_UNINSTALL_PLUGIN, 'motaword.php') < 0 )
     21if ( strpos( WP_UNINSTALL_PLUGIN, 'motaword.php' ) === false ) {
    2122    exit;
     23}
    2224
    2325require plugin_dir_path( __FILE__ ) . 'includes/class-motaword.php';
    2426
    25 $plugin = new MotaWord(plugin_basename(__FILE__));
     27$plugin = new MotaWord( plugin_basename( __FILE__ ) );
    2628$plugin->run();
    2729
    2830MotaWord_API::clear_cache();
    29 delete_option(MotaWord_Admin::$options['client_id']);
    30 delete_option(MotaWord_Admin::$options['client_secret']);
    31 delete_option(MotaWord_Admin::$options['sandbox']);
     31delete_option( MotaWord_Admin::$options['client_id'] );
     32delete_option( MotaWord_Admin::$options['client_secret'] );
     33delete_option( MotaWord_Admin::$options['sandbox'] );
Note: See TracChangeset for help on using the changeset viewer.