Example #1
0
 function clear()
 {
     $this->data = array();
     if ($this->cache_to_option) {
         icl_cache_clear($this->name . '_cache_class');
     }
 }
 /**
  * @param int     $pidd
  * @param WP_Post $post
  *
  * @return void
  */
 public function save_post_actions($pidd, $post)
 {
     global $sitepress;
     wp_defer_term_counting(true);
     $post = isset($post) ? $post : get_post($pidd);
     // exceptions
     if (!$this->has_save_post_action($post)) {
         wp_defer_term_counting(false);
         return;
     }
     $default_language = $sitepress->get_default_language();
     // allow post arguments to be passed via wp_insert_post directly and not be expected on $_POST exclusively
     $post_vars = (array) $_POST;
     foreach ((array) $post as $k => $v) {
         $post_vars[$k] = $v;
     }
     $post_vars['post_type'] = isset($post_vars['post_type']) ? $post_vars['post_type'] : $post->post_type;
     $post_id = isset($post_vars['post_ID']) ? $post_vars['post_ID'] : $pidd;
     //latter case for XML-RPC publishing
     $language_code = $this->get_save_post_lang($post_id, $sitepress);
     $trid = $this->get_save_post_trid($post_id, $post->post_status);
     // after getting the right trid set the source language from it by referring to the root translation
     // of this trid, in case no proper source language has been set yet
     $source_language = isset($source_language) ? $source_language : $this->get_save_post_source_lang($trid, $language_code, $default_language);
     $this->maybe_set_elid($trid, $post->post_type, $language_code, $post_id, $source_language);
     $translation_sync = $this->get_sync_helper();
     $original_id = $this->get_original_element($post_id);
     if ($original_id) {
         $translation_sync->sync_with_translations($original_id, $post_vars);
     }
     require_once ICL_PLUGIN_PATH . '/inc/cache.php';
     icl_cache_clear($post_vars['post_type'] . 's_per_language', true);
     wp_defer_term_counting(false);
 }
Example #3
0
 /**
  * Runs various database repair and cleanup actions on icl_translations
  *
  * @return int Number of rows in icl_translations that were fixed
  */
 public function repair_broken_assignments()
 {
     $rows_fixed = $this->fix_missing_original();
     $rows_fixed += $this->fix_wrong_source_language();
     $rows_fixed += $this->fix_broken_type_assignments();
     icl_cache_clear();
     wp_cache_init();
     return $rows_fixed;
 }
 function make_duplicate($master_post_id, $lang)
 {
     global $wpml_post_translations;
     do_action('icl_before_make_duplicate', $master_post_id, $lang);
     $master_post = get_post($master_post_id);
     $is_duplicated = false;
     $translations = $wpml_post_translations->get_element_translations($master_post_id, false, false);
     if (isset($translations[$lang])) {
         $post_array['ID'] = $translations[$lang];
         if (WPML_WordPress_Actions::is_bulk_trash($post_array['ID']) || WPML_WordPress_Actions::is_bulk_untrash($post_array['ID'])) {
             return true;
         }
         $is_duplicated = get_post_meta($translations[$lang], '_icl_lang_duplicate_of', true);
     }
     $post_array['post_author'] = $master_post->post_author;
     $post_array['post_date'] = $master_post->post_date;
     $post_array['post_date_gmt'] = $master_post->post_date_gmt;
     $duplicated_post_content = $this->duplicate_post_content($lang, $master_post);
     $post_array['post_content'] = addslashes_gpc($duplicated_post_content);
     $duplicated_post_title = $this->duplicate_post_title($lang, $master_post);
     $post_array['post_title'] = addslashes_gpc($duplicated_post_title);
     $duplicated_post_excerpt = $this->duplicate_post_excerpt($lang, $master_post);
     $post_array['post_excerpt'] = addslashes_gpc($duplicated_post_excerpt);
     if ($this->sitepress->get_setting('sync_post_status')) {
         $sync_post_status = true;
     } else {
         $sync_post_status = !isset($post_array['ID']) || $this->sitepress->get_setting('sync_delete') && $master_post->post_status === 'trash' || $is_duplicated;
     }
     if ($sync_post_status || isset($post_array['ID']) && get_post_status($post_array['ID']) === 'auto-draft') {
         $post_array['post_status'] = $master_post->post_status;
     }
     $post_array['comment_status'] = $master_post->comment_status;
     $post_array['ping_status'] = $master_post->ping_status;
     $post_array['post_name'] = $master_post->post_name;
     if ($master_post->post_parent) {
         $parent = $this->sitepress->get_object_id($master_post->post_parent, $master_post->post_type, false, $lang);
         $post_array['post_parent'] = $parent;
     }
     $post_array['menu_order'] = $master_post->menu_order;
     $post_array['post_type'] = $master_post->post_type;
     $post_array['post_mime_type'] = $master_post->post_mime_type;
     $trid = $this->sitepress->get_element_trid($master_post->ID, 'post_' . $master_post->post_type);
     $id = $this->save_duplicate($post_array, $lang);
     require_once ICL_PLUGIN_PATH . '/inc/cache.php';
     icl_cache_clear();
     global $ICL_Pro_Translation;
     /** @var WPML_Pro_Translation $ICL_Pro_Translation */
     if ($ICL_Pro_Translation) {
         $ICL_Pro_Translation->_content_fix_links_to_translated_content($id, $lang);
     }
     if (!is_wp_error($id)) {
         $ret = $this->run_wpml_actions($master_post, $trid, $lang, $id, $post_array);
     } else {
         $ret = false;
     }
     return $ret;
 }
 /**
  * Runs various database repair and cleanup actions on icl_translations.
  *
  * @return int Number of rows in icl_translations that were fixed
  */
 public function run()
 {
     $rows_fixed = $this->fix_broken_duplicate_rows();
     $rows_fixed += $this->fix_missing_original();
     $rows_fixed += $this->fix_wrong_source_language();
     $rows_fixed += $this->fix_broken_taxonomy_assignments();
     $rows_fixed += $this->fix_broken_post_assignments();
     $rows_fixed += $this->fix_broken_type_assignments();
     icl_cache_clear();
     wp_cache_init();
     return $rows_fixed;
 }
 public function save_post_actions($pidd, $post)
 {
     global $sitepress, $wpdb;
     wp_defer_term_counting(true);
     $post = isset($post) ? $post : get_post($pidd);
     // exceptions
     if (!$this->has_save_post_action($post)) {
         wp_defer_term_counting(false);
         return;
     }
     if (WPML_WordPress_Actions::is_bulk_trash($pidd) || WPML_WordPress_Actions::is_bulk_untrash($pidd)) {
         return;
     }
     $default_language = $sitepress->get_default_language();
     // allow post arguments to be passed via wp_insert_post directly and not be expected on $_POST exclusively
     $post_vars = (array) $_POST;
     foreach ((array) $post as $k => $v) {
         $post_vars[$k] = $v;
     }
     $post_vars['post_type'] = isset($post_vars['post_type']) ? $post_vars['post_type'] : $post->post_type;
     $post_id = $pidd;
     if (isset($post_vars['action']) && $post_vars['action'] === 'post-quickpress-publish') {
         $language_code = $default_language;
     } else {
         $post_id = isset($post_vars['post_ID']) ? $post_vars['post_ID'] : $pidd;
         //latter case for XML-RPC publishing
         $language_code = $this->get_save_post_lang($post_id, $sitepress);
     }
     if ($this->is_inline_action($post_vars) && !($language_code = $this->get_element_lang_code($post_id))) {
         return;
     }
     if (isset($post_vars['icl_translation_of']) && is_numeric($post_vars['icl_translation_of'])) {
         $translation_of_data_prepared = $wpdb->prepare("SELECT trid, language_code\n\t\t\t\t FROM {$wpdb->prefix}icl_translations\n\t\t\t\t WHERE element_id=%d\n\t\t\t\t  AND element_type=%s", $post_vars['icl_translation_of'], 'post_' . $post->post_type);
         list($trid, $source_language) = $wpdb->get_row($translation_of_data_prepared, 'ARRAY_N');
     }
     $trid = isset($trid) && $trid ? $trid : $this->get_save_post_trid($post_id, $post->post_status);
     // after getting the right trid set the source language from it by referring to the root translation
     // of this trid, in case no proper source language has been set yet
     $source_language = isset($source_language) ? $source_language : $this->get_save_post_source_lang($trid, $language_code, $default_language);
     $this->maybe_set_elid($trid, $post->post_type, $language_code, $post_id, $source_language);
     $translation_sync = $this->get_sync_helper();
     $original_id = $this->get_original_element($post_id);
     if ($original_id) {
         $translation_sync->sync_with_translations($original_id, $post_vars);
     }
     if (isset($post_vars['icl_tn_note'])) {
         update_post_meta($post_id, '_icl_translator_note', $post_vars['icl_tn_note']);
     }
     require_once ICL_PLUGIN_PATH . '/inc/cache.php';
     icl_cache_clear($post_vars['post_type'] . 's_per_language', true);
     wp_defer_term_counting(false);
 }
 function untrashed_post_actions($post_id)
 {
     if ($this->settings['sync_delete']) {
         global $wpdb;
         static $untrashed_posts = array();
         $post_type = $wpdb->get_var("SELECT post_type FROM {$wpdb->posts} WHERE ID={$post_id}");
         if (isset($untrashed_posts[$post_id])) {
             return;
             // avoid infinite loop
         }
         $untrashed_posts[$post_id] = $post_id;
         $trid = $this->get_element_trid($post_id, 'post_' . $post_type);
         $translations = $this->get_element_translations($trid, 'post_' . $post_type);
         foreach ($translations as $t) {
             if ($t->element_id != $post_id) {
                 wp_untrash_post($t->element_id);
             }
         }
         require_once ICL_PLUGIN_PATH . '/inc/cache.php';
         icl_cache_clear($post_type . 's_per_language');
     }
 }
Example #8
0
function icl_plugin_upgrade()
{
    global $wpdb;
    $iclsettings = get_option('icl_sitepress_settings');
    require_once ICL_PLUGIN_PATH . '/inc/cache.php';
    icl_cache_clear('locale_cache_class');
    icl_cache_clear('flags_cache_class');
    icl_cache_clear('language_name_cache_class');
    if (get_option('icl_sitepress_version') && version_compare(get_option('icl_sitepress_version'), '1.7.2', '<')) {
        $wpdb->update($wpdb->prefix . 'icl_flags', array('flag' => 'ku.png'), array('lang_code' => 'ku'));
        $wpdb->update($wpdb->prefix . 'icl_languages_translations', array('name' => 'Magyar'), array('language_code' => 'hu', 'display_language_code' => 'hu'));
        $wpdb->update($wpdb->prefix . 'icl_languages_translations', array('name' => 'Hrvatski'), array('language_code' => 'hr', 'display_language_code' => 'hr'));
        $wpdb->update($wpdb->prefix . 'icl_languages_translations', array('name' => 'فارسی'), array('language_code' => 'fa', 'display_language_code' => 'fa'));
    }
    if (get_option('icl_sitepress_version') && version_compare(get_option('icl_sitepress_version'), '1.7.3', '<')) {
        $wpdb->update($wpdb->prefix . 'icl_languages_translations', array('name' => 'پارسی'), array('language_code' => 'fa', 'display_language_code' => 'fa'));
    }
    if (get_option('icl_sitepress_version') && version_compare(get_option('icl_sitepress_version'), '1.7.7', '<')) {
        if (!isset($iclsettings['promote_wpml'])) {
            $iclsettings['promote_wpml'] = 0;
            update_option('icl_sitepress_settings', $iclsettings);
        }
        if (!isset($iclsettings['auto_adjust_ids'])) {
            $iclsettings['auto_adjust_ids'] = 0;
            update_option('icl_sitepress_settings', $iclsettings);
        }
        $wpdb->query("UPDATE {$wpdb->prefix}icl_translations SET element_type='tax_post_tag' WHERE element_type='tag'");
        // @since 3.1.5 - mysql_* function deprecated in php 5.5+
        $wpdb->query("UPDATE {$wpdb->prefix}icl_translations SET element_type='tax_category' WHERE element_type='category'");
    }
    if (get_option('icl_sitepress_version') && version_compare(get_option('icl_sitepress_version'), '1.7.8', '<')) {
        $res = $wpdb->get_results("SELECT ID, post_type FROM {$wpdb->posts}");
        $post_types = array();
        foreach ($res as $row) {
            $post_types[$row->post_type][] = $row->ID;
        }
        foreach ($post_types as $type => $ids) {
            if (!empty($ids)) {
                $q = "UPDATE {$wpdb->prefix}icl_translations SET element_type=%s WHERE element_type='post' AND element_id IN(" . join(',', $ids) . ")";
                $q_prepared = $wpdb->prepare($q, 'post_' . $type);
                $wpdb->query($q_prepared);
                // @since 3.1.5 - mysql_* function deprecated in php 5.5+
            }
        }
        // fix categories & tags in icl_translations
        $res = $wpdb->get_results("SELECT term_taxonomy_id, taxonomy FROM {$wpdb->term_taxonomy}");
        foreach ($res as $row) {
            $icltr = $wpdb->get_row($wpdb->prepare("SELECT translation_id, element_type FROM {$wpdb->prefix}icl_translations WHERE element_id=%d AND element_type LIKE %s", array($row->term_taxonomy_id, wpml_like_escape('tax_') . '%')));
            if ('tax_' . $row->taxonomy != $icltr->element_type) {
                $wpdb->update($wpdb->prefix . 'icl_translations', array('element_type' => 'tax_' . $row->taxonomy), array('translation_id' => $icltr->translation_id));
            }
        }
    }
    if (get_option('icl_sitepress_version') && version_compare(get_option('icl_sitepress_version'), '2.0.0', '<')) {
        include_once ICL_PLUGIN_PATH . '/inc/upgrade-functions/upgrade-2.0.0.php';
        if (empty($iclsettings['migrated_2_0_0'])) {
            define('ICL_MULTI_STEP_UPGRADE', true);
            return;
            // GET OUT AND DO NOT SET THE NEW VERSION
        }
    }
    if (get_option('icl_sitepress_version') && version_compare(get_option('icl_sitepress_version'), '2.0.4', '<')) {
        $sql = "ALTER TABLE {$wpdb->prefix}icl_translation_status ADD COLUMN `_prevstate` longtext";
        $wpdb->query($sql);
    }
    $versions = array('2.0.5', '2.2.2', '2.3.0', '2.3.1', '2.3.3', '2.4.0', '2.5.0', '2.5.2', '2.6.0', '2.7', '2.9', '2.9.3', '3.1', '3.1.5', '3.1.8', '3.1.9.5', '3.2', '3.2.3', '3.3', '3.3.7');
    foreach ($versions as $version) {
        icl_upgrade_version($version);
    }
    //Forcing upgrade logic when ICL_SITEPRESS_DEV_VERSION is defined
    //This allow to run the logic between different alpha/beta/RC versions
    //since we are now storing only the formal version in the options
    if (defined('ICL_SITEPRESS_DEV_VERSION')) {
        icl_upgrade_version(ICL_SITEPRESS_DEV_VERSION, true);
    }
    if (version_compare(get_option('icl_sitepress_version'), ICL_SITEPRESS_VERSION, '<')) {
        update_option('icl_sitepress_version', ICL_SITEPRESS_VERSION);
    }
}
 /**
  * Ajax handler for switching the language of a post.
  */
 public static function wpml_switch_post_language()
 {
     global $sitepress, $wpdb;
     $to = false;
     $post_id = false;
     if (isset($_POST['wpml_to'])) {
         $to = $_POST['wpml_to'];
     }
     if (isset($_POST['wpml_post_id'])) {
         $post_id = $_POST['wpml_post_id'];
     }
     $result = false;
     set_transient(md5($sitepress->get_current_user()->ID . 'current_user_post_edit_lang'), $to);
     if ($post_id && $to) {
         $post_type = get_post_type($post_id);
         $wpml_post_type = 'post_' . $post_type;
         $trid = $sitepress->get_element_trid($post_id, $wpml_post_type);
         /* Check if a translation in that language already exists with a different post id.
          * If so, then don't perform this action.
          */
         $query_for_existing_translation = $wpdb->prepare("\tSELECT translation_id, element_id\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tFROM {$wpdb->prefix}icl_translations\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE element_type = %s\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tAND trid = %d\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tAND language_code = %s", $wpml_post_type, $trid, $to);
         $existing_translation = $wpdb->get_row($query_for_existing_translation);
         if ($existing_translation && $existing_translation->element_id != $post_id) {
             $result = false;
         } else {
             $sitepress->set_element_language_details($post_id, $wpml_post_type, $trid, $to);
             // Synchronize the posts terms languages. Do not create automatic translations though.
             WPML_Terms_Translations::sync_post_terms_language($post_id);
             require_once ICL_PLUGIN_PATH . '/inc/cache.php';
             icl_cache_clear($post_type . 's_per_language', true);
             $result = $to;
         }
     }
     wp_send_json_success($result);
 }
 function save_translation($data)
 {
     global $wpdb, $sitepress, $sitepress_settings, $ICL_Pro_Translation;
     $new_post_id = false;
     $is_incomplete = false;
     foreach ($data['fields'] as $field) {
         $this->_save_translation_field($field['tid'], $field);
         if (!isset($field['finished']) || !$field['finished']) {
             $is_incomplete = true;
         }
     }
     //check if translation job still exists
     $job_count = $wpdb->get_var($wpdb->prepare("SELECT count(1) FROM {$wpdb->prefix}icl_translate_job WHERE job_id=%d", $data['job_id']));
     if ($job_count == 0) {
         wp_redirect(admin_url(sprintf('admin.php?page=%s', WPML_TM_FOLDER . '/menu/translations-queue.php', 'job-cancelled')));
         exit;
     }
     if (!empty($data['complete']) && !$is_incomplete) {
         $wpdb->update($wpdb->prefix . 'icl_translate_job', array('translated' => 1), array('job_id' => $data['job_id']));
         $rid = $wpdb->get_var($wpdb->prepare("SELECT rid FROM {$wpdb->prefix}icl_translate_job WHERE job_id=%d", $data['job_id']));
         $translation_id = $wpdb->get_var($wpdb->prepare("SELECT translation_id FROM {$wpdb->prefix}icl_translation_status WHERE rid=%d", $rid));
         $wpdb->update($wpdb->prefix . 'icl_translation_status', array('status' => ICL_TM_COMPLETE, 'needs_update' => 0), array('rid' => $rid));
         list($element_id, $trid) = $wpdb->get_row($wpdb->prepare("SELECT element_id, trid FROM {$wpdb->prefix}icl_translations WHERE translation_id=%d", $translation_id), ARRAY_N);
         $job = $this->get_translation_job($data['job_id'], true);
         $parts = explode('_', $job->original_doc_id);
         if ($parts[0] == 'external') {
             // Translations are saved in the string table for 'external' types
             $id = array_pop($parts);
             unset($parts[0]);
             $type = implode('_', $parts);
             $type = apply_filters('WPML_get_package_type', $type, $job->original_doc_id);
             foreach ($job->elements as $field) {
                 if ($field->field_translate) {
                     if (function_exists('icl_st_is_registered_string')) {
                         $string_id = icl_st_is_registered_string($type, $id . '_' . $field->field_type);
                         if (!$string_id) {
                             icl_register_string($type, $id . '_' . $field->field_type, self::decode_field_data($field->field_data, $field->field_format));
                             $string_id = icl_st_is_registered_string($type, $id . '_' . $field->field_type);
                         }
                         if ($string_id) {
                             icl_add_string_translation($string_id, $job->language_code, self::decode_field_data($field->field_data_translated, $field->field_format), ICL_STRING_TRANSLATION_COMPLETE);
                         }
                     }
                 }
             }
         } else {
             if (!is_null($element_id)) {
                 $postarr['ID'] = $_POST['post_ID'] = $element_id;
             }
             foreach ($job->elements as $field) {
                 switch ($field->field_type) {
                     case 'title':
                         $postarr['post_title'] = self::decode_field_data($field->field_data_translated, $field->field_format);
                         break;
                     case 'body':
                         $postarr['post_content'] = self::decode_field_data($field->field_data_translated, $field->field_format);
                         break;
                     case 'excerpt':
                         $postarr['post_excerpt'] = self::decode_field_data($field->field_data_translated, $field->field_format);
                         break;
                     case 'URL':
                         $postarr['post_name'] = self::decode_field_data($field->field_data_translated, $field->field_format);
                         break;
                     default:
                         break;
                 }
             }
             $original_post = get_post($job->original_doc_id);
             $postarr['post_author'] = $original_post->post_author;
             $postarr['post_type'] = $original_post->post_type;
             if ($sitepress_settings['sync_comment_status']) {
                 $postarr['comment_status'] = $original_post->comment_status;
             }
             if ($sitepress_settings['sync_ping_status']) {
                 $postarr['ping_status'] = $original_post->ping_status;
             }
             if ($sitepress_settings['sync_page_ordering']) {
                 $postarr['menu_order'] = $original_post->menu_order;
             }
             if ($sitepress_settings['sync_private_flag'] && $original_post->post_status == 'private') {
                 $postarr['post_status'] = 'private';
             }
             if ($sitepress_settings['sync_post_date']) {
                 $postarr['post_date'] = $original_post->post_date;
             }
             //set as draft or the same status as original post
             $postarr['post_status'] = !$sitepress_settings['translated_document_status'] ? 'draft' : $original_post->post_status;
             if ($original_post->post_parent) {
                 $post_parent_trid = $wpdb->get_var("SELECT trid FROM {$wpdb->prefix}icl_translations\n\t\t\t\t\t\tWHERE element_type='post_{$original_post->post_type}' AND element_id='{$original_post->post_parent}'");
                 if ($post_parent_trid) {
                     $parent_id = $wpdb->get_var("SELECT element_id FROM {$wpdb->prefix}icl_translations\n\t\t\t\t\t\t\tWHERE element_type='post_{$original_post->post_type}' AND trid='{$post_parent_trid}' AND language_code='{$job->language_code}'");
                 }
             }
             if (isset($parent_id) && $sitepress_settings['sync_page_parent']) {
                 $_POST['post_parent'] = $postarr['post_parent'] = $parent_id;
                 $_POST['parent_id'] = $postarr['parent_id'] = $parent_id;
             }
             $_POST['trid'] = $trid;
             $_POST['lang'] = $job->language_code;
             $_POST['skip_sitepress_actions'] = true;
             $postarr = apply_filters('icl_pre_save_pro_translation', $postarr);
             if (isset($element_id)) {
                 // it's an update so dont change the url
                 $postarr['post_name'] = $wpdb->get_var($wpdb->prepare("SELECT post_name FROM {$wpdb->posts} WHERE ID=%d", $element_id));
             }
             if (isset($element_id)) {
                 // it's an update so dont change post date
                 $existing_post = get_post($element_id);
                 $postarr['post_date'] = $existing_post->post_date;
                 $postarr['post_date_gmt'] = $existing_post->post_date_gmt;
             }
             $new_post_id = $this->icl_insert_post($postarr, $job->language_code);
             icl_cache_clear($postarr['post_type'] . 's_per_language');
             // clear post counter per language in cache
             do_action('icl_pro_translation_saved', $new_post_id, $data['fields']);
             // Allow identical slugs
             $post_name = sanitize_title($postarr['post_title']);
             // for Translated documents options:Page URL = Translate
             if (isset($data['fields']['URL']['data']) && $data['fields']['URL']['data']) {
                 $post_name = $data['fields']['URL']['data'];
             }
             $post_name_rewritten = $wpdb->get_var($wpdb->prepare("SELECT post_name FROM {$wpdb->posts} WHERE ID=%d", $new_post_id));
             $post_name_base = $post_name;
             if ($post_name != $post_name_rewritten || $postarr['post_type'] == 'post' || $postarr['post_type'] == 'page') {
                 $incr = 1;
                 do {
                     $exists = $wpdb->get_var($wpdb->prepare("\n\t\t\t\t\t\t\tSELECT p.ID FROM {$wpdb->posts} p\n\t\t\t\t\t\t\t\tJOIN {$wpdb->prefix}icl_translations t ON t.element_id = p.ID\n\t\t\t\t\t\t\tWHERE p.ID <> %d AND t.language_code = %s AND p.post_name=%s\n\t\t\t\t\t\t", $new_post_id, $job->language_code, $post_name));
                     if ($exists) {
                         $incr++;
                     } else {
                         break;
                     }
                     $post_name = $post_name_base . '-' . $incr;
                 } while ($exists);
                 $wpdb->update($wpdb->posts, array('post_name' => $post_name), array('ID' => $new_post_id));
             }
             $ICL_Pro_Translation->_content_fix_links_to_translated_content($new_post_id, $job->language_code);
             // update body translation with the links fixed
             $new_post_content = $wpdb->get_var($wpdb->prepare("SELECT post_content FROM {$wpdb->posts} WHERE ID=%d", $new_post_id));
             foreach ($job->elements as $jel) {
                 if ($jel->field_type == 'body') {
                     $fields_data_translated = $this->encode_field_data($new_post_content, $jel->field_format);
                     break;
                 }
             }
             $wpdb->update($wpdb->prefix . 'icl_translate', array('field_data_translated' => $fields_data_translated), array('job_id' => $data['job_id'], 'field_type' => 'body'));
             // set stickiness
             //is the original post a sticky post?
             remove_filter('option_sticky_posts', array($sitepress, 'option_sticky_posts'));
             // remove filter used to get language relevant stickies. get them all
             $sticky_posts = get_option('sticky_posts');
             $is_original_sticky = $original_post->post_type == 'post' && in_array($original_post->ID, $sticky_posts);
             if ($is_original_sticky && $sitepress_settings['sync_sticky_flag']) {
                 stick_post($new_post_id);
             } else {
                 if ($original_post->post_type == 'post' && !is_null($element_id)) {
                     unstick_post($new_post_id);
                     //just in case - if this is an update and the original post stckiness has changed since the post was sent to translation
                 }
             }
             //sync plugins texts
             foreach ((array) $this->settings['custom_fields_translation'] as $cf => $op) {
                 if ($op == 1) {
                     update_post_meta($new_post_id, $cf, get_post_meta($original_post->ID, $cf, true));
                 }
             }
             // set specific custom fields
             $copied_custom_fields = array('_top_nav_excluded', '_cms_nav_minihome');
             foreach ($copied_custom_fields as $ccf) {
                 $val = get_post_meta($original_post->ID, $ccf, true);
                 update_post_meta($new_post_id, $ccf, $val);
             }
             // sync _wp_page_template
             if ($sitepress_settings['sync_page_template']) {
                 $_wp_page_template = get_post_meta($original_post->ID, '_wp_page_template', true);
                 if (!empty($_wp_page_template)) {
                     update_post_meta($new_post_id, '_wp_page_template', $_wp_page_template);
                 }
             }
             // sync post format
             if ($sitepress_settings['sync_post_format']) {
                 $_wp_post_format = get_post_format($original_post->ID);
                 set_post_format($new_post_id, $_wp_post_format);
             }
             // set the translated custom fields if we have any.
             foreach ((array) $this->settings['custom_fields_translation'] as $field_name => $val) {
                 if ($val == 2) {
                     // should be translated
                     // find it in the translation
                     foreach ($job->elements as $name => $eldata) {
                         if ($eldata->field_data == $field_name) {
                             if (preg_match("/field-(.*?)-name/", $eldata->field_type, $match)) {
                                 $field_id = $match[1];
                                 foreach ($job->elements as $k => $v) {
                                     if ($v->field_type == 'field-' . $field_id) {
                                         $field_translation = self::decode_field_data($v->field_data_translated, $v->field_format);
                                     }
                                     if ($v->field_type == 'field-' . $field_id . '-type') {
                                         $field_type = $v->field_data;
                                     }
                                 }
                                 if (isset($field_type) && $field_type == 'custom_field') {
                                     $field_translation = str_replace('&#0A;', "\n", $field_translation);
                                     // always decode html entities  eg decode &amp; to &
                                     $field_translation = html_entity_decode($field_translation);
                                     update_post_meta($new_post_id, $field_name, $field_translation);
                                 }
                             }
                         }
                     }
                 }
             }
             $link = get_edit_post_link($new_post_id);
             if ($link == '') {
                 // the current user can't edit so just include permalink
                 $link = get_permalink($new_post_id);
             }
             if (is_null($element_id)) {
                 $wpdb->update($wpdb->prefix . 'icl_translations', array('element_id' => $new_post_id), array('translation_id' => $translation_id));
                 $user_message = __('Translation added: ', 'sitepress') . '<a href="' . $link . '">' . $postarr['post_title'] . '</a>.';
             } else {
                 $user_message = __('Translation updated: ', 'sitepress') . '<a href="' . $link . '">' . $postarr['post_title'] . '</a>.';
             }
             // synchronize the page parent for translations
             if ($trid && $sitepress_settings['sync_page_parent']) {
                 $translations = $sitepress->get_element_translations($trid, 'post_' . $postarr['post_type']);
                 foreach ($translations as $target_lang => $target_details) {
                     if ($target_lang != $job->language_code) {
                         if ($target_details->element_id) {
                             $sitepress->fix_translated_parent($new_post_id, $target_details->element_id, $target_lang);
                         }
                     }
                 }
             }
         }
         if (isset($user_message)) {
             $this->messages[] = array('type' => 'updated', 'text' => $user_message);
         }
         if ($this->settings['notification']['completed'] != ICL_TM_NOTIFICATION_NONE) {
             require_once ICL_PLUGIN_PATH . '/inc/translation-management/tm-notification.class.php';
             if ($data['job_id']) {
                 $tn_notification = new TM_Notification();
                 $tn_notification->work_complete($data['job_id'], !is_null($element_id));
             }
         }
         self::set_page_url($new_post_id);
         // redirect to jobs list
         wp_redirect(admin_url(sprintf('admin.php?page=%s&%s=%d', WPML_TM_FOLDER . '/menu/translations-queue.php', is_null($element_id) ? 'added' : 'updated', is_null($element_id) ? $new_post_id : $element_id)));
     } else {
         $this->messages[] = array('type' => 'updated', 'text' => __('Translation (incomplete) saved.', 'sitepress'));
     }
     /*
      * After all previous functionality the terms form the job are assigned to the new post just created or updated.
      * $overwrite is true by default for now.
      */
     $overwrite = true;
     WPML_Terms_Translations::save_all_terms_from_job($data['job_id'], $new_post_id, $overwrite);
     do_action('icl_pro_translation_completed', $new_post_id);
 }
Example #11
0
function icl_sitepress_deactivate()
{
    icl_disable_capabilities();
    wp_clear_scheduled_hook('update_wpml_config_index');
    require_once ICL_PLUGIN_PATH . '/inc/cache.php';
    icl_cache_clear();
}
	/**
	 * Converts a single wprss_feed_item to a post.
	 * 
	 * @param feed 		The wprss_feed_item object to convert
	 * @param source 	The wprss_feed id of the feed item. Used to retrieve settings for conversion.
	 * @since 1.0
	 */
	public static function convert_to_post( $item, $source, $permalink ) {
		WPRSS_FTP_Utils::log( 'Starting conversion to post', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_INFO );
		
		$error_source = 'convert_to_post';
		$source_obj = get_post( $source );

		// If the feed source does not exist, exit
		if ( $source_obj === null || $source === '' ) {
			// unschedule any scheduled updates
			wprss_feed_source_update_stop_schedule( $source );
			WPRSS_FTP_Utils::log_object( 'Source does not exist. Aborting.', $source, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_WARNING );
			return NULL;
		} else {
			// If the feed source exists, but is trashed or paused, exit
			if ( $source_obj->post_status !== 'trash' && !wprss_is_feed_source_active( $source ) ) {
				WPRSS_FTP_Utils::log_object( 'Source is inactive or trashed. Aborting.', $source, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_NOTICE );
				return NULL;
			}
		}

		# If we got NULL, pass it on
		if ( $item === NULL ) {
			WPRSS_FTP_Utils::log( 'Item is null. Aborting.', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_WARNING );
			return NULL;
		}
		# If the item has an empty permalink, log an error message
		if ( empty( $permalink ) ){
			WPRSS_FTP_Utils::log( 'Encounted feed item with no permalink for feed source "' . $source_obj->post_title . '". Possibly a corrupt RSS feed.', $error_source, WPRSS_FTP_Utils::LOG_LEVEL_WARNING );
		}

		# check existence of permalink
		$existing_permalinks = self::get_existing_permalinks( $source );

		# If permalink exists, do nothing
		if ( in_array( $permalink, $existing_permalinks ) ) {
			WPRSS_FTP_Utils::log_object( 'Item with this permalink already exists. Aborting.', $permalink, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_NOTICE );
			return NULL;
		}

		# Get the computed options ( global settings merged against individual settings )
		$options = WPRSS_FTP_Settings::get_instance()->get_computed_options( $source );

		if ( $options['post_type'] === 'wprss_feed_item' ) {
			WPRSS_FTP_Utils::log_object( 'Legacy import method. Aborting.', $source, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_INFO );
			return $item;
		}
		
		self::_prepareItem( $item );

		/*==============================================
		 * 1) DETERMINE THE POST AUTHOR USER
		 */
		WPRSS_FTP_Utils::log( 'Determining post author...', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_INFO );
		// Get author-related options from meta, or from global settings, if not found
		$def_author = $options['def_author'];
		$fallback_author = $options['fallback_author'];
		$author_fallback_method = $options['author_fallback_method'];
		$fallback_user = get_user_by( 'id', $fallback_author );
		if ( ! is_object( $fallback_user ) ) {
			$fallback_user = get_user_by( 'login', $fallback_author );
		}
		$fallback_user = $fallback_user->ID;
		$no_author_found = $options['no_author_found'];

		// Determined user. Start with NULL
		$user = NULL;

		// If using an existing user, we are done.
		if ( $def_author !== '.' ) {
			$user = $def_author;
			WPRSS_FTP_Utils::log( 'Author is preset.', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );
		}
		// If getting feed from author, determine the user to assign to the post
		else {
			/* Get the author from the feed
			 * If author not found - use fallback user
			 */
			if ( $author = $item->get_author() ) {
			    $has_author_name = $author->get_name() !== '' && is_string( $author->get_name() );
			    $has_author_email = $author->get_email() !== '' && is_string( $author->get_email() );
			}
			else {
			    $has_author_name = $has_author_email = false;
			}

			// Author NOT found
			if ( $author === NULL || !( $has_author_name || $has_author_email ) ) {
				// If option to use fallback when no author found, use fallback
				if ( $no_author_found === 'fallback' ) {
					$user = $fallback_user;
					WPRSS_FTP_Utils::log_object( 'Author is a fallback user.', $fallback_user, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );
				}
				// Otherwise, skip the post
				else {
					WPRSS_FTP_Utils::log( 'Author could not be determined. Aborting.', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_WARNING );
					return NULL;
				}
			}
			// Author found
			else {
				WPRSS_FTP_Utils::log( 'Author found in feed.', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );
				$author_name = $author->get_name();
				$author_email = $author->get_email();

				// No author name fix
				if ( !$has_author_name && $has_author_email ) {
					// "Email is actually the name"" fix
					if ( filter_var( $author_email, FILTER_VALIDATE_EMAIL ) === FALSE ) {
						// Set the name to the email, and reset the email
						$author_name = $author_email;
						$author_email = '';
						// Set the flags appropriately
						$has_author_name = TRUE;
						$has_author_email = FALSE;
					}
					else {
						$parts = explode("@", $author_email);
						$author_name = $parts[0];
						$has_author_name = TRUE;
					}
					
					WPRSS_FTP_Utils::log_object( sprintf( 'Author name determined from email "%1$s".', $author_email), $author_name, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );
				}
				
				// No author email fix
				if ( !$has_author_email && $has_author_name ) {
					// Get rid of wwww and everything before it
					$domain_name =  preg_replace( '/^www\./', '', $_SERVER['SERVER_NAME'] );
					// Lowercase the author name, remove the spaces
					$email_username = str_replace( ' ', '', strtolower($author_name) );
					// Remove all disallowed chars
					$email_username = preg_replace('![^\w\d_.]!', '', $email_username);
					// For domains with no TLDN suffix (such as localhost)
					if ( stripos( $domain_name, '.' ) === FALSE ) $domain_name .= '.com';
					// Generate the email
					$author_email = "$email_username@$domain_name";
					$has_author_email = TRUE;
					
					WPRSS_FTP_Utils::log_object( sprintf( 'Author email determined from name "%1$s".', $author_name), $author_email, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );
				}

				$user_obj = FALSE;

				// If email is available, check if a user with this email exists
				$user_obj = get_user_by( 'email', $author_email );
				// If search by email failed, search the email for the login
				if ( !$user_obj ) {
					$user_obj = get_user_by( 'login', $author_email );
				}
				// If search by email failed, search by name
				if ( !$user_obj ) {
					$user_obj = get_user_by( 'login', $author_name );
				}

				// Feed author has a user on site
				if ( $user_obj !== FALSE && isset( $user_obj->ID ) ) {
					$user = $user_obj->ID;
					WPRSS_FTP_Utils::log_object( 'User found in system', $user, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );
				}
				// Author has no user on site
				else {
					$new_user_id = NULL;

					// Fallback method: create user
					if ( $author_fallback_method === 'create' ) {
						$random_password = wp_generate_password( $length = 12, $include_standard_special_chars = false );
						$new_user_id = wp_create_user( $author_name, $random_password, $author_email );
						WPRSS_FTP_Utils::log_object( 'User not found in system. Attempted to create', $author_email, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );
						if ( !$new_user_id || ($is_error = is_wp_error( $new_user_id )) ) {
							WPRSS_FTP_Utils::log_object( 'User could not be created.', $is_error ? $new_user_id->get_error_message() : $author_email, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_NOTICE );
							$new_user_id = null;
						} else {
							// Check if the author has a URI in the feed
							$author_uri = $author->get_link();
							if ( $author_uri !== NULL ) {
								// Filter the meta field and value
								$uri_meta = apply_filters( 'wprss_author_uri_meta_field', 'wprss_author_uri' );
								$author_uri = apply_filters( 'wprss_author_uri', $author_uri, $source );
								// Add the URI as user meta
								add_user_meta( $user, $uri_meta,  $author_uri );
								// Add the URI to the author
								wp_update_user( array(
									'ID'		=>	$new_user_id,
									'user_url'	=>	$author_uri,
								) );
							}

							// Check if the author name has spaces
							if ( strpos( $author_name, ' ' ) !== FALSE ) {
								// Split name into parts
								$split = explode( ' ', $author_name );
								$first_name = '';
								$last_name = '';
								// check if we have more than one parts
								if ( ( $c = count( $split ) ) > 1 ) {
									$m = $c / 2;
									$first_half = array_slice( $split, 0, $m);
									$second_half = array_slice( $split, $m );
									$first_name = implode( ' ', $first_half );
									$last_name = implode( ' ', $second_half );
								}
								// Update the user
								wp_update_user( array(
									'ID'			=>	$new_user_id,
									'first_name'	=>	$first_name,
									'last_name'		=>	$last_name,
								) );
							}
						}
					}

					// Fallback method: existing user
					// OR creating a user failed
					if ( $new_user_id === NULL ) {
						$new_user_id = $fallback_user;
						WPRSS_FTP_Utils::log_object( 'Falling back to existing user', $new_user_id, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );
					}

					$user = $new_user_id;
				}
			}
		}
		
		WPRSS_FTP_Utils::log_object( 'Post author determined', $user, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_INFO );

		// Get WordPress' GMT offset in hours, and PHP's timezone
		$wp_tz = function_exists('wprss_get_timezone_string') ? wprss_get_timezone_string() : get_option( 'timezone_string ' );
		$php_tz = date_default_timezone_get();
		// Set Timezone to WordPress'
		date_default_timezone_set( $wp_tz );
		WPRSS_FTP_Utils::log_object( 'Default timezone temporarily changed', $wp_tz, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );
		
		// Prepare the rest of the post data
		$date_timestamp = ( $options['post_date'] === 'original' && ( $date_timestamp = $item->get_date( 'U' ) ) )
				? $date_timestamp
				: date( 'U' ); // Fall back to current date if explicitly configured, or no date
		
                // Prepare post dates
		$post_date		= date( 'Y-m-d H:i:s', $date_timestamp );
		$post_date_gmt	= gmdate( 'Y-m-d H:i:s', $date_timestamp );
		WPRSS_FTP_Utils::log_object( 'Post timestamp determined', $date_timestamp, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );

		// Reset Timezone to PHP's
		date_default_timezone_set( $php_tz );
		WPRSS_FTP_Utils::log_object( 'Default timezone restored', $php_tz, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );
		
		// Prepare the post tags
		$tags_str = WPRSS_FTP_Meta::get_instance()->get_meta( $source, 'post_tags' );
		$tags = array_map( 'trim', explode( ',', $tags_str ) );
		if( count( $tags ) )
			WPRSS_FTP_Utils::log_object( 'Tags will be added', $tags_str, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );


		/*==============================================
		 * 2) APPLY FILTERS TO POST FIELDS
		 */

		WPRSS_FTP_Utils::log( 'Applying filters to post fields...', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );
		
		WPRSS_FTP_Utils::log( 'Applying post_title filter...', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );
		$post_title		= apply_filters( 'wprss_ftp_converter_post_title',		$item->get_title(), $source );

		WPRSS_FTP_Utils::log( 'Applying post_content filter...', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );
		$post_content	= apply_filters( 'wprss_ftp_converter_post_content',	$item->get_content(), $source );

		WPRSS_FTP_Utils::log( 'Applying post_status filter...', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );
		$post_status 	= apply_filters( 'wprss_ftp_converter_post_status',		$options['post_status'], $source );

		WPRSS_FTP_Utils::log( 'Applying post_comments filter...', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );
		$post_comments 	= apply_filters( 'wprss_ftp_converter_post_comments',	$options['comment_status'], $source );

		WPRSS_FTP_Utils::log( 'Applying post_type filter...', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );
		$post_type 		= apply_filters( 'wprss_ftp_converter_post_type',		$options['post_type'], $source );

		WPRSS_FTP_Utils::log( 'Applying post_format filter...', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );
		$post_format 	= apply_filters( 'wprss_ftp_converter_post_format',		$options['post_format'], $source );

		WPRSS_FTP_Utils::log( 'Applying post_terms filter...', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );
		$post_terms 	= apply_filters( 'wprss_ftp_converter_post_terms',		$options['post_terms'], $source );

		WPRSS_FTP_Utils::log( 'Applying post_taxonomy filter...', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );
		$post_taxonomy 	= apply_filters( 'wprss_ftp_converter_post_taxonomy',	$options['post_taxonomy'], $source );

		WPRSS_FTP_Utils::log( 'Applying permalink filter...', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );
		$permalink 		= apply_filters( 'wprss_ftp_converter_permalink',		$permalink, $source );

		WPRSS_FTP_Utils::log( 'Applying post_author filter...', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );
		$post_author 	= apply_filters( 'wprss_ftp_converter_post_author',		$user, $source );

		WPRSS_FTP_Utils::log( 'Applying post_date filter...', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );
		$post_date		= apply_filters( 'wprss_ftp_converter_post_date',		$post_date, $source );

		WPRSS_FTP_Utils::log( 'Applying post_date_gmt filter...', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );
		$post_date_gmt	= apply_filters( 'wprss_ftp_converter_post_date_gmt',	$post_date_gmt, $source );

		WPRSS_FTP_Utils::log( 'Applying post_tags filter...', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );
		$post_tags		= apply_filters( 'wprss_ftp_converter_post_tags',		$tags, $source );

		WPRSS_FTP_Utils::log( 'Applying post_language filter...', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );
		$post_language 	= apply_filters( 'wprss_ftp_converter_post_language',	$options['post_language'], $source );
		
		WPRSS_FTP_Utils::log( 'Applying post_site filter...', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );
		$post_site		= apply_filters( 'wprss_ftp_converter_post_site',		$options['post_site'], $source );
		
		WPRSS_FTP_Utils::log( 'Filters applied', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );

		$post_comments = ( WPRSS_FTP_Utils::multiboolean( $post_comments ) === TRUE )? 'open' : 'close';
		WPRSS_FTP_Utils::log_object( 'Comments status determined', $post_comments, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );


		/*==============================================
		 * 3) CREATE THE POST
		 */

		// Initialize the excerpt to an empty string
		$post_excerpt = '';

		// Prepare the post data
		WPRSS_FTP_Utils::log( 'Begin creating post...', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );
		$post = array(
			'post_title'		=>	$post_title,
			'post_content'		=>	$post_content,
			'post_excerpt'		=>	$post_excerpt,
			'post_date'			=>	$post_date,
			'post_date_gmt'		=>	$post_date_gmt,
			'post_status'		=>	$post_status,
			'post_type'			=>	$post_type,
			'post_author'		=>	$post_author,
			'tags_input'		=>	implode( ', ' , $post_tags ),
			'comment_status'	=>	$post_comments
		);

		/**
		 * Filter the post args.
		 * @var array $post		Array containing the post fields
		 * @var WP_Post $source		An post that represents the feed source
		 * @var SimplePie_Item $item    The feed item currently being processed
		 */
		$post = apply_filters( 'wprss_ftp_post_args', $post, $source, $item );
		WPRSS_FTP_Utils::log( 'Post args filters applied', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );
		

		/*==============================================
		 * 4) INSERT THE POST
		 */
		if ( defined( 'ICL_SITEPRESS_VERSION' ) )
			@include_once( WP_PLUGIN_DIR . '/sitepress-multilingual-cms/inc/wpml-api.php' );
		if ( defined( 'ICL_LANGUAGE_CODE' ) ) {
			$_POST['icl_post_language'] = $language_code = ICL_LANGUAGE_CODE;
			WPRSS_FTP_Utils::log_object( 'WPMP Detected. Language determined.', $language_code, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_INFO );
		}


		// check for multisite option - and switch blogs if necessaray
		$switch_success = FALSE;
		if ( WPRSS_FTP_Utils::is_multisite() && $post_site !== '' ) {
			global $switched;
			if( $switch_success = switch_to_blog( $post_site ) )
				WPRSS_FTP_Utils::log_object( 'Switched blog.', $post_site, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );
			else
				WPRSS_FTP_Utils::log_object( 'Could not switch to blog.', $post_site, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_NOTICE );
		}

		// Check if embedded content is allowed
		$allow_embedded_content = WPRSS_FTP_Meta::get_instance()->get_meta( $source, 'allow_embedded_content' );

		// If embedded content is allowed, remove KSES filtering
		if ( WPRSS_FTP_Utils::multiboolean( $allow_embedded_content ) === TRUE ) {
			kses_remove_filters();
			WPRSS_FTP_Utils::log( 'Embedded content allowed', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_INFO );
		}

		// Insert the post
		$inserted_id = wp_insert_post( $post );
		
		// If embedded content is allowed, re-add KSES filtering
		if ( WPRSS_FTP_Utils::multiboolean( $allow_embedded_content ) === TRUE ) {
			kses_init_filters();
		}

		if ( !is_wp_error( $inserted_id ) ) {

			if ( is_object( $inserted_id ) ) {
				if ( isset( $inserted_id['ID'] ) ) {
					$inserted_id = $inserted_id['ID'];
				}
				elseif ( isset( $inserted_id->ID ) ) {
					$inserted_id = $inserted_id->ID;
				}
			}
			
			WPRSS_FTP_Utils::log_object( 'Post created', $inserted_id, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_INFO );

			if ( $user === NULL )
				WPRSS_FTP_Utils::log( 'Failed to determine a user for post #$inserted_id', $error_source, WPRSS_FTP_Utils::LOG_LEVEL_WARNING );

			// Update the post format
			set_post_format( $inserted_id, $post_format );

			if ( function_exists( 'wpml_update_translatable_content' ) ) {
				if ( $post_language === '' || $post_language === NULL ) {
					$post_language = ICL_LANGUAGE_CODE;
				}
				// Might be needed by WPML?
				$_POST['icl_post_language '] = $post_language;
				// Update the translation for the created post
				wpml_add_translatable_content( 'post_' . $post_type, $inserted_id, $post_language );
				wpml_update_translatable_content( 'post_' . $post_type, $inserted_id, $post_language );
				icl_cache_clear($post_type.'s_per_language');
				WPRSS_FTP_Utils::log_object( 'Post translated', $post_language, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_INFO );
			}


			/*==============================================
			 * 5) ADD THE POST META DATA
			 */
			WPRSS_FTP_Utils::log( 'Adding post meta', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_INFO );
			$thumbnail = '';
			$enclosure_image = '';
			if ( $enclosure = $item->get_enclosure() ) {
				$thumbnail = $enclosure->get_thumbnail();
				$enclosure_image = $enclosure->get_link();
				$enclosure_player = $enclosure->get_player();

				WPRSS_FTP_Utils::log( 'Item has enclosure', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_INFO );
			}

			// Prepare the post meta, and pass though the wprss_ftp_post_meta filter.
			// Note: Prepend '!' to ignore the 'wprss_ftp_' prefix
			$post_meta_data = apply_filters(
				'wprss_ftp_post_meta',
				array(
					'!wprss_item_permalink'		=>	$permalink,
					'feed_source'				=>	$source,
					'media:thumbnail'			=>	$thumbnail,
					'enclosure:thumbnail'		=>	$enclosure_image,
					'enclosure_link'			=>	$enclosure_image, // Included twice for code readablity
					'enclosure_player'			=>	$enclosure_player,
					'import_date'				=>	time(),
					'!wprss_item_date'			=>	$date_timestamp, // Required by core
					'!wprss_feed_id'			=>	$source,
				),
				$inserted_id,
				$source,
				$item
			);
			WPRSS_FTP_Utils::log_object( 'Post meta filters applied', $inserted_id, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );

			// Insert the post meta
			WPRSS_FTP_Meta::get_instance()->add_meta( $inserted_id, $post_meta_data );
			WPRSS_FTP_Utils::log( 'Post meta added', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_INFO );



			/*==============================================
			 * 6) ADD THE TAXONOMY TERMS
			 *
			
			$all_post_terms = ( !is_array( $post_terms ) )? array() : $post_terms;

			// Check if the source auto creates taxonomy terms
			$auto_create_terms = WPRSS_FTP_Meta::get_instance()->get_meta( $source, 'post_auto_tax_terms' );
			// If yes ...
			if ( WPRSS_FTP_Utils::multiboolean( $auto_create_terms ) === TRUE ) {
				// Get the feed categories
				$categories = $item->get_categories();
				
				if ( is_array( $categories ) && count( $categories ) > 0 ) {
					// For each category in the feed item

					// Turn the categories into an array
					$new_categories = array();
					foreach( $categories as $cat ) {
						$new_categories[] = array(
							'name'	=>	$cat->get_label(),
							'args'	=>	array(),
						);
					}

					// Filter the categories
					$categories = apply_filters( 'wprss_auto_create_terms', $new_categories, $post_taxonomy, $source );

					foreach ( $categories as $category_obj ) {
						$category = $category_obj['name'];
						// Find the term that matches that category
						$cat_term = term_exists( $category , $post_taxonomy );

						// If the term does not exist create it
						if ( $cat_term === 0 || $cat_term === NULL ) {

							// check if parent field exists, and turn the slug into an id
							if ( isset( $category_obj['args']['parent'] ) ) {
								// Get the slug, and find the term by the slug
								$parent_slug = $category_obj['args']['parent'];
								$parent_term = get_term_by( 'slug', $parent_slug, $post_taxonomy, 'ARRAY_A' );
								// If term not found, removed the parent arg
								if ( $parent_term === FALSE ) {
									unset( $category_obj['args']['parent'] );
								}
								// Otherwise, change the slug to the id
								else $category_obj['args']['parent'] = intval( $parent_term['term_id'] );
							}

							// Insert the term
							$cat_term = wp_insert_term( $category, $post_taxonomy, $category_obj['args'] );
							delete_option($post_taxonomy."_children"); // clear the cache
						}
						$term_id = $cat_term['term_id'];

						$term_obj = get_term_by( 'id', $term_id, $post_taxonomy, 'ARRAY_A' );

						if ( $term_obj !== FALSE && $term_obj !== NULL ) {

							if ( !is_array($all_post_terms) ) {
								WPRSS_FTP_Utils::log_object( 'The $all_post_terms variable is not an array:', $all_post_terms, $error_source );
							} else {
								// Add it to the list of terms to add
								$all_post_terms[] = $term_obj['slug'];
							}

						}
					}
				}
			}

			$wp_categories_return = wp_set_object_terms( $inserted_id, $all_post_terms, $post_taxonomy, FALSE );
			if ( !is_array( $wp_categories_return ) ) {
				WPRSS_FTP_Utils::log_object( "Possible error while inserting taxonomy terms for post #$inserted_id:", $all_post_terms );
			}
			*/
			wprss_ftp_add_taxonomies_to_post( $inserted_id, $source, $item );
			WPRSS_FTP_Utils::log( 'Added taxonomies', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_INFO );

			/*==============================================
			 * 8) CUSTOM FIELD MAPPING
			 */

			WPRSS_FTP_Utils::log( 'Mapping custom fields', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_INFO );
			
			// Get the namespaces
			$cfm_namespaces = WPRSS_FTP_Meta::get_instance()->get_meta( $source, 'rss_namespaces' );
			$cfm_namespaces = ( $cfm_namespaces === '' )? array() : $cfm_namespaces;
			// Get the tags
			$cfm_tags = WPRSS_FTP_Meta::get_instance()->get_meta( $source, 'rss_tags' );
			$cfm_tags = ( $cfm_tags === '' )? array() : $cfm_tags;
			// Get the custom fields
			$cfm_fields = WPRSS_FTP_Meta::get_instance()->get_meta( $source, 'custom_fields' );
			$cfm_fields = ( $cfm_fields === '' )? array() : $cfm_fields;

			// For each custom field mapping
			for ( $i = 0; $i < count( $cfm_namespaces ); $i++ ) {
				// Get the URL of the namespace
				$namespace_url = WPRSS_FTP_Settings::get_namespace_url( $cfm_namespaces[$i] );
				// If the namespace url is NULL (namespace no longer exists in the settings), skip to next mapping
				if ( $namespace_url === NULL ) continue;

				// Match the syntax "tagname[attrib]" in the tag name
				preg_match('/([^\[]+) (\[ ([^\]]+) \])?/x', $cfm_tags[$i], $m);
				// If no matches, stop. Tag name is not correct. Possibly empty
				if ( !is_array($m) || count($m) < 2 ) continue;
				// Get the tag and attribute from the matches
				$tag_name = $m[1];
				$attrib = ( isset( $m[3] ) )? $m[3] : NULL;

				// Get the tag from the feed item
				$item_tags = $item->get_item_tags( $namespace_url, $tag_name );
				// Check if the tag exists. If not, skip to next mapping
				if ( !isset( $item_tags[0] ) ) continue;

				// Get the first tag found, and get its data contents
				$item_tag = $item_tags[0];
				$attribs = $item_tag['attribs'][''];
				// If not using an attribute, simply get the text data
				if ( $attrib === NULL ) {
					$data = $item_tag['data'];
				}
				// Otherwise, check if the attribute exists
				elseif ( isset( $attribs[ $attrib ] ) ) {
					$data = $attribs[ $attrib ];
				}
				// Otherwise do nothing
				else {
					continue;
				}

				// Put the data in the inserted post's meta, using the custom field as the meta key
				update_post_meta( $inserted_id, $cfm_fields[$i], $data );
				WPRSS_FTP_Utils::log_object( 'Post meta updated', $i+1 . '/' . count($cfm_namespaces), __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );
			}
			
			WPRSS_FTP_Utils::log( 'Custom fields mapped', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_INFO );

			$post = get_post( $inserted_id );
			if ( $post === NULL || $post === FALSE ) {
				$title = $item->get_title();
				WPRSS_FTP_Utils::log( "An error occurred while converting a feed item into a post \"$title\". Kindly report this error to support@wprssaggregator.com" );
			}
			else {
				WPRSS_FTP_Utils::log_object( 'Post created', $inserted_id, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_INFO );
				do_action( 'wprss_ftp_converter_inserted_post', $inserted_id, $source );
				self::trim_words_for_post( $inserted_id, $source );
			}
		}
		else {
			WPRSS_FTP_Utils::log( 'Failed to insert post. $inserted_id = ' . $inserted_id, $error_source );
		}

		// If multisite and blog was switched, switch back to current blog
		if ( WPRSS_FTP_Utils::is_multisite() && $switch_success === TRUE ) {
			restore_current_blog();
			WPRSS_FTP_Utils::log( 'Blog restored', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );
		}
		
		WPRSS_FTP_Utils::log( 'Conversion complete', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_INFO );

		// Filter the return value
		$return = apply_filters( 'wprss_ftp_converter_return_post_'.$inserted_id, TRUE );
		// If the return is still TRUE, ensure that the post that was created was not deleted
		if ( $return === TRUE ) {
			$post = get_post( $inserted_id );
			$return = ( $post !== NULL && $post !== FALSE );
		}
		// Log return value if anything other than TRUE
		else {
			wprss_log( 'Recieved "'.$return.'" as a return value for post #'.$inserted_id, NULL, WPRSS_LOG_LEVEL_SYSTEM );
		}

		return $return;
	}
 function delete_language($lang_id)
 {
     global $wpdb, $sitepress;
     $lang = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$wpdb->prefix}icl_languages WHERE id=%d", $lang_id));
     if ($lang) {
         if (in_array($lang->code, $this->built_in_languages)) {
             $error = __("Error: This is a built in language. You can't delete it.", 'sitepress');
         } else {
             $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->prefix}icl_languages WHERE id=%d", $lang_id));
             $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->prefix}icl_languages_translations WHERE language_code=%s", $lang->code));
             $translation_ids = $wpdb->get_col($wpdb->prepare("SELECT translation_id FROM {$wpdb->prefix}icl_translations WHERE language_code=%s", $lang->code));
             if ($translation_ids) {
                 $rids = $wpdb->get_col("SELECT rid FROM {$wpdb->prefix}icl_translation_status WHERE translation_id IN (" . wpml_prepare_in($translation_ids, '%d') . ")");
                 if ($rids) {
                     $job_ids = $wpdb->get_col("SELECT job_id FROM {$wpdb->prefix}icl_translate_job WHERE rid IN (" . wpml_prepare_in($rids, '%d') . ")");
                     if ($job_ids) {
                         $wpdb->query("DELETE FROM {$wpdb->prefix}icl_translate WHERE job_id IN (" . wpml_prepare_in($job_ids, '%d') . ")");
                     }
                 }
             }
             // delete posts
             $post_ids = $wpdb->get_col($wpdb->prepare("SELECT element_id FROM {$wpdb->prefix}icl_translations WHERE element_type LIKE %s AND language_code=%s", array(wpml_like_escape('post_') . '%', $lang->code)));
             remove_action('delete_post', array($sitepress, 'delete_post_actions'));
             foreach ($post_ids as $post_id) {
                 wp_delete_post($post_id, true);
             }
             add_action('delete_post', array($sitepress, 'delete_post_actions'));
             // delete terms
             remove_action('delete_term', array($sitepress, 'delete_term'), 1, 3);
             $tax_ids = $wpdb->get_col($wpdb->prepare("SELECT element_id FROM {$wpdb->prefix}icl_translations WHERE element_type LIKE %s AND language_code=%s", array(wpml_like_escape('tax_') . '%', $lang->code)));
             foreach ($tax_ids as $tax_id) {
                 $row = $wpdb->get_row($wpdb->prepare("SELECT term_id, taxonomy FROM {$wpdb->term_taxonomy} WHERE term_taxonomy_id=%d", $tax_id));
                 if ($row) {
                     wp_delete_term($row->term_id, $row->taxonomy);
                 }
             }
             add_action('delete_term', array($sitepress, 'delete_term'), 1, 3);
             // delete comments
             global $IclCommentsTranslation;
             remove_action('delete_comment', array($IclCommentsTranslation, 'delete_comment_actions'));
             foreach ($post_ids as $post_id) {
                 wp_delete_post($post_id, true);
             }
             add_action('delete_comment', array($IclCommentsTranslation, 'delete_comment_actions'));
             $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->prefix}icl_translations WHERE language_code=%s", $lang->code));
             $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->prefix}icl_strings WHERE language=%s", $lang->code));
             $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->prefix}icl_string_translations WHERE language=%s", $lang->code));
             $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->prefix}icl_locale_map WHERE code=%s", $lang->code));
             $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->prefix}icl_flags WHERE lang_code=%s", $lang->code));
             icl_cache_clear(false);
             $sitepress->icl_translations_cache->clear();
             $sitepress->clear_flags_cache();
             $sitepress->icl_language_name_cache->clear();
             $this->message(sprintf(__("The language %s was deleted.", 'sitepress'), '<strong>' . $lang->code . '</strong>'));
         }
     } else {
         $error = __('Error: Language not found.', 'sitepress');
     }
     if (!empty($error)) {
         $this->error($error);
     }
 }
 function save_translation($data)
 {
     global $wpdb, $sitepress, $sitepress_settings, $ICL_Pro_Translation;
     $new_post_id = false;
     $is_incomplete = false;
     foreach ($data['fields'] as $field) {
         $this->_save_translation_field($field['tid'], $field);
         if (!isset($field['finished']) || !$field['finished']) {
             $is_incomplete = true;
         }
     }
     //check if translation job still exists
     $job_id = $wpdb->get_var($wpdb->prepare("SELECT count(1) FROM {$wpdb->prefix}icl_translate_job WHERE job_id=%d", $data['job_id']));
     if ($job_id == 0) {
         wp_redirect(admin_url(sprintf('admin.php?page=%s', WPML_TM_FOLDER . '/menu/translations-queue.php', 'job-cancelled')));
         exit;
     }
     if (!empty($data['complete']) && !$is_incomplete) {
         $wpdb->update($wpdb->prefix . 'icl_translate_job', array('translated' => 1), array('job_id' => $data['job_id']));
         $rid = $wpdb->get_var($wpdb->prepare("SELECT rid FROM {$wpdb->prefix}icl_translate_job WHERE job_id=%d", $data['job_id']));
         $translation_id = $wpdb->get_var($wpdb->prepare("SELECT translation_id FROM {$wpdb->prefix}icl_translation_status WHERE rid=%d", $rid));
         $wpdb->update($wpdb->prefix . 'icl_translation_status', array('status' => ICL_TM_COMPLETE, 'needs_update' => 0), array('rid' => $rid));
         list($element_id, $trid) = $wpdb->get_row($wpdb->prepare("SELECT element_id, trid FROM {$wpdb->prefix}icl_translations WHERE translation_id=%d", $translation_id), ARRAY_N);
         $job = $this->get_translation_job($data['job_id'], true);
         $parts = explode('_', $job->original_doc_id);
         if ($parts[0] == 'external') {
             // Translations are saved in the string table for 'external' types
             $id = array_pop($parts);
             unset($parts[0]);
             $type = implode('_', $parts);
             foreach ($job->elements as $field) {
                 if ($field->field_translate) {
                     if (function_exists('icl_st_is_registered_string')) {
                         $string_id = icl_st_is_registered_string($type, $id . '_' . $field->field_type);
                         if (!$string_id) {
                             icl_register_string($type, $id . '_' . $field->field_type, self::decode_field_data($field->field_data, $field->field_format));
                             $string_id = icl_st_is_registered_string($type, $id . '_' . $field->field_type);
                         }
                         if ($string_id) {
                             icl_add_string_translation($string_id, $job->language_code, self::decode_field_data($field->field_data_translated, $field->field_format), ICL_STRING_TRANSLATION_COMPLETE);
                         }
                     }
                 }
             }
         } else {
             if (!is_null($element_id)) {
                 $postarr['ID'] = $_POST['post_ID'] = $element_id;
             }
             foreach ($job->elements as $field) {
                 switch ($field->field_type) {
                     case 'title':
                         $postarr['post_title'] = self::decode_field_data($field->field_data_translated, $field->field_format);
                         break;
                     case 'body':
                         $postarr['post_content'] = self::decode_field_data($field->field_data_translated, $field->field_format);
                         break;
                     case 'excerpt':
                         $postarr['post_excerpt'] = self::decode_field_data($field->field_data_translated, $field->field_format);
                         break;
                     case 'URL':
                         $postarr['post_name'] = self::decode_field_data($field->field_data_translated, $field->field_format);
                         break;
                     case 'tags':
                         $tags = self::decode_field_data($field->field_data_translated, $field->field_format);
                         $original_tags = self::decode_field_data($field->field_data, $field->field_format);
                         // create tags that don't exist
                         foreach ($tags as $k => $t) {
                             $thetag = $sitepress->get_term_by_name_and_lang($t, 'post_tag', $job->language_code);
                             $tags[$k] = $t;
                             // Save $t as we may have added @.lang to it
                             if (empty($thetag)) {
                                 $the_original_tag = $sitepress->get_term_by_name_and_lang($original_tags[$k], 'post_tag', $job->source_language_code);
                                 $tmp = self::icl_insert_term($t, 'post_tag', array(), $job->language_code);
                                 if (!is_wp_error($tmp) && isset($tmp['term_taxonomy_id'])) {
                                     $sitepress->set_term_translation($the_original_tag, $tmp['term_taxonomy_id'], 'post_tag', $job->language_code, $job->source_language_code);
                                 }
                             }
                         }
                         $postarr['tags_input'] = join(',', $tags);
                         $postarr['tax_input']['post_tag'] = $tags;
                         break;
                     case 'categories':
                         $cats = self::decode_field_data($field->field_data_translated, $field->field_format);
                         $original_cats = self::decode_field_data($field->field_data, $field->field_format);
                         $missing_parents = array();
                         $cat_ids = array();
                         foreach ($cats as $k => $c) {
                             $parent_missing = false;
                             $thecat = $sitepress->get_term_by_name_and_lang($c, 'category', $job->language_code);
                             $cat_id = 0;
                             if (empty($thecat)) {
                                 $the_original_cat = $sitepress->get_term_by_name_and_lang($original_cats[$k], 'category', $job->source_language_code);
                                 if ($the_original_cat) {
                                     $original_parent_id = $wpdb->get_var("SELECT parent FROM {$wpdb->term_taxonomy} WHERE term_taxonomy_id=" . $the_original_cat->term_taxonomy_id);
                                 } else {
                                     $original_parent_id = false;
                                 }
                                 if ($original_parent_id) {
                                     $translated_parent_id = icl_object_id($original_parent_id, 'category', false, $job->language_code);
                                     if (!$translated_parent_id) {
                                         // The parent is missing. Possibly because we haven't created a translation of it yet
                                         $parent_missing = true;
                                     }
                                 } else {
                                     $translated_parent_id = 0;
                                 }
                                 $tmp = self::icl_insert_term($c, 'category', array('parent' => $translated_parent_id), $job->language_code);
                                 if (!is_wp_error($tmp) && isset($tmp['term_taxonomy_id'])) {
                                     $sitepress->set_term_translation($the_original_cat, $tmp['term_taxonomy_id'], 'category', $job->language_code, $job->source_language_code);
                                     $cat_id = $tmp['term_id'];
                                 }
                             } else {
                                 $cat_id = $thecat->term_id;
                             }
                             if ($cat_id) {
                                 $cat_ids[] = $cat_id;
                             }
                             if ($parent_missing && isset($original_parent_id)) {
                                 $missing_parents[$cat_id] = $original_parent_id;
                             }
                         }
                         // Double check missing parents as they might be available now.
                         foreach ($missing_parents as $cat_id => $original_parent_id) {
                             $translated_parent_id = icl_object_id($original_parent_id, 'category', false, $job->language_code);
                             $cat_trid = $sitepress->get_element_trid($cat_id, 'tax_category');
                             $buf_post = isset($_POST) ? $_POST : array();
                             $_POST['icl_trid'] = $cat_trid;
                             $_POST['icl_translation_of'] = $wpdb->get_var($wpdb->prepare("SELECT element_id FROM {$wpdb->prefix}icl_translations WHERE element_type='tax_category' AND trid=%d AND source_language_code IS NULL", $cat_trid));
                             $_POST['icl_tax_category_language'] = $job->language_code;
                             wp_update_term($cat_id, 'category', array('parent' => $translated_parent_id));
                             $_POST = $buf_post;
                             $cat_tax_id = $wpdb->get_var($wpdb->prepare("SELECT term_taxonomy_id FROM {$wpdb->term_taxonomy} WHERE term_id=%d AND taxonomy='category'", $cat_id));
                             $wpdb->update($wpdb->prefix . 'icl_translations', array('language_code' => $job->language_code, 'trid' => $cat_trid, 'source_language_code' => $job->source_language_code), array('element_type' => 'tax_category', 'element_id' => $cat_tax_id));
                             $sitepress->update_terms_relationship_cache(array($translated_parent_id, $cat_id), 'category');
                         }
                         $postarr['post_category'] = $cat_ids;
                         if ($cat_ids) {
                             $sitepress->update_terms_relationship_cache($missing_parents, 'category');
                             $sitepress->update_terms_relationship_cache($cat_ids, 'category');
                         }
                         break;
                     default:
                         if (in_array($field->field_type, $sitepress->get_translatable_taxonomies(false, $job->original_post_type))) {
                             $taxs = self::decode_field_data($field->field_data_translated, $field->field_format);
                             $missing_parents = array();
                             $original_taxs = self::decode_field_data($field->field_data, $field->field_format);
                             $taxonomy = $field->field_type;
                             $taxonomy_obj = get_taxonomy($taxonomy);
                             // array = hierarchical, string = non-hierarchical.
                             if ($taxonomy_obj->hierarchical) {
                                 $missing_parents = array();
                             }
                             $alltaxs = $tax_ids = array();
                             foreach ($taxs as $k => $c) {
                                 $the_original_tax_parent = false;
                                 $parent_missing = false;
                                 if ($taxonomy_obj->hierarchical) {
                                     $parent_missing = false;
                                 }
                                 $thetax = $sitepress->get_term_by_name_and_lang($c, $taxonomy, $job->language_code);
                                 $taxs[$k] = $c;
                                 // Save $c as we may have added @.lang to it
                                 if (empty($thetax)) {
                                     $the_original_tax = $sitepress->get_term_by_name_and_lang($original_taxs[$k], $taxonomy, $job->source_language_code);
                                     if ($taxonomy_obj->hierarchical && $the_original_tax) {
                                         $the_original_tax_parent = $wpdb->get_var("SELECT parent FROM {$wpdb->term_taxonomy} WHERE term_taxonomy_id=" . $the_original_tax->term_taxonomy_id);
                                     }
                                     if ($the_original_tax_parent) {
                                         $translated_parent_id = icl_object_id($the_original_tax_parent, $taxonomy, false, $job->language_code);
                                         if (!$translated_parent_id) {
                                             // The parent is missing. Possibly because we haven't created a translation of it yet
                                             $parent_missing = true;
                                         }
                                     } else {
                                         $translated_parent_id = 0;
                                     }
                                     $tmp = self::icl_insert_term($c, $taxonomy, array('parent' => $translated_parent_id), $job->language_code);
                                     if (isset($tmp['term_taxonomy_id'])) {
                                         $sitepress->set_term_translation($the_original_tax, $tmp['term_taxonomy_id'], $taxonomy, $job->language_code, $job->source_language_code);
                                     }
                                     $tax_id = $tmp['term_id'];
                                 } else {
                                     $tax_id = $thetax->term_id;
                                 }
                                 if ($taxonomy_obj->hierarchical && $parent_missing) {
                                     $missing_parents[$tax_id] = $the_original_tax_parent;
                                 }
                                 $tax_ids[] = $tax_id;
                                 $alltaxs[] = $c;
                             }
                             // Double check missing parents as they might be available now.
                             foreach ($missing_parents as $tax_id => $the_original_tax_parent) {
                                 $translated_parent_id = icl_object_id($the_original_tax_parent, $taxonomy, false, $job->language_code);
                                 $tax_trid = $sitepress->get_element_trid($tax_id, 'tax_' . $taxonomy);
                                 $buf_post = isset($_POST) ? $_POST : array();
                                 $_POST['icl_trid'] = $tax_trid;
                                 $_POST['icl_translation_of'] = $wpdb->get_var($wpdb->prepare("SELECT element_id FROM {$wpdb->prefix}icl_translations WHERE element_type=%s AND trid=%d AND source_language_code IS NULL", 'tax_' . $taxonomy, $tax_trid));
                                 $_POST['icl_tax_' . $taxonomy . '_language'] = $job->language_code;
                                 wp_update_term($tax_id, $taxonomy, array('parent' => $translated_parent_id));
                                 $_POST = $buf_post;
                                 $tax_tax_id = $wpdb->get_var($wpdb->prepare("SELECT term_taxonomy_id FROM {$wpdb->term_taxonomy} WHERE term_id=%d AND taxonomy=%s", $tax_id, $taxonomy));
                                 $wpdb->update($wpdb->prefix . 'icl_translations', array('language_code' => $job->language_code, 'trid' => $tax_trid, 'source_language_code' => $job->source_language_code), array('element_type' => 'tax_' . $taxonomy, 'element_id' => $tax_tax_id));
                                 $sitepress->update_terms_relationship_cache(array($translated_parent_id, $tax_id), $taxonomy);
                             }
                             if ($taxonomy_obj->hierarchical) {
                                 $postarr['tax_input'][$taxonomy] = $tax_ids;
                             } else {
                                 $postarr['tax_input'][$taxonomy] = $taxs;
                             }
                         }
                 }
             }
             $original_post = get_post($job->original_doc_id);
             $postarr['post_author'] = $original_post->post_author;
             $postarr['post_type'] = $original_post->post_type;
             if ($sitepress_settings['sync_comment_status']) {
                 $postarr['comment_status'] = $original_post->comment_status;
             }
             if ($sitepress_settings['sync_ping_status']) {
                 $postarr['ping_status'] = $original_post->ping_status;
             }
             if ($sitepress_settings['sync_page_ordering']) {
                 $postarr['menu_order'] = $original_post->menu_order;
             }
             if ($sitepress_settings['sync_private_flag'] && $original_post->post_status == 'private') {
                 $postarr['post_status'] = 'private';
             }
             if ($sitepress_settings['sync_post_date']) {
                 $postarr['post_date'] = $original_post->post_date;
             }
             //set as draft or the same status as original post
             $postarr['post_status'] = !$sitepress_settings['translated_document_status'] ? 'draft' : $original_post->post_status;
             if ($original_post->post_parent) {
                 $post_parent_trid = $wpdb->get_var("SELECT trid FROM {$wpdb->prefix}icl_translations\n                        WHERE element_type='post_{$original_post->post_type}' AND element_id='{$original_post->post_parent}'");
                 if ($post_parent_trid) {
                     $parent_id = $wpdb->get_var("SELECT element_id FROM {$wpdb->prefix}icl_translations\n                            WHERE element_type='post_{$original_post->post_type}' AND trid='{$post_parent_trid}' AND language_code='{$job->language_code}'");
                 }
             }
             if (isset($parent_id) && $sitepress_settings['sync_page_parent']) {
                 $_POST['post_parent'] = $postarr['post_parent'] = $parent_id;
                 $_POST['parent_id'] = $postarr['parent_id'] = $parent_id;
             }
             $_POST['trid'] = $trid;
             $_POST['lang'] = $job->language_code;
             $_POST['skip_sitepress_actions'] = true;
             $postarr = apply_filters('icl_pre_save_pro_translation', $postarr);
             if (isset($element_id)) {
                 // it's an update so dont change the url
                 $postarr['post_name'] = $wpdb->get_var($wpdb->prepare("SELECT post_name FROM {$wpdb->posts} WHERE ID=%d", $element_id));
             }
             if (isset($element_id)) {
                 // it's an update so dont change post date
                 $existing_post = get_post($element_id);
                 $postarr['post_date'] = $existing_post->post_date;
                 $postarr['post_date_gmt'] = $existing_post->post_date_gmt;
             }
             $new_post_id = $this->icl_insert_post($postarr, $job->language_code);
             icl_cache_clear($postarr['post_type'] . 's_per_language');
             // clear post counter per language in cache
             // set taxonomies for users with limited caps
             if (!current_user_can('manage-categories') && !empty($postarr['tax_input'])) {
                 foreach ($postarr['tax_input'] as $taxonomy => $terms) {
                     wp_set_post_terms($new_post_id, $terms, $taxonomy, FALSE);
                     // true to append to existing tags | false to replace existing tags
                 }
             }
             do_action('icl_pro_translation_saved', $new_post_id, $data['fields']);
             // Allow identical slugs
             $post_name = sanitize_title($postarr['post_title']);
             $post_name_rewritten = $wpdb->get_var($wpdb->prepare("SELECT post_name FROM {$wpdb->posts} WHERE ID=%d", $new_post_id));
             $post_name_base = $post_name;
             if ($post_name != $post_name_rewritten) {
                 $incr = 1;
                 do {
                     $exists = $wpdb->get_var($wpdb->prepare("\n                            SELECT p.ID FROM {$wpdb->posts} p\n                                JOIN {$wpdb->prefix}icl_translations t ON t.element_id = p.ID AND t.element_type=%s\n                            WHERE p.ID <> %d AND t.language_code = %s AND p.post_name=%s\n                        ", 'post_' . $postarr['post_type'], $new_post_id, $job->language_code, $post_name));
                     if ($exists) {
                         $incr++;
                     } else {
                         break;
                     }
                     $post_name = $post_name_base . '-' . $incr;
                 } while ($exists);
                 $wpdb->update($wpdb->posts, array('post_name' => $post_name), array('ID' => $new_post_id));
             }
             $ICL_Pro_Translation->_content_fix_links_to_translated_content($new_post_id, $job->language_code);
             // update body translation with the links fixed
             $new_post_content = $wpdb->get_var($wpdb->prepare("SELECT post_content FROM {$wpdb->posts} WHERE ID=%d", $new_post_id));
             foreach ($job->elements as $jel) {
                 if ($jel->field_type == 'body') {
                     $fields_data_translated = $this->encode_field_data($new_post_content, $jel->field_format);
                     break;
                 }
             }
             $wpdb->update($wpdb->prefix . 'icl_translate', array('field_data_translated' => $fields_data_translated), array('job_id' => $data['job_id'], 'field_type' => 'body'));
             // set stickiness
             //is the original post a sticky post?
             remove_filter('option_sticky_posts', array($sitepress, 'option_sticky_posts'));
             // remove filter used to get language relevant stickies. get them all
             $sticky_posts = get_option('sticky_posts');
             $is_original_sticky = $original_post->post_type == 'post' && in_array($original_post->ID, $sticky_posts);
             if ($is_original_sticky && $sitepress_settings['sync_sticky_flag']) {
                 stick_post($new_post_id);
             } else {
                 if ($original_post->post_type == 'post' && !is_null($element_id)) {
                     unstick_post($new_post_id);
                     //just in case - if this is an update and the original post stckiness has changed since the post was sent to translation
                 }
             }
             //sync plugins texts
             foreach ((array) $this->settings['custom_fields_translation'] as $cf => $op) {
                 if ($op == 1) {
                     update_post_meta($new_post_id, $cf, get_post_meta($original_post->ID, $cf, true));
                 }
             }
             // set specific custom fields
             $copied_custom_fields = array('_top_nav_excluded', '_cms_nav_minihome');
             foreach ($copied_custom_fields as $ccf) {
                 $val = get_post_meta($original_post->ID, $ccf, true);
                 update_post_meta($new_post_id, $ccf, $val);
             }
             // sync _wp_page_template
             if ($sitepress_settings['sync_page_template']) {
                 $_wp_page_template = get_post_meta($original_post->ID, '_wp_page_template', true);
                 if (!empty($_wp_page_template)) {
                     update_post_meta($new_post_id, '_wp_page_template', $_wp_page_template);
                 }
             }
             // sync post format
             if ($sitepress_settings['sync_post_format']) {
                 $_wp_post_format = get_post_format($original_post->ID);
                 set_post_format($new_post_id, $_wp_post_format);
             }
             // set the translated custom fields if we have any.
             foreach ((array) $this->settings['custom_fields_translation'] as $field_name => $val) {
                 if ($val == 2) {
                     // should be translated
                     // find it in the translation
                     foreach ($job->elements as $name => $eldata) {
                         if ($eldata->field_data == $field_name) {
                             if (preg_match("/field-(.*?)-name/", $eldata->field_type, $match)) {
                                 $field_id = $match[1];
                                 foreach ($job->elements as $k => $v) {
                                     if ($v->field_type == 'field-' . $field_id) {
                                         $field_translation = self::decode_field_data($v->field_data_translated, $v->field_format);
                                     }
                                     if ($v->field_type == 'field-' . $field_id . '-type') {
                                         $field_type = $v->field_data;
                                     }
                                 }
                                 if (isset($field_type) && $field_type == 'custom_field') {
                                     $field_translation = str_replace('&#0A;', "\n", $field_translation);
                                     // always decode html entities  eg decode &amp; to &
                                     $field_translation = html_entity_decode($field_translation);
                                     update_post_meta($new_post_id, $field_name, $field_translation);
                                 }
                             }
                         }
                     }
                 }
             }
             $link = get_edit_post_link($new_post_id);
             if ($link == '') {
                 // the current user can't edit so just include permalink
                 $link = get_permalink($new_post_id);
             }
             if (is_null($element_id)) {
                 $wpdb->update($wpdb->prefix . 'icl_translations', array('element_id' => $new_post_id), array('translation_id' => $translation_id));
                 $user_message = __('Translation added: ', 'sitepress') . '<a href="' . $link . '">' . $postarr['post_title'] . '</a>.';
             } else {
                 $user_message = __('Translation updated: ', 'sitepress') . '<a href="' . $link . '">' . $postarr['post_title'] . '</a>.';
             }
             // synchronize the page parent for translations
             if ($trid && $sitepress_settings['sync_page_parent']) {
                 $translations = $sitepress->get_element_translations($trid, 'post_' . $postarr['post_type']);
                 foreach ($translations as $target_lang => $target_details) {
                     if ($target_lang != $job->language_code) {
                         if ($target_details->element_id) {
                             $sitepress->fix_translated_parent($new_post_id, $target_details->element_id, $target_lang);
                         }
                     }
                 }
             }
         }
         if (isset($user_message)) {
             $this->messages[] = array('type' => 'updated', 'text' => $user_message);
         }
         if ($this->settings['notification']['completed'] != ICL_TM_NOTIFICATION_NONE) {
             require_once ICL_PLUGIN_PATH . '/inc/translation-management/tm-notification.class.php';
             if ($data['job_id']) {
                 $tn_notification = new TM_Notification();
                 $tn_notification->work_complete($data['job_id'], !is_null($element_id));
             }
         }
         self::set_page_url($new_post_id);
         // redirect to jobs list
         wp_redirect(admin_url(sprintf('admin.php?page=%s&%s=%d', WPML_TM_FOLDER . '/menu/translations-queue.php', is_null($element_id) ? 'added' : 'updated', is_null($element_id) ? $new_post_id : $element_id)));
     } else {
         $this->messages[] = array('type' => 'updated', 'text' => __('Translation (incomplete) saved.', 'sitepress'));
     }
     do_action('icl_pro_translation_completed', $new_post_id);
 }
function icl_plugin_upgrade()
{
    global $wpdb, $sitepress_settings, $sitepress;
    if (defined('ICL_DEBUG_MODE') && ICL_DEBUG_MODE && (is_writable(ICL_PLUGIN_PATH) || is_writable(ICL_PLUGIN_PATH . '/upgrade.log'))) {
        $mig_debug = @fopen(ICL_PLUGIN_PATH . '/upgrade.log', 'w');
    } else {
        $mig_debug = false;
    }
    $iclsettings = get_option('icl_sitepress_settings');
    // upgrade actions
    // 1. reset ajx_health_flag
    $iclsettings['ajx_health_checked'] = 0;
    update_option('icl_sitepress_settings', $iclsettings);
    // clear any caches
    if ($mig_debug) {
        fwrite($mig_debug, "Clearing cache \n");
    }
    require_once ICL_PLUGIN_PATH . '/inc/cache.php';
    icl_cache_clear('locale_cache_class');
    icl_cache_clear('flags_cache_class');
    icl_cache_clear('language_name_cache_class');
    icl_cache_clear('cms_nav_offsite_url_cache_class');
    if ($mig_debug) {
        fwrite($mig_debug, "Cleared cache \n");
    }
    if (get_option('icl_sitepress_version') && version_compare(get_option('icl_sitepress_version'), '0.9.3', '<')) {
        require_once ICL_PLUGIN_PATH . '/inc/lang-data.inc';
        $wpdb->query("UPDATE {$wpdb->prefix}icl_languages SET english_name='Norwegian Bokmål', code='nb' WHERE english_name='Norwegian'");
        foreach ($langs_names['Norwegian Bokm?l']['tr'] as $k => $display) {
            if (!trim($display)) {
                $display = 'Norwegian Bokm?l';
            }
            $wpdb->insert($wpdb->prefix . 'icl_languages_translations', array('language_code' => 'nb', 'display_language_code' => $lang_codes[$k], 'name' => $display));
        }
        $wpdb->insert($wpdb->prefix . 'icl_languages', array('code' => 'pa', 'english_name' => 'Punjabi'));
        foreach ($langs_names['Punjabi']['tr'] as $k => $display) {
            if (!trim($display)) {
                $display = 'Punjabi';
            }
            $wpdb->insert($wpdb->prefix . 'icl_languages_translations', array('language_code' => 'pa', 'display_language_code' => $lang_codes[$k], 'name' => $display));
        }
        $wpdb->insert($wpdb->prefix . 'icl_languages', array('code' => 'pt-br', 'english_name' => 'Portuguese, Brazil'));
        foreach ($langs_names['Portuguese, Brazil']['tr'] as $k => $display) {
            if (!trim($display)) {
                $display = 'Portuguese, Brazil';
            }
            $wpdb->insert($wpdb->prefix . 'icl_languages_translations', array('language_code' => 'pt-br', 'display_language_code' => $lang_codes[$k], 'name' => $display));
        }
        $wpdb->insert($wpdb->prefix . 'icl_languages', array('code' => 'pt-pt', 'english_name' => 'Portuguese, Portugal'));
        foreach ($langs_names['Portuguese, Portugal']['tr'] as $k => $display) {
            if (!trim($display)) {
                $display = 'Portuguese, Portugal';
            }
            $wpdb->insert($wpdb->prefix . 'icl_languages_translations', array('language_code' => 'pt-pt', 'display_language_code' => $lang_codes[$k], 'name' => $display));
        }
    }
    if (get_option('icl_sitepress_version') && version_compare(get_option('icl_sitepress_version'), '0.9.9', '<')) {
        $iclsettings['icl_lso_flags'] = 0;
        $iclsettings['icl_lso_native_lang'] = 1;
        $iclsettings['icl_lso_display_lang'] = 1;
        update_option('icl_sitepress_settings', $iclsettings);
        // flags table
        $table_name = $wpdb->prefix . 'icl_flags';
        if ($wpdb->get_var("SHOW TABLES LIKE '{$table_name}'") != $table_name) {
            $sql = "\r\n                CREATE TABLE `{$table_name}` (\r\n                `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,\r\n                `lang_code` VARCHAR( 10 ) NOT NULL ,\r\n                `flag` VARCHAR( 32 ) NOT NULL ,\r\n                `from_template` TINYINT NOT NULL DEFAULT '0',\r\n                UNIQUE (`lang_code`)\r\n                )      \r\n            ";
            mysql_query($sql);
        }
        $codes = $wpdb->get_col("SELECT code FROM {$wpdb->prefix}icl_languages");
        foreach ($codes as $code) {
            if (!$code) {
                continue;
            }
            if (!file_exists(ICL_PLUGIN_PATH . '/res/flags/' . $code . '.png')) {
                $file = 'nil.png';
            } else {
                $file = $code . '.png';
            }
            $wpdb->insert($wpdb->prefix . 'icl_flags', array('lang_code' => $code, 'flag' => $file));
        }
        //fix norwegian records
        mysql_query("UPDATE {$wpdb->prefix}icl_languages SET code='nb', english_name='Norwegian Bokmål' WHERE english_name LIKE 'Norwegian Bokm%'");
        mysql_query("UPDATE {$wpdb->prefix}icl_languages_translations SET language_code='nb' WHERE language_code=''");
    }
    // version 1.0.1
    if (get_option('icl_sitepress_version') && version_compare(get_option('icl_sitepress_version'), '1.0.1', '<')) {
        $sitepress_settings = get_option('icl_sitepress_settings');
        if ($sitepress_settings['existing_content_language_verified']) {
            include ICL_PLUGIN_PATH . '/modules/icl-translation/db-scheme.php';
        }
    }
    // version 1.0.2
    if (get_option('icl_sitepress_version') && version_compare(get_option('icl_sitepress_version'), '1.0.2', '<')) {
        //fix norwegian records
        $wpdb->query("UPDATE {$wpdb->prefix}icl_languages SET code='nb', english_name='Norwegian Bokmål' WHERE english_name LIKE 'Norwegian Bokm%'");
        $wpdb->query("UPDATE {$wpdb->prefix}icl_languages_translations SET language_code='nb' WHERE language_code=''");
        $wpdb->query("UPDATE {$wpdb->prefix}icl_languages_translations SET display_language_code='nb' WHERE display_language_code=''");
        $wpdb->query("ALTER TABLE {$wpdb->prefix}icl_translations DROP KEY translation");
        // get elements with duplicates
        $res = $wpdb->get_results("SELECT element_id, element_type, COUNT(translation_id) AS c FROM {$wpdb->prefix}icl_translations GROUP BY element_id, element_type HAVING c > 1");
        foreach ($res as $r) {
            $row_count = $r->c - 1;
            $wpdb->query("\r\n                DELETE FROM {$wpdb->prefix}icl_translations \r\n                WHERE \r\n                    element_id={$r->element_id} AND \r\n                    element_type='{$r->element_type}'\r\n                ORDER BY translation_id DESC\r\n                LIMIT {$row_count}\r\n            ");
        }
        $wpdb->query("ALTER TABLE {$wpdb->prefix}icl_translations ADD UNIQUE KEY `el_type_id` (`element_type`, `element_id`)");
        // fix multiple languages per trid
        $res = $wpdb->get_results("SELECT trid, language_code, COUNT(translation_id) AS c FROM {$wpdb->prefix}icl_translations GROUP BY trid, language_code HAVING c > 1");
        foreach ($res as $r) {
            $row_count = $r->c - 1;
            $wpdb->query("\r\n                DELETE FROM {$wpdb->prefix}icl_translations \r\n                WHERE \r\n                    trid={$r->trid} AND \r\n                    language_code='{$r->language_code}'\r\n                ORDER BY translation_id DESC\r\n                LIMIT {$row_count}\r\n            ");
        }
        $wpdb->query("ALTER TABLE {$wpdb->prefix}icl_translations ADD UNIQUE KEY `trid_lang` (`trid`, `language_code`)");
        $res = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}icl_translations WHERE language_code='' OR language_code IS NULL");
        $sp_default_lcode = $sitepress_settings['default_language'];
        foreach ($res as $r) {
            if (!$sp_default_lcode || $wpdb->get_var("SELECT translation_id FROM {$wpdb->prefix}icl_translations WHERE trid={$r->trid} AND language_code='{$sp_default_lcode}'")) {
                $wpdb->query("DELETE FROM {$wpdb->prefix}icl_translations WHERE translation_id={$r->translation_id}");
            } else {
                $wpdb->update($wpdb->prefix . 'icl_translations', array('language_code' => $sp_default_lcode), array('translation_id' => $r->translation_id));
            }
        }
        $wpdb->query("ALTER TABLE {$wpdb->prefix}icl_translations  CHANGE `language_code` `language_code` VARCHAR( 7 ) NOT NULL");
    }
    if (get_option('icl_sitepress_version') && version_compare(get_option('icl_sitepress_version'), '1.2.0', '<')) {
        if ($iclsettings['icl_interview_translators'] == 0) {
            $iclsettings['icl_interview_translators'] = 1;
            update_option('icl_sitepress_settings', $iclsettings);
        }
    }
    if (get_option('icl_sitepress_version') && version_compare(get_option('icl_sitepress_version'), '1.3.0.1', '<')) {
        if ($mig_debug) {
            fwrite($mig_debug, "Upgrading to 1.3.0.1 \n");
        }
        $iclsettings['modules']['cms-navigation']['enabled'] = 1;
        $iclsettings['dont_show_help_admin_notice'] = 1;
        $iclsettings['setup_complete'] = 1;
        $iclsettings['setup_wizard_step'] = 0;
        mysql_query("ALTER TABLE `{$wpdb->prefix}icl_translations` CHANGE `element_type` `element_type` VARCHAR( 32 ) NOT NULL DEFAULT 'post'");
        if (!$iclsettings['admin_default_language']) {
            $iclsettings['admin_default_language'] = $iclsettings['default_language'];
        }
        update_option('icl_sitepress_settings', $iclsettings);
        $maxtrid = 1 + $wpdb->get_var("SELECT MAX(trid) FROM {$wpdb->prefix}icl_translations");
        mysql_query("\r\n            INSERT INTO {$wpdb->prefix}icl_translations(element_type, element_id, trid, language_code, source_language_code)\r\n            SELECT 'comment', comment_ID, {$maxtrid}+comment_ID, t.language_code, NULL \r\n                FROM {$wpdb->comments} c JOIN {$wpdb->prefix}icl_translations t ON c.comment_post_id = t.element_id AND t.element_type='post'\r\n            ");
        if ($mig_debug) {
            fwrite($mig_debug, "Upgraded to 1.3.0.1 \n");
        }
    }
    if (get_option('icl_sitepress_version') && version_compare(get_option('icl_sitepress_version'), '1.3.0.2', '<')) {
        if ($mig_debug) {
            fwrite($mig_debug, "Upgrading to 1.3.0.2 \n");
        }
        $wpdb->update($wpdb->prefix . 'icl_translations', array('language_code' => $iclsettings['admin_default_language']), array('language_code' => '', 'element_type' => 'comment', 'source_language_code' => ''));
        if ($mig_debug) {
            fwrite($mig_debug, "Upgraded to 1.3.0.2 \n");
        }
    }
    if (get_option('icl_sitepress_version') && version_compare(get_option('icl_sitepress_version'), '1.3.1', '<')) {
        if ($mig_debug) {
            fwrite($mig_debug, "Upgrading to 1.3.1 \n");
        }
        $iclsettings = get_option('icl_sitepress_settings');
        if ($iclsettings['site_id'] && $iclsettings['access_key']) {
            $iclsettings['content_translation_setup_complete'] = 1;
            update_option('icl_sitepress_settings', $iclsettings);
        }
        if ($mig_debug) {
            fwrite($mig_debug, "Upgraded to 1.3.1 \n");
        }
    }
    if (get_option('icl_sitepress_version') && version_compare(get_option('icl_sitepress_version'), '1.3.2', '<')) {
        if ($mig_debug) {
            fwrite($mig_debug, "Upgrading to 1.3.2 \n");
        }
        $comment_translations = array();
        $res = mysql_query("\r\n            SELECT element_id, language_code, trid\r\n                FROM {$wpdb->prefix}icl_translations WHERE element_type='comment'\r\n            ");
        while ($row = mysql_fetch_assoc($res)) {
            $comment_translations[$row['element_id']] = $row;
        }
        $res = mysql_query("\r\n            SELECT c.comment_ID, t.language_code AS post_language\r\n                FROM {$wpdb->comments} c \r\n                    JOIN {$wpdb->prefix}icl_translations t ON  c.comment_post_ID = t.element_id AND t.element_type='post'                    \r\n            ");
        while ($row = mysql_fetch_object($res)) {
            if ($row->post_language != $comment_translations[$row->comment_ID]['language_code']) {
                //check whether we have a comment in this comment's trid that's in the post language
                if (!$wpdb->get_var("\r\n                    SELECT translation_id \r\n                    FROM {$wpdb->prefix}icl_translations \r\n                    WHERE trid={$comment_translations[$row->comment_ID]['trid']} AND element_id<>{$row->comment_ID}\r\n                    ")) {
                    $wpdb->update($wpdb->prefix . 'icl_translations', array('language_code' => $row->post_language), array('element_id' => $row->comment_ID, 'element_type' => 'comment'));
                }
            }
        }
        if ($mig_debug) {
            fwrite($mig_debug, "Upgraded to 1.3.2 \n");
        }
    }
    if (get_option('icl_sitepress_version') && version_compare(get_option('icl_sitepress_version'), '1.3.3', '<')) {
        if ($mig_debug) {
            fwrite($mig_debug, "Upgrading to 1.3.3 \n");
        }
        $iclsettings['modules']['cms-navigation']['cache'] = 1;
        update_option('icl_sitepress_settings', $iclsettings);
        $wpdb->update($wpdb->prefix . 'icl_languages_translations', array('name' => 'Čeština'), array('language_code' => 'cs', 'display_language_code' => 'cs'));
        if ($mig_debug) {
            fwrite($mig_debug, "Upgraded to 1.3.3 \n");
        }
    }
    if (get_option('icl_sitepress_version') && version_compare(get_option('icl_sitepress_version'), '1.3.4', '<')) {
        if ($mig_debug) {
            fwrite($mig_debug, "Upgrading to 1.3.4 \n");
        }
        $iclsettings = get_option('icl_sitepress_settings');
        $iclsettings['modules']['cms-navigation']['cat_menu_contents'] = 'categories';
        update_option('icl_sitepress_settings', $iclsettings);
        if ($mig_debug) {
            fwrite($mig_debug, "Upgraded to 1.3.4 \n");
        }
    }
    if (get_option('icl_sitepress_version') && version_compare(get_option('icl_sitepress_version'), '1.3.5', '<')) {
        if ($iclsettings['existing_content_language_verified']) {
            include ICL_PLUGIN_PATH . '/modules/icl-translation/db-scheme.php';
        }
        if (!$iclsettings['setup_complete'] && 1 < $wpdb->get_var("SELECT COUNT(id) FROM {$wpdb->prefix}icl_languages WHERE active=1")) {
            $iclsettings['setup_complete'] = 1;
            $iclsettings['setup_wizard_step'] = 0;
            update_option('icl_sitepress_settings', $iclsettings);
        }
    }
    if (get_option('icl_sitepress_version') && version_compare(get_option('icl_sitepress_version'), '1.4.0.1', '<')) {
        if ($mig_debug) {
            fwrite($mig_debug, "Upgrading to 1.4.0.1 \n");
        }
        include ICL_PLUGIN_PATH . '/inc/lang-data.inc';
        $cols = $wpdb->get_col("SHOW COLUMNS FROM {$wpdb->prefix}icl_languages");
        if (!in_array('default_locate', $cols)) {
            mysql_query("ALTER TABLE {$wpdb->prefix}icl_languages ADD COLUMN default_locale VARCHAR(8)");
        }
        foreach ($lang_locales as $code => $default_locale) {
            $wpdb->update($wpdb->prefix . 'icl_languages', array('default_locale' => $default_locale), array('code' => $code));
        }
        $res = $wpdb->get_results("SHOW INDEX FROM {$wpdb->prefix}icl_translations");
        foreach ($res as $row) {
            if ($row->Column_name == 'element_type' && $row->Sub_part == 1) {
                mysql_query("ALTER TABLE {$wpdb->prefix}icl_translations DROP KEY `el_type_id`");
                mysql_query("ALTER TABLE {$wpdb->prefix}icl_translations ADD UNIQUE KEY `el_type_id` (`element_type`, `element_id`)");
                $comment_translations = array();
                $res = mysql_query("\r\n                    SELECT element_id, language_code, trid\r\n                        FROM {$wpdb->prefix}icl_translations WHERE element_type='comment'\r\n                    ");
                while ($row = mysql_fetch_assoc($res)) {
                    $comment_translations[$row['element_id']] = $row;
                }
                $res = mysql_query("\r\n                    SELECT c.comment_ID, t.language_code AS post_language\r\n                        FROM {$wpdb->comments} c \r\n                            JOIN {$wpdb->prefix}icl_translations t ON  c.comment_post_ID = t.element_id AND t.element_type='post'                    \r\n                    ");
                while ($row = mysql_fetch_object($res)) {
                    if ($row->post_language != $comment_translations[$row->comment_ID]['language_code']) {
                        //check whether we have a comment in this comment's trid that's in the post language
                        if (!$wpdb->get_var("\r\n                            SELECT translation_id \r\n                            FROM {$wpdb->prefix}icl_translations \r\n                            WHERE trid={$comment_translations[$row->comment_ID]['trid']} AND element_id<>{$row->comment_ID}\r\n                            ")) {
                            $wpdb->update($wpdb->prefix . 'icl_translations', array('language_code' => $row->post_language), array('element_id' => $row->comment_ID, 'element_type' => 'comment'));
                        }
                    }
                    if (!isset($comment_translations[$row->comment_ID]['language_code'])) {
                        $nexttrid = 1 + $wpdb->get_var("SELECT MAX(trid) FROM {$wpdb->prefix}icl_translations");
                        $wpdb->insert($wpdb->prefix . 'icl_translations', array('element_type' => 'comment', 'element_id' => $row->comment_ID, 'trid' => $nexttrid, 'language_code' => $iclsettings['default_language']));
                    }
                }
                break;
            }
        }
        if ($mig_debug) {
            fwrite($mig_debug, "Upgraded to 1.4.0.1 \n");
        }
    }
    if (get_option('icl_sitepress_version') && version_compare(get_option('icl_sitepress_version'), '1.5.0', '<')) {
        if ($mig_debug) {
            fwrite($mig_debug, "Upgrading to 1.5.0 \n");
        }
        if (!isset($iclsettings['icl_lang_sel_config'])) {
            $iclsettings['icl_lang_sel_config'] = array('font-current-normal' => ICL_LANG_SEL_BLUE_FONT_CURRENT_NORMAL, 'font-current-hover' => ICL_LANG_SEL_BLUE_FONT_CURRENT_HOVER, 'background-current-normal' => ICL_LANG_SEL_BLUE_BACKGROUND_CURRENT_NORMAL, 'background-current-hover' => ICL_LANG_SEL_BLUE_BACKGROUND_CURRENT_HOVER, 'font-other-normal' => ICL_LANG_SEL_BLUE_FONT_OTHER_NORMAL, 'font-other-hover' => ICL_LANG_SEL_BLUE_FONT_OTHER_HOVER, 'background-other-normal' => ICL_LANG_SEL_BLUE_BACKGROUND_OTHER_NORMAL, 'background-other-hover' => ICL_LANG_SEL_BLUE_BACKGROUND_OTHER_HOVER, 'border' => ICL_LANG_SEL_BLUE_BORDER);
        }
        $iclsettings['upgrade_flags']['1.5'] = true;
        update_option('icl_sitepress_settings', $iclsettings);
        mysql_query("DELETE FROM {$wpdb->prefix}icl_translations WHERE element_type='comment' AND element_id = 0");
        if ($mig_debug) {
            fwrite($mig_debug, "Upgraded to 1.5.0 \n");
        }
    }
    if (get_option('icl_sitepress_version') && version_compare(get_option('icl_sitepress_version'), '1.6.0', '<')) {
        if ($mig_debug) {
            fwrite($mig_debug, "Upgrading to 1.6.0 \n");
        }
        // force icl_string_positions table creation
        $table_name = $wpdb->prefix . 'icl_string_positions';
        if ($wpdb->get_var("SHOW TABLES LIKE '{$table_name}'") != $table_name) {
            icl_sitepress_activate();
        }
        $iclsettings['st']['track_strings'] = 1;
        $iclsettings['st']['hl_color'] = '#FFFF00';
        update_option('icl_sitepress_settings', $iclsettings);
        if ($mig_debug) {
            fwrite($mig_debug, "Upgraded to 1.6.0 \n");
        }
    }
    if (get_option('icl_sitepress_version') && version_compare(get_option('icl_sitepress_version'), '1.7.0', '<')) {
        if ($mig_debug) {
            fwrite($mig_debug, "Upgrading to 1.7.0 \n");
        }
        $iclsettings['sync_ping_status'] = 1;
        $iclsettings['sync_comment_status'] = 1;
        $iclsettings['sync_sticky_flag'] = 1;
        $iclsettings['sync_page_template'] = 1;
        $iclsettings['auto_adjust_ids'] = 0;
        update_option('icl_sitepress_settings', $iclsettings);
        // get tags with missing language_code value in icl_translations
        $tags = $wpdb->get_col("SELECT element_id FROM {$wpdb->prefix}icl_translations WHERE language_code=''");
        if (!empty($tags)) {
            $res = $wpdb->get_results("\r\n                SELECT r.object_id, r.term_taxonomy_id, t.language_code \r\n                FROM {$wpdb->term_relationships} r \r\n                    JOIN {$wpdb->posts} p ON r.object_id = p.ID\r\n                    JOIN {$wpdb->prefix}icl_translations t ON p.ID = t.element_id AND t.element_type='post'\r\n                WHERE term_taxonomy_id IN (" . join(",", $tags) . ")");
            foreach ($res as $row) {
                $wpdb->update($wpdb->prefix . 'icl_translations', array('language_code' => $row->language_code), array('element_id' => $row->term_taxonomy_id, 'element_type' => 'tag'));
            }
        }
        // set the rest to default language
        $wpdb->update($wpdb->prefix . 'icl_translations', array('language_code' => $sitepress_settings['default_language']), array('element_type' => 'tag', 'language_code' => ''));
        if ($mig_debug) {
            fwrite($mig_debug, "Upgraded to 1.7.0 \n");
        }
    }
    if (get_option('icl_sitepress_version') && version_compare(get_option('icl_sitepress_version'), '1.7.2', '<')) {
        if ($mig_debug) {
            fwrite($mig_debug, "Upgrading to 1.7.2 \n");
        }
        $wpdb->update($wpdb->prefix . 'icl_flags', array('flag' => 'ku.png'), array('lang_code' => 'ku'));
        $wpdb->update($wpdb->prefix . 'icl_languages_translations', array('name' => 'Magyar'), array('language_code' => 'hu', 'display_language_code' => 'hu'));
        $wpdb->update($wpdb->prefix . 'icl_languages_translations', array('name' => 'Hrvatski'), array('language_code' => 'hr', 'display_language_code' => 'hr'));
        $wpdb->update($wpdb->prefix . 'icl_languages_translations', array('name' => 'فارسی'), array('language_code' => 'fa', 'display_language_code' => 'fa'));
        if ($mig_debug) {
            fwrite($mig_debug, "Upgraded to 1.7.2 \n");
        }
    }
    if (get_option('icl_sitepress_version') && version_compare(get_option('icl_sitepress_version'), '1.7.3', '<')) {
        if ($mig_debug) {
            fwrite($mig_debug, "Upgrading to 1.7.3 \n");
        }
        $wpdb->update($wpdb->prefix . 'icl_languages_translations', array('name' => 'پارسی'), array('language_code' => 'fa', 'display_language_code' => 'fa'));
        if ($mig_debug) {
            fwrite($mig_debug, "Upgraded to 1.7.3 \n");
        }
    }
    if (get_option('icl_sitepress_version') && version_compare(get_option('icl_sitepress_version'), '1.7.7', '<')) {
        if ($mig_debug) {
            fwrite($mig_debug, "Upgrading to 1.7.7 \n");
        }
        if (!isset($iclsettings['promote_wpml'])) {
            $iclsettings['promote_wpml'] = 0;
            update_option('icl_sitepress_settings', $iclsettings);
        }
        if (!isset($iclsettings['auto_adjust_ids'])) {
            $iclsettings['auto_adjust_ids'] = 0;
            update_option('icl_sitepress_settings', $iclsettings);
        }
        mysql_query("UPDATE {$wpdb->prefix}icl_translations SET element_type='tax_post_tag' WHERE element_type='tag'");
        mysql_query("UPDATE {$wpdb->prefix}icl_translations SET element_type='tax_category' WHERE element_type='category'");
        if ($mig_debug) {
            fwrite($mig_debug, "Upgraded to 1.7.7 \n");
        }
    }
    if (get_option('icl_sitepress_version') && version_compare(get_option('icl_sitepress_version'), '1.7.8', '<')) {
        if ($mig_debug) {
            fwrite($mig_debug, "Upgrading to 1.7.8 \n");
        }
        $res = $wpdb->get_results("SELECT ID, post_type FROM {$wpdb->posts}");
        foreach ($res as $row) {
            $post_types[$row->post_type][] = $row->ID;
        }
        foreach ($post_types as $type => $ids) {
            if (!empty($ids)) {
                mysql_query("UPDATE {$wpdb->prefix}icl_translations SET element_type='post_{$type}' WHERE element_type='post' AND element_id IN(" . join(',', $ids) . ")");
            }
        }
        // fix categories & tags in icl_translations
        $res = mysql_query("SELECT term_taxonomy_id, taxonomy FROM {$wpdb->term_taxonomy}");
        while ($row = mysql_fetch_object($res)) {
            $icltr = $wpdb->get_row("SELECT translation_id, element_type FROM {$wpdb->prefix}icl_translations WHERE element_id='{$row->term_taxonomy_id}' AND element_type LIKE 'tax\\_%'");
            if ('tax_' . $row->taxonomy != $icltr->element_type) {
                $wpdb->update($wpdb->prefix . 'icl_translations', array('element_type' => 'tax_' . $row->taxonomy), array('translation_id' => $icltr->translation_id));
            }
        }
        if ($mig_debug) {
            fwrite($mig_debug, "Upgraded to 1.7.8 \n");
        }
    }
    if (get_option('icl_sitepress_version') && version_compare(get_option('icl_sitepress_version'), '1.8.1', '<')) {
        if ($mig_debug) {
            fwrite($mig_debug, "Upgrading to 1.8.1 \n");
        }
        $sitepress->get_icl_translator_status($iclsettings);
        $sitepress->save_settings($iclsettings);
        if ($mig_debug) {
            fwrite($mig_debug, "Upgraded to 1.8.1 \n");
        }
    }
    if (get_option('icl_sitepress_version') && version_compare(get_option('icl_sitepress_version'), '2.0.0', '<')) {
        if ($mig_debug) {
            fwrite($mig_debug, "Upgrading to 2.0.0 \n");
        }
        include_once ICL_PLUGIN_PATH . '/inc/upgrade-functions/upgrade-2.0.0.php';
        if (!$iclsettings['migrated_2_0_0']) {
            define('ICL_MULTI_STEP_UPGRADE', true);
            return;
            // GET OUT AND DO NOT SET THE NEW VERSION
        }
        if ($mig_debug) {
            fwrite($mig_debug, "Upgraded to 2.0.0 \n");
        }
    }
    if (get_option('icl_sitepress_version') && version_compare(get_option('icl_sitepress_version'), '2.0.4', '<')) {
        if ($mig_debug) {
            fwrite($mig_debug, "Upgrading to 2.0.4 \n");
        }
        $sql = "ALTER TABLE {$wpdb->prefix}icl_translation_status ADD COLUMN `_prevstate` longtext";
        mysql_query($sql);
        if ($mig_debug) {
            fwrite($mig_debug, "Upgraded to 2.0.4 \n");
        }
    }
    if (version_compare(get_option('icl_sitepress_version'), ICL_SITEPRESS_VERSION, '<')) {
        if ($mig_debug) {
            fwrite($mig_debug, "Update plugin version in the database \n");
        }
        update_option('icl_sitepress_version', ICL_SITEPRESS_VERSION);
        if ($mig_debug) {
            fwrite($mig_debug, "Updated plugin version in the database \n");
        }
    }
    if (defined('ICL_DEBUG_MODE') && ICL_DEBUG_MODE && $mig_debug) {
        @fclose($mig_debug);
    }
}
 function save_translation()
 {
     global $wpdb, $sitepress, $ICL_Pro_Translation, $iclTranslationManagement, $wpml_post_translations;
     $new_post_id = false;
     $is_incomplete = false;
     $data = $this->data;
     /** @var stdClass $job */
     $job = !empty($data['job_id']) ? $this->get_translation_job($data['job_id'], true) : null;
     $original_post = null;
     $element_type_prefix = null;
     if (is_object($job)) {
         $element_type_prefix = $iclTranslationManagement->get_element_type_prefix_from_job($job);
         $original_post = $iclTranslationManagement->get_post($job->original_doc_id, $element_type_prefix);
     }
     $is_external = apply_filters('wpml_is_external', false, $element_type_prefix);
     $data_to_validate = array('original_post' => $original_post, 'type_prefix' => $element_type_prefix, 'data' => $data, 'is_external' => $is_external);
     $validation_results = $this->get_validation_results($job, $data_to_validate);
     if (!$validation_results['is_valid']) {
         $this->handle_failed_validation($validation_results, $data_to_validate);
         $res = false;
     } else {
         foreach ($data['fields'] as $fieldname => $field) {
             if (substr($fieldname, 0, 6) === 'field-') {
                 $field = apply_filters('wpml_tm_save_translation_cf', $field, $fieldname, $data);
             }
             $this->save_translation_field($field['tid'], $field);
             if (!isset($field['finished']) || !$field['finished']) {
                 $is_incomplete = true;
             }
         }
         $icl_translate_job = $this->tm_records->icl_translate_job_by_job_id($data['job_id']);
         $rid = $icl_translate_job->rid();
         $translation_status = $this->tm_records->icl_translation_status_by_rid($rid);
         $translation_id = $translation_status->translation_id();
         if (($is_incomplete === true || empty($data['complete'])) && empty($data['resign'])) {
             $iclTranslationManagement->update_translation_status(array('translation_id' => $translation_id, 'status' => ICL_TM_IN_PROGRESS));
             $icl_translate_job->update(array('translated' => 0));
         }
         $element_id = $translation_status->element_id();
         delete_post_meta($element_id, '_icl_lang_duplicate_of');
         if (!empty($data['complete']) && !$is_incomplete) {
             $icl_translate_job->update(array('translated' => 1));
             $translation_status->update(array('status' => ICL_TM_COMPLETE, 'needs_update' => 0));
             $job = $this->get_translation_job($data['job_id'], true);
             if ($is_external) {
                 $this->save_external($element_type_prefix, $job);
             } else {
                 if (!is_null($element_id)) {
                     $postarr['ID'] = $_POST['post_ID'] = $element_id;
                 } else {
                     $postarr['post_status'] = !$sitepress->get_setting('translated_document_status') ? 'draft' : $original_post->post_status;
                 }
                 foreach ($job->elements as $field) {
                     switch ($field->field_type) {
                         case 'title':
                             $postarr['post_title'] = $this->decode_field_data($field->field_data_translated, $field->field_format);
                             break;
                         case 'body':
                             $postarr['post_content'] = $this->decode_field_data($field->field_data_translated, $field->field_format);
                             break;
                         case 'excerpt':
                             $postarr['post_excerpt'] = $this->decode_field_data($field->field_data_translated, $field->field_format);
                             break;
                         case 'URL':
                             $postarr['post_name'] = $this->decode_field_data($field->field_data_translated, $field->field_format);
                             break;
                         default:
                             break;
                     }
                 }
                 $postarr['post_author'] = $original_post->post_author;
                 $postarr['post_type'] = $original_post->post_type;
                 if ($sitepress->get_setting('sync_comment_status')) {
                     $postarr['comment_status'] = $original_post->comment_status;
                 }
                 if ($sitepress->get_setting('sync_ping_status')) {
                     $postarr['ping_status'] = $original_post->ping_status;
                 }
                 if ($sitepress->get_setting('sync_page_ordering')) {
                     $postarr['menu_order'] = $original_post->menu_order;
                 }
                 if ($sitepress->get_setting('sync_private_flag') && $original_post->post_status == 'private') {
                     $postarr['post_status'] = 'private';
                 }
                 if ($sitepress->get_setting('sync_password') && $original_post->post_password) {
                     $postarr['post_password'] = $original_post->post_password;
                 }
                 if ($sitepress->get_setting('sync_post_date')) {
                     $postarr['post_date'] = $original_post->post_date;
                 }
                 if ($original_post->post_parent) {
                     $parent_id = $wpml_post_translations->element_id_in($original_post->post_parent, $job->language_code);
                 }
                 if (isset($parent_id) && $sitepress->get_setting('sync_page_parent')) {
                     $_POST['post_parent'] = $postarr['post_parent'] = $parent_id;
                     $_POST['parent_id'] = $postarr['parent_id'] = $parent_id;
                 }
                 $_POST['trid'] = $translation_status->trid();
                 $_POST['lang'] = $job->language_code;
                 $_POST['skip_sitepress_actions'] = true;
                 $postarr = apply_filters('icl_pre_save_pro_translation', $postarr);
                 // it's an update and user do not want to translate urls so do not change the url
                 if (isset($element_id) && $sitepress->get_setting('translated_document_page_url') !== 'translate') {
                     $postarr['post_name'] = $wpdb->get_var($wpdb->prepare("SELECT post_name\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t FROM {$wpdb->posts}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t     WHERE ID=%d\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t     LIMIT 1", $element_id));
                 }
                 if (isset($element_id)) {
                     // it's an update so dont change post date
                     $existing_post = get_post($element_id);
                     $postarr['post_date'] = $existing_post->post_date;
                     $postarr['post_date_gmt'] = $existing_post->post_date_gmt;
                 }
                 $new_post_id = $iclTranslationManagement->icl_insert_post($postarr, $job->language_code);
                 icl_cache_clear($postarr['post_type'] . 's_per_language');
                 // clear post counter per language in cache
                 // set taxonomies for users with limited caps
                 if (!current_user_can('manage-categories') && !empty($postarr['tax_input'])) {
                     foreach ($postarr['tax_input'] as $taxonomy => $terms) {
                         wp_set_post_terms($new_post_id, $terms, $taxonomy, false);
                         // true to append to existing tags | false to replace existing tags
                     }
                 }
                 do_action('icl_pro_translation_saved', $new_post_id, $data['fields'], $job);
                 do_action('wpml_translation_job_saved', $new_post_id, $data['fields'], $job);
                 if ($ICL_Pro_Translation) {
                     /** @var WPML_Pro_Translation $ICL_Pro_Translation */
                     $ICL_Pro_Translation->fix_links_to_translated_content($new_post_id, $job->language_code);
                 }
                 // update body translation with the links fixed
                 $new_post_content = $wpdb->get_var($wpdb->prepare("SELECT post_content FROM {$wpdb->posts} WHERE ID=%d", $new_post_id));
                 foreach ($job->elements as $jel) {
                     if ($jel->field_type === 'body') {
                         $fields_data_translated = $this->encode_field_data($new_post_content, $jel->field_format);
                         $wpdb->update($wpdb->prefix . 'icl_translate', array('field_data_translated' => $fields_data_translated), array('job_id' => $data['job_id'], 'field_type' => 'body'));
                         break;
                     }
                 }
                 // set stickiness
                 //is the original post a sticky post?
                 $sticky_posts = get_option('sticky_posts');
                 $is_original_sticky = $original_post->post_type == 'post' && in_array($original_post->ID, $sticky_posts);
                 if ($is_original_sticky && $sitepress->get_setting('sync_sticky_flag')) {
                     stick_post($new_post_id);
                 } else {
                     if ($original_post->post_type == 'post' && !is_null($element_id)) {
                         unstick_post($new_post_id);
                         //just in case - if this is an update and the original post stckiness has changed since the post was sent to translation
                     }
                 }
                 //sync plugins texts
                 $cf_translation_settings = $this->get_tm_setting(array('custom_fields_translation'));
                 foreach ((array) $cf_translation_settings as $cf => $op) {
                     if (1 === (int) $op && get_post_meta($original_post->ID, $cf)) {
                         update_post_meta($new_post_id, $cf, get_post_meta($original_post->ID, $cf, true));
                     }
                 }
                 // set specific custom fields
                 $copied_custom_fields = array('_top_nav_excluded', '_cms_nav_minihome');
                 foreach ($copied_custom_fields as $ccf) {
                     $val = get_post_meta($original_post->ID, $ccf, true);
                     update_post_meta($new_post_id, $ccf, $val);
                 }
                 // sync _wp_page_template
                 if ($sitepress->get_setting('sync_page_template')) {
                     $_wp_page_template = get_post_meta($original_post->ID, '_wp_page_template', true);
                     if (!empty($_wp_page_template)) {
                         update_post_meta($new_post_id, '_wp_page_template', $_wp_page_template);
                     }
                 }
                 $this->package_helper->save_job_custom_fields($job, $new_post_id, (array) $cf_translation_settings);
                 $link = get_edit_post_link($new_post_id);
                 if ($link == '') {
                     // the current user can't edit so just include permalink
                     $link = get_permalink($new_post_id);
                 }
                 if (is_null($element_id)) {
                     $wpdb->delete($wpdb->prefix . 'icl_translations', array('element_id' => $new_post_id, 'element_type' => 'post_' . $postarr['post_type']));
                     $wpdb->update($wpdb->prefix . 'icl_translations', array('element_id' => $new_post_id), array('translation_id' => $translation_id));
                     $user_message = __('Translation added: ', 'sitepress') . '<a href="' . $link . '">' . $postarr['post_title'] . '</a>.';
                 } else {
                     $user_message = __('Translation updated: ', 'sitepress') . '<a href="' . $link . '">' . $postarr['post_title'] . '</a>.';
                 }
                 $this->add_message(array('type' => 'updated', 'text' => $user_message));
             }
             if ($this->get_tm_setting(array('notification', 'completed')) != ICL_TM_NOTIFICATION_NONE && $data['job_id']) {
                 do_action('wpml_tm_complete_job_notification', $data['job_id'], !is_null($element_id));
             }
             $iclTranslationManagement->set_page_url($new_post_id);
             if (isset($job) && isset($job->language_code) && isset($job->source_language_code)) {
                 $this->save_terms_for_job($data['job_id']);
             }
             // sync post format
             // Must be after save terms otherwise it gets lost.
             if ($sitepress->get_setting('sync_post_format')) {
                 $_wp_post_format = get_post_format($original_post->ID);
                 set_post_format($new_post_id, $_wp_post_format);
             }
             do_action('icl_pro_translation_completed', $new_post_id, $data['fields'], $job);
             do_action('wpml_pro_translation_completed', $new_post_id, $data['fields'], $job);
             $this->translate_link_targets_in_posts->new_content();
             $this->translate_link_targets_in_strings->new_content();
             if (!defined('XMLRPC_REQUEST') && !defined('DOING_AJAX') && !isset($_POST['xliff_upload'])) {
                 $action_type = is_null($element_id) ? 'added' : 'updated';
                 $element_id = is_null($element_id) ? $new_post_id : $element_id;
                 $this->redirect_target = admin_url(sprintf('admin.php?page=%s&%s=%d&element_type=%s', WPML_TM_FOLDER . '/menu/translations-queue.php', $action_type, $element_id, $element_type_prefix));
             }
         } else {
             $this->add_message(array('type' => 'updated', 'text' => __('Translation (incomplete) saved.', 'sitepress')));
         }
         $res = true;
     }
     return $res;
 }
function icl_sitepress_deactivate()
{
    icl_disable_capabilities();
    require_once ICL_PLUGIN_PATH . '/inc/cache.php';
    icl_cache_clear();
}
Example #18
0
 function reset_language_data()
 {
     global $wpdb, $sitepress;
     $active = $wpdb->get_col("SELECT code FROM {$wpdb->prefix}icl_languages WHERE active = 1");
     $wpdb->query("TRUNCATE TABLE `{$wpdb->prefix}icl_languages`");
     SitePress_Setup::fill_languages();
     $wpdb->query("TRUNCATE TABLE `{$wpdb->prefix}icl_languages_translations`");
     SitePress_Setup::fill_languages_translations();
     $wpdb->query("TRUNCATE TABLE `{$wpdb->prefix}icl_flags`");
     SitePress_Setup::fill_flags();
     //restore active
     $wpdb->query("UPDATE {$wpdb->prefix}icl_languages SET active=1 WHERE code IN(" . wpml_prepare_in($active) . ")");
     $wpdb->update($wpdb->prefix . 'icl_flags', array('from_template' => 0), null);
     $codes = $wpdb->get_col("SELECT code FROM {$wpdb->prefix}icl_languages");
     foreach ($codes as $code) {
         if (!$code || $wpdb->get_var($wpdb->prepare("SELECT lang_code FROM {$wpdb->prefix}icl_flags WHERE lang_code = %s", $code))) {
             continue;
         }
         if (!file_exists(ICL_PLUGIN_PATH . '/res/flags/' . $code . '.png')) {
             $file = 'nil.png';
         } else {
             $file = $code . '.png';
         }
         $wpdb->insert($wpdb->prefix . 'icl_flags', array('lang_code' => $code, 'flag' => $file, 'from_template' => 0));
     }
     $last_default_language = $sitepress !== null ? $sitepress->get_default_language() : 'en';
     if (!in_array($last_default_language, $codes)) {
         $last_active_languages = $sitepress->get_active_languages();
         foreach ($last_active_languages as $code => $last_active_language) {
             if (in_array($code, $codes)) {
                 $sitepress->set_default_language($code);
                 break;
             }
         }
     }
     icl_cache_clear();
 }
 function cancel_translation_request($translation_id)
 {
     global $wpdb, $WPML_String_Translation;
     if (is_array($translation_id)) {
         foreach ($translation_id as $id) {
             $this->cancel_translation_request($id);
         }
     } else {
         if ($WPML_String_Translation && wpml_mb_strpos($translation_id, 'string|') === 0) {
             //string translations get handled in wpml-string-translation
             //first remove the "string|" prefix
             $id = substr($translation_id, 7);
             //then send it to the respective function in wpml-string-translation
             $WPML_String_Translation->cancel_local_translation($id);
             return;
         }
         list($rid, $translator_id) = $wpdb->get_row($wpdb->prepare("SELECT rid, translator_id\n                     FROM {$wpdb->prefix}icl_translation_status\n                     WHERE translation_id=%d\n                       AND ( status = %d OR status = %d )", $translation_id, ICL_TM_WAITING_FOR_TRANSLATOR, ICL_TM_IN_PROGRESS), ARRAY_N);
         if (!$rid) {
             return;
         }
         $job_id = $wpdb->get_var($wpdb->prepare("SELECT job_id FROM {$wpdb->prefix}icl_translate_job WHERE rid=%d AND revision IS NULL ", $rid));
         if (isset($this->settings['notification']['resigned']) && $this->settings['notification']['resigned'] == ICL_TM_NOTIFICATION_IMMEDIATELY && !empty($translator_id)) {
             do_action('wpml_tm_remove_job_notification', $translator_id, $job_id);
         }
         $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->prefix}icl_translate_job WHERE job_id=%d", $job_id));
         $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->prefix}icl_translate WHERE job_id=%d", $job_id));
         $max_job_id = $wpdb->get_var($wpdb->prepare("SELECT MAX(job_id) FROM {$wpdb->prefix}icl_translate_job WHERE rid=%d", $rid));
         if ($max_job_id) {
             $wpdb->query($wpdb->prepare("UPDATE {$wpdb->prefix}icl_translate_job SET revision = NULL WHERE job_id=%d", $max_job_id));
             $previous_state = $wpdb->get_var($wpdb->prepare("SELECT _prevstate FROM {$wpdb->prefix}icl_translation_status WHERE translation_id = %d", $translation_id));
             if (!empty($previous_state)) {
                 $previous_state = unserialize($previous_state);
                 $arr_data = array('status' => $previous_state['status'], 'translator_id' => $previous_state['translator_id'], 'needs_update' => $previous_state['needs_update'], 'md5' => $previous_state['md5'], 'translation_service' => $previous_state['translation_service'], 'translation_package' => $previous_state['translation_package'], 'timestamp' => $previous_state['timestamp'], 'links_fixed' => $previous_state['links_fixed']);
                 $data_where = array('translation_id' => $translation_id);
                 $wpdb->update($wpdb->prefix . 'icl_translation_status', $arr_data, $data_where);
             }
         } else {
             $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->prefix}icl_translation_status WHERE translation_id=%d", $translation_id));
         }
         // delete record from icl_translations if trid is null
         $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->prefix}icl_translations WHERE translation_id=%d AND element_id IS NULL", $translation_id));
         icl_cache_clear();
     }
 }
 /**
  * Sets a posts language details, invalidates caches relating to the post and triggers
  * synchronisation actions across translations of the just saved post.
  *
  * @param int    $trid
  * @param array  $post_vars
  * @param string $language_code
  * @param string $source_language
  *
  * @used-by \WPML_Post_Translation::save_post_actions as final step of the WPML Core save_post actions
  */
 protected function after_save_post($trid, $post_vars, $language_code, $source_language)
 {
     $this->maybe_set_elid($trid, $post_vars['post_type'], $language_code, $post_vars['ID'], $source_language);
     $translation_sync = $this->get_sync_helper();
     $original_id = $this->get_original_element($post_vars['ID']);
     $translation_sync->sync_with_translations($original_id ? $original_id : $post_vars['ID'], $post_vars);
     $translation_sync->sync_with_duplicates($post_vars['ID']);
     require_once ICL_PLUGIN_PATH . '/inc/cache.php';
     icl_cache_clear($post_vars['post_type'] . 's_per_language', true);
     wp_defer_term_counting(false);
     if ($post_vars['post_type'] !== 'nav_menu_item') {
         do_action('wpml_tm_save_post', $post_vars['ID'], get_post($post_vars['ID']), false);
     }
 }
 function make_duplicate($master_post_id, $lang)
 {
     static $done = array();
     if (isset($done[$master_post_id][$lang])) {
         return;
     }
     $done[$master_post_id][$lang] = true;
     global $sitepress, $sitepress_settings, $wpdb;
     do_action('icl_before_make_duplicate', $master_post_id, $lang);
     $master_post = get_post($master_post_id);
     $is_duplicated = false;
     $trid = $sitepress->get_element_trid($master_post_id, 'post_' . $master_post->post_type);
     if ($trid) {
         $translations = $sitepress->get_element_translations($trid, 'post_' . $master_post->post_type);
         if (isset($translations[$lang])) {
             $postarr['ID'] = $translations[$lang]->element_id;
             $is_duplicated = get_post_meta($translations[$lang]->element_id, '_icl_lang_duplicate_of', true);
         }
     }
     // covers the case when deleting in bulk from all languages
     // setting post_status to trash before wp_trash_post runs issues an WP error
     $posts_to_delete_or_restore_in_bulk = false;
     if (isset($_GET['action']) && ($_GET['action'] == 'trash' || $_GET['action'] == 'untrash') && isset($_GET['lang']) && $_GET['lang'] == 'all') {
         static $posts_to_delete_or_restore_in_bulk;
         if (is_null($posts_to_delete_or_restore_in_bulk)) {
             $posts_to_delete_or_restore_in_bulk = isset($_GET['post']) && is_array($_GET['post']) ? $_GET['post'] : false;
         }
     }
     $postarr['post_author'] = $master_post->post_author;
     $postarr['post_date'] = $master_post->post_date;
     $postarr['post_date_gmt'] = $master_post->post_date_gmt;
     $postarr['post_content'] = $master_post->post_content;
     $postarr['post_title'] = $master_post->post_title;
     $postarr['post_excerpt'] = $master_post->post_excerpt;
     if (($sitepress_settings['sync_delete'] || $is_duplicated) && (!$posts_to_delete_or_restore_in_bulk || !in_array($postarr['ID'], $posts_to_delete_or_restore_in_bulk))) {
         $postarr['post_status'] = $master_post->post_status;
     }
     $postarr['comment_status'] = $master_post->comment_status;
     $postarr['ping_status'] = $master_post->ping_status;
     $postarr['post_name'] = $master_post->post_name;
     if ($master_post->post_parent) {
         $parent = icl_object_id($master_post->post_parent, $master_post->post_type, false, $lang);
         $postarr['post_parent'] = $parent;
     }
     $postarr['menu_order'] = $master_post->menu_order;
     $postarr['post_type'] = $master_post->post_type;
     $postarr['post_mime_type'] = $master_post->post_mime_type;
     $trid = $sitepress->get_element_trid($master_post->ID, 'post_' . $master_post->post_type);
     $_POST['icl_trid'] = $trid;
     $_POST['icl_post_language'] = $lang;
     $_POST['skip_sitepress_actions'] = true;
     $_POST['post_type'] = $master_post->post_type;
     if (isset($postarr['ID'])) {
         $id = wp_update_post($postarr);
     } else {
         $id = $this->icl_insert_post($postarr, $lang);
     }
     require_once ICL_PLUGIN_PATH . '/inc/cache.php';
     icl_cache_clear($postarr['post_type'] . 's_per_language');
     global $ICL_Pro_Translation;
     $ICL_Pro_Translation->_content_fix_links_to_translated_content($id, $lang);
     if (!is_wp_error($id)) {
         $sitepress->set_element_language_details($id, 'post_' . $master_post->post_type, $trid, $lang);
         $this->save_post_actions($id, get_post($id), ICL_TM_DUPLICATE);
         $this->duplicate_fix_children($master_post_id, $lang);
         // dup comments
         if ($sitepress->get_option('sync_comments_on_duplicates')) {
             $this->duplicate_comments($master_post_id, $lang);
         }
         // make sure post name is copied
         $wpdb->update($wpdb->posts, array('post_name' => $master_post->post_name), array('ID' => $id));
         update_post_meta($id, '_icl_lang_duplicate_of', $master_post->ID);
         if ($sitepress->get_option('sync_post_taxonomies')) {
             $this->duplicate_taxonomies($master_post_id, $lang);
         }
         $this->duplicate_custom_fields($master_post_id, $lang);
         $ret = $id;
         do_action('icl_make_duplicate', $master_post_id, $lang, $postarr, $id);
     } else {
         $ret = false;
     }
     return $ret;
 }
 function untrashed_post_actions($post_id)
 {
     if ($this->sync_delete) {
         $translations = $this->post_translation->get_element_translations($post_id, false, true);
         foreach ($translations as $t_id) {
             $this->post_translation->untrash_translation($t_id);
         }
     }
     $post_type = get_post_type($post_id);
     require_once ICL_PLUGIN_PATH . '/inc/cache.php';
     icl_cache_clear($post_type . 's_per_language', true);
 }
Example #23
0
function icl_sitepress_deactivate()
{
    wp_clear_scheduled_hook('update_wpml_config_index');
    require_once ICL_PLUGIN_PATH . '/inc/cache.php';
    icl_cache_clear();
    do_action('wpml_deactivated');
}
 function untrashed_post_actions($post_id)
 {
     global $wpdb;
     $post_type = $wpdb->get_var("SELECT post_type FROM {$wpdb->posts} WHERE ID={$post_id}");
     if ($this->settings['sync_delete']) {
         $trid = $this->get_element_trid($post_id, 'post_' . $post_type);
         $translations = $this->get_element_translations($trid, 'post_' . $post_type);
         foreach ($translations as $t) {
             /* The first line of these checks ensures, that we are actually restoring a trashed post.
              * The second line ensures, that this post is not going to be restored anyways through a bulk
              * action from the UI.
              */
             if (isset($t->element_id) && $t->element_id != $post_id && get_post_status($t->element_id) == 'trash' && !(isset($_REQUEST['post']) && is_array($_REQUEST['post']) && in_array($t->element_id, $_REQUEST['post']))) {
                 remove_action('untrashed_post', array($this, 'untrashed_post_actions'));
                 wp_untrash_post($t->element_id);
                 add_action('untrashed_post', array($this, 'untrashed_post_actions'));
             }
         }
     }
     require_once ICL_PLUGIN_PATH . '/inc/cache.php';
     icl_cache_clear($post_type . 's_per_language', true);
 }
Example #25
0
function icl_plugin_upgrade()
{
    global $wpdb, $sitepress_settings, $sitepress;
    $iclsettings = get_option('icl_sitepress_settings');
    // upgrade actions
    // 1. reset ajx_health_flag
    $iclsettings['ajx_health_checked'] = 0;
    update_option('icl_sitepress_settings', $iclsettings);
    // clear any caches
    require_once ICL_PLUGIN_PATH . '/inc/cache.php';
    icl_cache_clear('locale_cache_class');
    icl_cache_clear('flags_cache_class');
    icl_cache_clear('language_name_cache_class');
    if (get_option('icl_sitepress_version') && version_compare(get_option('icl_sitepress_version'), '1.7.2', '<')) {
        $wpdb->update($wpdb->prefix . 'icl_flags', array('flag' => 'ku.png'), array('lang_code' => 'ku'));
        $wpdb->update($wpdb->prefix . 'icl_languages_translations', array('name' => 'Magyar'), array('language_code' => 'hu', 'display_language_code' => 'hu'));
        $wpdb->update($wpdb->prefix . 'icl_languages_translations', array('name' => 'Hrvatski'), array('language_code' => 'hr', 'display_language_code' => 'hr'));
        $wpdb->update($wpdb->prefix . 'icl_languages_translations', array('name' => 'فارسی'), array('language_code' => 'fa', 'display_language_code' => 'fa'));
    }
    if (get_option('icl_sitepress_version') && version_compare(get_option('icl_sitepress_version'), '1.7.3', '<')) {
        $wpdb->update($wpdb->prefix . 'icl_languages_translations', array('name' => 'پارسی'), array('language_code' => 'fa', 'display_language_code' => 'fa'));
    }
    if (get_option('icl_sitepress_version') && version_compare(get_option('icl_sitepress_version'), '1.7.7', '<')) {
        if (!isset($iclsettings['promote_wpml'])) {
            $iclsettings['promote_wpml'] = 0;
            update_option('icl_sitepress_settings', $iclsettings);
        }
        if (!isset($iclsettings['auto_adjust_ids'])) {
            $iclsettings['auto_adjust_ids'] = 0;
            update_option('icl_sitepress_settings', $iclsettings);
        }
        mysql_query("UPDATE {$wpdb->prefix}icl_translations SET element_type='tax_post_tag' WHERE element_type='tag'");
        mysql_query("UPDATE {$wpdb->prefix}icl_translations SET element_type='tax_category' WHERE element_type='category'");
    }
    if (get_option('icl_sitepress_version') && version_compare(get_option('icl_sitepress_version'), '1.7.8', '<')) {
        $res = $wpdb->get_results("SELECT ID, post_type FROM {$wpdb->posts}");
        foreach ($res as $row) {
            $post_types[$row->post_type][] = $row->ID;
        }
        foreach ($post_types as $type => $ids) {
            if (!empty($ids)) {
                mysql_query("UPDATE {$wpdb->prefix}icl_translations SET element_type='post_{$type}' WHERE element_type='post' AND element_id IN(" . join(',', $ids) . ")");
            }
        }
        // fix categories & tags in icl_translations
        $res = mysql_query("SELECT term_taxonomy_id, taxonomy FROM {$wpdb->term_taxonomy}");
        while ($row = mysql_fetch_object($res)) {
            $icltr = $wpdb->get_row("SELECT translation_id, element_type FROM {$wpdb->prefix}icl_translations WHERE element_id='{$row->term_taxonomy_id}' AND element_type LIKE 'tax\\_%'");
            if ('tax_' . $row->taxonomy != $icltr->element_type) {
                $wpdb->update($wpdb->prefix . 'icl_translations', array('element_type' => 'tax_' . $row->taxonomy), array('translation_id' => $icltr->translation_id));
            }
        }
    }
    if (get_option('icl_sitepress_version') && version_compare(get_option('icl_sitepress_version'), '2.0.0', '<')) {
        include_once ICL_PLUGIN_PATH . '/inc/upgrade-functions/upgrade-2.0.0.php';
        if (empty($iclsettings['migrated_2_0_0'])) {
            define('ICL_MULTI_STEP_UPGRADE', true);
            return;
            // GET OUT AND DO NOT SET THE NEW VERSION
        }
    }
    if (get_option('icl_sitepress_version') && version_compare(get_option('icl_sitepress_version'), '2.0.4', '<')) {
        $sql = "ALTER TABLE {$wpdb->prefix}icl_translation_status ADD COLUMN `_prevstate` longtext";
        mysql_query($sql);
    }
    icl_upgrade_version('2.0.5');
    icl_upgrade_version('2.2.2');
    icl_upgrade_version('2.3.0');
    icl_upgrade_version('2.3.1');
    icl_upgrade_version('2.3.3');
    icl_upgrade_version('2.4.0');
    if (version_compare(get_option('icl_sitepress_version'), ICL_SITEPRESS_VERSION, '<')) {
        update_option('icl_sitepress_version', ICL_SITEPRESS_VERSION);
    }
}
Example #26
0
 * @return callable
 */
function get_term_taxonomy_id_from_term_object($term_object)
{
    return $term_object->term_taxonomy_id;
}
$action = filter_input(INPUT_GET, 'debug_action', FILTER_SANITIZE_STRING);
$nonce = filter_input(INPUT_GET, 'nonce', FILTER_SANITIZE_STRING);
if (isset($action) && wp_verify_nonce($nonce, $action)) {
    ob_end_clean();
    global $wpdb;
    switch ($action) {
        case 'fix_languages':
            SitePress_Setup::fill_languages();
            SitePress_Setup::fill_languages_translations();
            icl_cache_clear();
            exit;
        case 'icl_fix_collation':
            repair_el_type_collate();
            exit;
        case 'reset_pro_translation_configuration':
            $sitepress_settings = get_option('icl_sitepress_settings');
            $sitepress_settings['content_translation_languages_setup'] = false;
            $sitepress_settings['content_translation_setup_complete'] = false;
            unset($sitepress_settings['content_translation_setup_wizard_step']);
            unset($sitepress_settings['site_id']);
            unset($sitepress_settings['access_key']);
            unset($sitepress_settings['translator_choice']);
            unset($sitepress_settings['icl_lang_status']);
            unset($sitepress_settings['icl_balance']);
            unset($sitepress_settings['icl_support_ticket_id']);
 function make_duplicate($master_post_id, $lang)
 {
     global $wpml_post_translations, $wpml_language_resolution;
     static $duplicated_post_ids;
     if (!isset($duplicated_post_ids)) {
         $duplicated_post_ids = array();
     }
     //It is already done? (avoid infinite recursions)
     if (!$wpml_language_resolution->is_language_active($lang) || in_array($master_post_id . '|' . $lang, $duplicated_post_ids)) {
         return true;
     }
     $duplicated_post_ids[] = $master_post_id . '|' . $lang;
     global $sitepress, $sitepress_settings;
     do_action('icl_before_make_duplicate', $master_post_id, $lang);
     $master_post = get_post($master_post_id);
     $is_duplicated = false;
     $translations = $wpml_post_translations->get_element_translations($master_post_id, false, false);
     if (isset($translations[$lang])) {
         $post_array['ID'] = $translations[$lang];
         if (WPML_WordPress_Actions::is_bulk_trash($post_array['ID']) || WPML_WordPress_Actions::is_bulk_untrash($post_array['ID'])) {
             return true;
         }
         $is_duplicated = get_post_meta($translations[$lang], '_icl_lang_duplicate_of', true);
     }
     $post_array['post_author'] = $master_post->post_author;
     $post_array['post_date'] = $master_post->post_date;
     $post_array['post_date_gmt'] = $master_post->post_date_gmt;
     $post_array['post_content'] = addslashes_gpc(apply_filters('icl_duplicate_generic_string', $master_post->post_content, $lang, array('context' => 'post', 'attribute' => 'content', 'key' => $master_post->ID)));
     $post_array['post_title'] = addslashes_gpc(apply_filters('icl_duplicate_generic_string', $master_post->post_title, $lang, array('context' => 'post', 'attribute' => 'title', 'key' => $master_post->ID)));
     $post_array['post_excerpt'] = addslashes_gpc(apply_filters('icl_duplicate_generic_string', $master_post->post_excerpt, $lang, array('context' => 'post', 'attribute' => 'excerpt', 'key' => $master_post->ID)));
     if (isset($sitepress_settings['sync_post_status']) && $sitepress_settings['sync_post_status']) {
         $sync_post_status = true;
     } else {
         $sync_post_status = !isset($post_array['ID']) || $sitepress_settings['sync_delete'] && $master_post->post_status == 'trash' || $is_duplicated;
     }
     if ($sync_post_status || isset($post_array['ID']) && get_post_status($post_array['ID']) === 'auto-draft') {
         $post_array['post_status'] = $master_post->post_status;
     }
     $post_array['comment_status'] = $master_post->comment_status;
     $post_array['ping_status'] = $master_post->ping_status;
     $post_array['post_name'] = $master_post->post_name;
     if ($master_post->post_parent) {
         $parent = icl_object_id($master_post->post_parent, $master_post->post_type, false, $lang);
         $post_array['post_parent'] = $parent;
     }
     $post_array['menu_order'] = $master_post->menu_order;
     $post_array['post_type'] = $master_post->post_type;
     $post_array['post_mime_type'] = $master_post->post_mime_type;
     $trid = $sitepress->get_element_trid($master_post->ID, 'post_' . $master_post->post_type);
     $id = $this->save_duplicate($post_array, $lang);
     require_once ICL_PLUGIN_PATH . '/inc/cache.php';
     icl_cache_clear();
     global $ICL_Pro_Translation;
     /** @var WPML_Pro_Translation $ICL_Pro_Translation */
     if ($ICL_Pro_Translation) {
         $ICL_Pro_Translation->_content_fix_links_to_translated_content($id, $lang);
     }
     if (!is_wp_error($id)) {
         $ret = $this->run_wpml_actions($master_post, $trid, $lang, $id, $post_array);
     } else {
         $ret = false;
     }
     return $ret;
 }