/**
 * @since 3.3.2
 */
function qtranxf_load_config_files($json_files)
{
    $content_dir = null;
    $qtransx_dir = null;
    foreach ($json_files as $k => $fnm) {
        //$fnm = trim($v,'/\\');
        if (file_exists($fnm)) {
            continue;
        }
        $ffnm = null;
        if ($fnm[0] == '.' && $fnm[1] == '/') {
            if (!$qtransx_dir) {
                $qtransx_dir = QTRANSLATE_DIR;
            }
            $ffnm = $qtransx_dir . substr($fnm, 1);
        }
        if (!file_exists($ffnm)) {
            if (!$content_dir) {
                $content_dir = trailingslashit(WP_CONTENT_DIR);
            }
            $ffnm = $content_dir . $fnm;
        }
        if (file_exists($ffnm)) {
            $json_files[$k] = $ffnm;
        } else {
            qtranxf_error_log(sprintf(__('Could not find file "%s" listed in option "%s".', 'qtranslate'), '<strong>' . $fnm . '</strong>', '<a href="' . admin_url('options-general.php?page=qtranslate-x#integration') . '">' . __('Configuration Files', 'qtranslate') . '</a>') . ' ' . __('Please, either put file in place or update the option.', 'qtranslate') . ' ' . sprintf(__('Once the problem is fixed, re-save the configuration by pressing button "%s" on plugin %ssettings page%s.', 'qtranslate'), __('Save Changes', 'qtranslate'), '<a href="' . admin_url('options-general.php?page=qtranslate-x#integration') . '">', '</a>'));
            unset($json_files[$k]);
        }
    }
    $cfg_all = array();
    foreach ($json_files as $fnm) {
        $cfg_json = file_get_contents($fnm);
        //$cfg_json=php_strip_whitespace($fnm);
        if ($cfg_json) {
            $cfg = json_decode($cfg_json, true);
            if (!empty($cfg) && is_array($cfg)) {
                $cfg_all = qtranxf_merge_config($cfg_all, $cfg);
            } else {
                qtranxf_error_log(sprintf(__('Could not parse %s file "%s" listed in option "%s".', 'qtranslate'), 'JSON', '<strong>' . $fnm . '</strong>', '<a href="' . admin_url('options-general.php?page=qtranslate-x#integration') . '">' . __('Configuration Files', 'qtranslate') . '</a>') . ' ' . __('Please, correct the syntax error in the file.', 'qtranslate') . ' ' . sprintf(__('Once the problem is fixed, re-save the configuration by pressing button "%s" on plugin %ssettings page%s.', 'qtranslate'), __('Save Changes', 'qtranslate'), '<a href="' . admin_url('options-general.php?page=qtranslate-x#integration') . '">', '</a>'));
            }
        } else {
            qtranxf_error_log(sprintf(__('Could not load file "%s" listed in option "%s".', 'qtranslate'), '<strong>' . $fnm . '</strong>', '<a href="' . admin_url('options-general.php?page=qtranslate-x#integration') . '">' . __('Configuration Files', 'qtranslate') . '</a>') . ' ' . __('Please, make sure the file is accessible and readable.', 'qtranslate') . ' ' . sprintf(__('Once the problem is fixed, re-save the configuration by pressing button "%s" on plugin %ssettings page%s.', 'qtranslate'), __('Save Changes', 'qtranslate'), '<a href="' . admin_url('options-general.php?page=qtranslate-x#integration') . '">', '</a>'));
        }
    }
    if (!isset($cfg_all['admin-config'])) {
        $cfg_all['admin-config'] = array();
    }
    if (!isset($cfg_all['front-config'])) {
        $cfg_all['front-config'] = array();
    }
    return $cfg_all;
}
function qtranxf_migrate_import_qtranslate_slug()
{
    global $q_config, $wpdb;
    //qtranxf_dbg_log('qtranxf_migrate_import_qtranslate_slug: REQUEST_TIME_FLOAT: ', $_SERVER['REQUEST_TIME_FLOAT']);
    $nm = '<a href="https://wordpress.org/plugins/qtranslate-slug/" target="_blank"><span style="color:blue"><strong>QTranslate Slug</strong></span></a>';
    $wpdb->show_errors();
    @set_time_limit(0);
    $sql = 'SELECT post_name, meta_key, meta_value FROM ' . $wpdb->postmeta . ' as m INNER JOIN ' . $wpdb->posts . ' as p ON p.ID = m.post_id WHERE m.meta_key LIKE "_qts_slug___" AND m.meta_value IS NOT NULL';
    //$sql .= ' AND NOT EXISTS (SELECT * FROM '.$wpdb->prefix.'posts_i18n WHERE ID = post_id AND lang = MID(meta_key,11))';
    $sql .= ' AND NOT EXISTS (SELECT * FROM ' . $wpdb->prefix . 'i18n_slugs WHERE name = p.post_name AND lang = MID(m.meta_key,11))';
    $result = $wpdb->get_results($sql);
    //qtranxf_dbg_log('qtranxf_migrate_import_qtranslate_slug: $result: ', $result);
    //qtranxf_dbg_log('qtranxf_migrate_import_qtranslate_slug: count($result): ', count($result));
    if (is_array($result)) {
        $default_language = $q_config['default_language'];
        //$sql = 'INSERT INTO '.$wpdb->prefix.'posts_i18n (ID, lang, slug) VALUES (%s, %s, %s)';
        $sql = 'INSERT INTO ' . $wpdb->prefix . 'i18n_slugs (slug, lang, name) VALUES (%s, %s, %s)';
        foreach ($result as $row) {
            $slug = $row->meta_value;
            $lang = substr($row->meta_key, -2);
            $name = $row->post_name;
            if ($lang == $default_language) {
                if ($slug != $name) {
                    //qtranxf_dbg_log('qtranxf_migrate_import_qtranslate_slug: $slug('.$slug.') != $name('.$name.')');
                    //todo
                }
            } else {
                $slug = qtranxf_slug_unique($row->meta_value, $lang, $name);
                if ($slug != $row->meta_value) {
                    //todo report
                }
                //qtranxf_dbg_log('qtranxf_migrate_import_qtranslate_slug: $lang='.$lang.'; row: ', $row);
                //$query = $wpdb->prepare($sql, $row->post_id, $lang, $row->meta_value);
                $query = $wpdb->prepare($sql, $slug, $lang, $row->post_name);
                $wpdb->query($query);
            }
        }
        qtranxf_add_message(sprintf(__('Applicable options and slug data from plugin %s have been imported.', 'qtranslate'), $nm) . ' ' . sprintf(__('It might be a good idea to review %smigration instructions%s, if you have not yet done so.', 'qtranslate'), '<a href="https://qtranslatexteam.wordpress.com/migration/" target="_blank">', '</a>'));
    } else {
        qtranxf_error_log(sprintf(__('Failed to import data from plugin %s.', 'qtranslate'), $nm) . ' ' . sprintf(__('It might be a good idea to review %smigration instructions%s, if you have not yet done so.', 'qtranslate'), '<a href="https://qtranslatexteam.wordpress.com/migration/" target="_blank">', '</a>'));
    }
}
function qtranxf_get_admin_page_config_post_type($post_type)
{
    global $q_config, $pagenow;
    static $page_config;
    //cache
    if (!is_null($page_config)) {
        //qtranxf_dbg_log('qtranxf_get_admin_page_config_post_type: cached: '.$pagenow.'; post_type: ', $post_type);
        return $page_config;
    }
    if ($q_config['editor_mode'] == QTX_EDITOR_MODE_RAW) {
        //qtranxf_dbg_log('qtranxf_get_admin_page_config_post_type: QTX_EDITOR_MODE_RAW: '.$pagenow.'; post_type: ', $post_type);
        $page_config = array();
        return $page_config;
    }
    if (!empty($q_config['post_type_excluded'])) {
        switch ($pagenow) {
            case 'post.php':
            case 'post-new.php':
                if (in_array($post_type, $q_config['post_type_excluded'])) {
                    //qtranxf_dbg_log('qtranxf_get_admin_page_config_post_type: post_type_excluded: pagenow: '.$pagenow.'; post_type: ', $post_type);
                    $page_config = array();
                    return $page_config;
                }
            default:
                break;
        }
    }
    //qtranxf_dbg_log('qtranxf_get_admin_page_config_post_type: pagenow: '.$pagenow.'; post_type: ', $post_type);
    $page_configs = qtranxf_get_admin_page_config();
    //$page_configs = apply_filters('i18n_admin_config_post_type', $page_configs, $post_type);
    //qtranxf_dbg_log('qtranxf_get_admin_page_config_post_type: $page_configs: ', $page_configs);
    $page_config = isset($page_configs['']) ? $page_configs[''] : array();
    if ($post_type) {
        foreach ($page_configs as $k => $cfg) {
            if (empty($k)) {
                continue;
            }
            if (isset($cfg['post_type'])) {
                $cfg_post_type = $cfg['post_type'];
                unset($cfg['post_type']);
            } else {
                $cfg_post_type = $k;
            }
            $matched = qtranxf_match_post_type($cfg_post_type, $post_type);
            //qtranxf_dbg_log('qtranxf_get_admin_page_config_post_type: $cfg: ', $cfg);
            //qtranxf_dbg_log('qtranxf_get_admin_page_config_post_type: $matched: ', $matched);
            if ($matched === false) {
                continue;
            }
            if (is_null($matched)) {
                $page_config = array();
                break;
            }
            $page_config = qtranxf_merge_config($page_config, $cfg);
        }
    }
    //qtranxf_dbg_log('qtranxf_get_admin_page_config_post_type: $page_config: ', $page_config);
    unset($page_config['filters']);
    if (!empty($page_config)) {
        //clean up empty items
        if (!empty($page_config['forms'])) {
            foreach ($page_config['forms'] as $form_id => &$frm) {
                if (!isset($frm['fields'])) {
                    continue;
                }
                foreach ($frm['fields'] as $k => $f) {
                    if (isset($f['encode']) && $f['encode'] == 'none') {
                        //unset($page_config['forms'][$form_id]['fields'][$k]);
                        unset($frm['fields'][$k]);
                    }
                    if ($post_type && !empty($f['post-type-excluded']) && preg_match('/' . $f['post-type-excluded'] . '/', $post_type)) {
                        unset($frm['fields'][$k]);
                    }
                }
                foreach ($frm as $k => $token) {
                    if (empty($token)) {
                        unset($frm[$k]);
                    }
                }
                if (empty($frm)) {
                    unset($page_config['forms'][$form_id]);
                }
            }
        }
        foreach ($page_config as $k => $cfg) {
            if (empty($cfg)) {
                unset($page_config[$k]);
            }
        }
    }
    if (!empty($page_config)) {
        $page_config['js'] = array();
        if (isset($page_config['js-conf'])) {
            foreach ($page_config['js-conf'] as $k => $js) {
                if (!isset($js['handle'])) {
                    $js['handle'] = $k;
                }
                $page_config['js'][] = $js;
            }
            unset($page_config['js-conf']);
        }
        $page_config['js'][] = array('handle' => 'qtranslate-admin-common', 'src' => './admin/js/common.min.js');
        if (isset($page_config['js-exec'])) {
            foreach ($page_config['js-exec'] as $k => $js) {
                if (!isset($js['handle'])) {
                    $js['handle'] = $k;
                }
                $page_config['js'][] = $js;
            }
            unset($page_config['js-exec']);
        }
        //make src to be relative to WP_CONTENT_DIR
        //$bnm = 'plugins/'.qtranxf_plugin_dirname();
        $bnm = qtranxf_plugin_dirname_from_wp_content();
        $content_dir = trailingslashit(WP_CONTENT_DIR);
        foreach ($page_config['js'] as $k => $js) {
            if (!isset($js['src'])) {
                continue;
            }
            $src = $js['src'];
            if ($src[0] == '.' && ($src[1] == '/' || $src[1] == DIRECTORY_SEPARATOR)) {
                $page_config['js'][$k]['src'] = $bnm . substr($src, 1);
            } else {
                if (file_exists($content_dir . $src)) {
                    continue;
                }
                //from WP_CONTENT_DIR as expected
                $fp = dirname($bnm) . '/' . $src;
                //from 'plugins' folder
                if (file_exists($content_dir . $fp)) {
                    $page_config['js'][$k]['src'] = $fp;
                    continue;
                }
                $fp = $bnm . '/' . $src;
                //from this plugin folder
                if (file_exists($content_dir . $fp)) {
                    $page_config['js'][$k]['src'] = $fp;
                    continue;
                }
                if (file_exists($src)) {
                    //absolute path was given
                    if (qtranxf_startsWith($src, $content_dir)) {
                        $fp = substr($src, strlen($content_dir));
                        $page_config['js'][$k]['src'] = $fp;
                        continue;
                    }
                }
                unset($page_config['js'][$k]);
                qtranxf_error_log(sprintf(__('Could not find script file "%s" for handle "%s".', 'qtranslate'), $src, $js['handle']));
            }
        }
    }
    /*
     * Customize the $page_config for this admin request.
     * @param (array) $page_config 'admin_config', filtered for the current page.
     * @param (string) $pagenow value of WordPress global variable $pagenow.
     * @param (string) $url_query query part of URL without '?', sanitized version of $_SERVER['QUERY_STRING'].
     * @param (string) $post_type type of post serving on the current page, or null if not applicable.
     */
    //$page_config = apply_filters('i18n_admin_page_config', $page_config, $pagenow, $url_query, $post_type);
    //qtranxf_dbg_log('qtranxf_get_admin_page_config_post_type: $pagenow='.$pagenow.'; $url_query='.$q_config['url_info']['query'].'; $post_type='.$post_type.'; $page_config: ',qtranxf_json_encode($page_config));
    qtranxf_write_config_log($page_config, '', $pagenow, '', $post_type);
    return $page_config;
}
function qtranxf_migrate_import_qtranslate_slug($default_language)
{
    //$q_config is not yet available
    global $wpdb;
    //qtranxf_dbg_log('qtranxf_migrate_import_qtranslate_slug: ');
    $nm = '<a href="https://wordpress.org/plugins/qtranslate-slug/" target="_blank"><span style="color:blue"><strong>QTranslate Slug</strong></span></a>';
    $wpdb->show_errors();
    @set_time_limit(0);
    $qts_options = get_option('qts_options');
    if (!empty($qts_options)) {
        //qtranxf_dbg_log('qtranxf_migrate_import_qtranslate_slug: $qts_options: ', $qts_options);
        if (is_array($qts_options)) {
            foreach ($qts_options as $k => $v) {
            }
        } else {
            qtranxf_error_log(sprintf(__('Failed to import options from plugin %s.', 'qtranslate'), $nm));
        }
    }
    $sql = 'SELECT ID, post_name, post_type, post_parent, meta_key, meta_value FROM ' . $wpdb->postmeta . ' as m INNER JOIN ' . $wpdb->posts . ' as p ON p.ID = m.post_id WHERE p.post_status = "publish" AND p.post_name != "" AND m.meta_key LIKE "_qts_slug___" AND m.meta_value IS NOT NULL';
    $sql .= ' AND NOT EXISTS (SELECT * FROM ' . $wpdb->prefix . 'i18n_slugs WHERE name = p.post_name AND lang = MID(m.meta_key,11))';
    $result = $wpdb->get_results($sql);
    //qtranxf_dbg_log('qtranxf_migrate_import_qtranslate_slug: $result: ', $result);
    //qtranxf_dbg_log('qtranxf_migrate_import_qtranslate_slug: count($result): ', count($result));
    if (!is_array($result)) {
        qtranxf_error_log(sprintf(__('Failed to import data from plugin %s.', 'qtranslate'), $nm) . ' ' . sprintf(__('It might be a good idea to review %smigration instructions%s, if you have not yet done so.', 'qtranslate'), '<a href="https://qtranslatexteam.wordpress.com/migration/" target="_blank">', '</a>'));
        return;
    }
    foreach ($result as $row) {
        $name = $row->post_name;
        if (empty($name)) {
            continue;
        }
        $slug = $row->meta_value;
        if (empty($slug)) {
            continue;
        }
        $lang = substr($row->meta_key, -2);
        if ($lang != $default_language) {
            continue;
        }
        if ($slug == $name) {
            continue;
        }
        //qtranxf_dbg_log('qtranxf_migrate_import_qtranslate_slug: default language $slug('.$slug.') != $name('.$name.')');
        $slug = wp_unique_post_slug($slug, $row->ID, 'publish', $row->post_type, $row->post_parent);
        $wpdb->query($wpdb->prepare('UPDATE ' . $wpdb->posts . ' SET post_name = %s WHERE ID = %d', $slug, $row->ID));
        $row->post_name = $row->meta_value = $slug;
    }
    $cnt = 0;
    $cnt_renamed = 0;
    $lst = '';
    $sql = 'INSERT INTO ' . $wpdb->prefix . 'i18n_slugs (slug, lang, name) VALUES (%s, %s, %s)';
    foreach ($result as $row) {
        $lang = substr($row->meta_key, -2);
        if ($lang == $default_language) {
            continue;
        }
        $name = $row->post_name;
        if (empty($name)) {
            continue;
        }
        $slug = $row->meta_value;
        if (empty($slug)) {
            continue;
        }
        if (!qtranxf_isEnabled($lang)) {
            continue;
        }
        $slug = qtranxf_slug_unique($row->meta_value, $lang, $name);
        if ($slug != $row->meta_value) {
            $lst .= $row->ID . '\\t' . $name . '\\t' . $lang . '\\t' . $row->meta_value . ' => ' . $slug . PHP_EOL;
            ++$cnt_renamed;
        }
        //qtranxf_dbg_log('qtranxf_migrate_import_qtranslate_slug: $lang='.$lang.'; row: ', $row);
        $query = $wpdb->prepare($sql, $slug, $lang, $row->post_name);
        $wpdb->query($query);
        ++$cnt;
    }
    $msg = '';
    if ($cnt != 0) {
        $msg .= sprintf(__('Applicable options and slug data from plugin %s have been imported.', 'qtranslate'), $nm);
    }
    //if(!empty($lst))){
    $upload_dir = wp_upload_dir();
    //qtranxf_dbg_log('qtranxf_migrate_import_qtranslate_slug: upload_dir: ',$upload_dir);
    $fnm = '/qts-qtx-report-of-renamed.log';
    $fn = $upload_dir['basedir'] . $fnm;
    //[01-Nov-2015 02:21:57 UTC]
    error_log(date('[d-M-Y H:i:s T]') . ': Slugs renamed during import:' . PHP_EOL . "Post_ID\tpost_name\tLANG\tQtranslate Slug => qTranslate-X Slug" . PHP_EOL . $lst . PHP_EOL, 3, $fn);
    $url = $upload_dir['baseurl'] . $fnm;
    $msg .= ' ' . sprintf(__('A number of post slugs have had to be renamed in order to provide uniqueness. The report of renamed slugs is saved in the file "%s".', 'qtranslate'), '<a href="' . $url . ' target="_blank">' . $url . '</a>');
    //}
    if (!empty($msg)) {
        $msg .= ' ' . sprintf(__('It might be a good idea to review %smigration instructions%s, if you have not yet done so.', 'qtranslate'), '<a href="https://qtranslatexteam.wordpress.com/migration/" target="_blank">', '</a>');
        qtranxf_add_message($msg);
    }
}