Plugin Directory

Changeset 3813524


Ignore:
Timestamp:
11/20/2026 11:09:26 AM (2 weeks ago)
Author:
evgenyviner
Message:

Version 1.0.6: fix CVE-2024-13637 (capability + nonce checks on all AJAX actions), demo import fixes

Location:
demo-awesome
Files:
10 added
2 deleted
26 edited
1 copied

Legend:

Unmodified
Added
Removed
  • demo-awesome/tags/1.0.6/README.txt

    r3081092 r3813524  
    11=== Demo Awesome ===
    22Contributors: evgenyviner
    3 Tags: theme4press, data importer, one-click demo import, theme demo, demos, importer, theme4press demo
    4 Requires at least: 4.7
    5 Tested up to: 6.5.2
    6 Requires PHP: 7.0
    7 Stable tag: trunk
     3Tags: data importer, one-click demo import, theme demo, demos, importer
     4Requires at least: 5.5
     5Tested up to: 7.1
     6Requires PHP: 7.4
     7Stable tag: 1.0.6
    88License: GPLv2 or later
    99License URI: http://www.gnu.org/licenses/gpl-2.0.html
    … …  
    4040We strongly recommend using these demos for newly created websites, development websites, etc. as the plugin will change or remove much existing content of your website like posts, pages, widgets, theme settings, etc.
    4141
     42== External services ==
     43
     44This plugin connects to the Theme4Press demo server, **demo.theme4press.com**, operated by Theme4Press. The demos are stored there, so the plugin cannot work without it.
     45
     46What is requested and when:
     47
     48* **Opening the demo browser** (Appearance > Demo Awesome): the plugin downloads the list of available demos (`get-list-demos.json`). Your browser loads each demo's screenshot image from the demo server.
     49* **Live preview** of a demo: the demo website on demo.theme4press.com is shown in a frame, so it is loaded by your browser.
     50* **Importing a demo**: the plugin downloads that demo's content, widget and theme-settings files (and slider files for demos that have them), and WordPress downloads the demo's images.
     51
     52No personal data, account data or content from your site is sent. As with any web request, the demo server receives the requesting IP address and browser or server details; image downloads made by WordPress also include your site's address in the standard WordPress user-agent header.
     53
     54Premium demos may require premium plugins. With the evolve Plus theme, these are downloaded by the theme from Theme4Press using the theme's license key; Demo Awesome itself does not send the key. Free required plugins are installed from WordPress.org.
     55
     56Theme4Press terms and conditions: https://theme4press.com/terms-conditions/
     57Theme4Press privacy policy: https://theme4press.com/privacy-policy/
     58
    4259== Screenshots ==
    4360
    … …  
    4966== Changelog ==
    5067
     68= 1.0.6 =
     69* Fixed the demo import doing nothing but showing "requires additional plugins" (a stray duplicate AJAX action introduced by an earlier release)
     70* Removed the over-aggressive request rate limit that blocked legitimate importing/plugin installation
     71* Allowed required-plugin installation for any valid plugin slug (was limited to a small hardcoded list); hardened the activation match against regex injection
     72* Fixed every import failing with "Invalid template name" (demo folders such as "business/1" were rejected)
     73* Fixed 12 of the 20 demos being rejected because their content contains ordinary embed scripts; downloads are now validated by file format and rejected only if they contain PHP code
     74* Security: the demo to import is now looked up by its index in the demo list from the demo server; folder, options and required plugins are no longer taken from the browser request
     75* Fixed a premium demo, or a failed download, removing the site's theme settings, menus and widgets before the import was refused; nothing is removed until the demo content has been downloaded and validated
     76* Fixed the download cache: cached files of some demos (App 1, App 2, Blog 1, Portfolio 1) could never be read back, so any repeat import within an hour failed; a missing or invalid cached copy is now downloaded again
     77* Import errors are now shown in the import window instead of failing silently
     78* Fixed LayerSlider data never being imported (demo list key mismatch) and PHP warnings for demos without slider data
     79
     80= 1.0.5 =
     81* Security: prevented PHP object injection when importing customizer (.dat) data
     82* Security: hardened XML validation against XXE / entity-expansion attacks
     83* Security: blocked demo data from overwriting sensitive WordPress options
     84* Updated the bundled WordPress Importer to 0.8.3 (security & bug fixes, incl. safer attachment downloads and object-injection-safe meta handling)
     85* Fixed a bug that disabled the remote demo list cache (every admin page load re-fetched it)
     86* Replaced the deprecated get_page_by_title() with a WP_Query-based helper
     87* Prevented a fatal error in the plugin install/activate handlers when the theme helper is unavailable
     88* Various WordPress coding-standard fixes (text domains, output escaping, script/style enqueue)
     89
    5190= 1.0.2 =
    5291* Fixed some security vulnerablities
  • demo-awesome/tags/1.0.6/demo-awesome.php

    r3081092 r3813524  
    1010 * Plugin URI:        https://theme4press.com/demo-awesome-the-data-importer/
    1111 * Description:       Import the Theme4Press theme demo content including theme settings, menus, widgets, sliders, and much more with just one click. Awesome!
    12  * Version:           1.0.3
     12 * Version:           1.0.6
    1313 * Author:            Theme4Press
    1414 * Author URI:        https://theme4press.com
    … …  
    2727 * @since    1.0.0
    2828 */
    29 define( 'DEMO_AWESOME_VERSION', '1.0.0' );
     29define( 'DEMO_AWESOME_VERSION', '1.0.6' );
    3030
    3131/**
    … …  
    4444        }
    4545}
    46 // Allow SVG in wp_kses_post()
    47 function demo_awesome_allow_svg_in_wp_kses_post( $allowed_post_tags ) {
    48     $allowed_post_tags['svg'] = array(
    49         'xmlns' => true,
    50         'width' => true,
    51         'height' => true,
    52         'viewBox' => true,
    53         'fill' => true,
    54         'class' => true,
    55         'aria-hidden' => true,
    56         'role' => true,
    57         'focusable' => true,
    58         'style' => true,
    59     );
    60     $allowed_post_tags['path'] = array(
    61         'd' => true,
    62         'fill' => true,
    63     );
    64     return $allowed_post_tags;
    65 }
    66 add_filter( 'wp_kses_allowed_html', 'demo_awesome_allow_svg_in_wp_kses_post', 10, 1 );
     46// Security: SVG support removed due to XSS vulnerability
     47// SVG files can contain malicious JavaScript and are not safe for upload
     48// Use PNG, JPG, or other safe image formats instead
    6749
    6850
  • demo-awesome/tags/1.0.6/inc/admin/class-demo-awesome-admin.php

    r3081092 r3813524  
    99 */
    1010
     11// Exit if accessed directly.
     12if (!defined('ABSPATH')) {
     13    exit;
     14}
     15
    1116if (!defined('DEMO_AWESOME_IMPORTER_FOLDER')) {
    1217    define('DEMO_AWESOME_IMPORTER_FOLDER', '/demo-awesome-import/');
    … …  
    4853            add_action('wp_loaded', array($this, 'hide_notice'));
    4954            add_filter(
    50                 'customizer_demo_import_settings',
     55                'demo_awesome_customizer_import_settings',
    5156                array(
    5257                    $this,
    … …  
    5661                2
    5762            );
    58             add_filter('widget_demo_import_settings', array($this, 'update_widget_data'), 10, 4);
    59 
    60             if (isset($_GET['hide-notice']) && $_GET['hide-notice'] == 'demo_awesome_no_theme4press_theme_notice') {
     63            add_filter('demo_awesome_widget_import_settings', array($this, 'update_widget_data'), 10, 4);
     64
     65            if (isset($_GET['hide-notice'])
     66                && 'demo_awesome_no_theme4press_theme_notice' === sanitize_text_field(wp_unslash($_GET['hide-notice']))
     67                && isset($_GET['_demo_awesome_notice'])
     68                && wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['_demo_awesome_notice'])), 'demo_awesome_hide_notice')
     69                && current_user_can('edit_theme_options')) {
    6170                update_option('demo_awesome_no_theme4press_theme_notice', 0);
    6271            }
    … …  
    8594        public static function hide_notice()
    8695        {
    87             if (isset($_GET['demo-awesome-hide-notice']) && $_GET['demo-awesome-hide-notice'] == 'activation_notice') {
    88                 if (!wp_verify_nonce($_GET['_demo_awesome_notice'], 'demo_awesome_hide_notice')) {
    89                     wp_die(__('Action failed. Please refresh the page and retry.', 'evolve'));
     96            if (isset($_GET['demo-awesome-hide-notice']) && 'activation_notice' === sanitize_text_field(wp_unslash($_GET['demo-awesome-hide-notice']))) {
     97                $notice_nonce = isset($_GET['_demo_awesome_notice']) ? sanitize_text_field(wp_unslash($_GET['_demo_awesome_notice'])) : '';
     98                if (!wp_verify_nonce($notice_nonce, 'demo_awesome_hide_notice')) {
     99                    wp_die(esc_html__('Action failed. Please refresh the page and retry.', 'demo-awesome'));
    90100                }
    91101
    92102                if (!current_user_can('manage_options')) {
    93                     wp_die(__('Cheatin’ huh?', 'evolve'));
    94                 }
    95 
    96                 $hide_notice = sanitize_text_field($_GET['demo-awesome-hide-notice']);
     103                    wp_die(esc_html__('Cheatin’ huh?', 'demo-awesome'));
     104                }
     105
     106                $hide_notice = sanitize_text_field(wp_unslash($_GET['demo-awesome-hide-notice']));
    97107                update_option('demo_awesome_'.$hide_notice, 1);
    98108            }
    … …  
    112122        function get_demo_packages($url, $template_name = '', $save_cache = true)
    113123        {
    114             $packages = '';
    115             $decode_url = base64_encode($url);
    116             if (true || false === ($create_time = get_transient('demo_awesome_importer_packages_'.$decode_url))) {
    117                 $raw_packages = wp_safe_remote_get($url);
    118                 if (!is_wp_error($raw_packages)) {
    119                     $packages = wp_remote_retrieve_body($raw_packages);
    120                     if ($packages) {
    121                         set_transient('demo_awesome_importer_packages_'.$decode_url, time(), HOUR_IN_SECONDS);
    122                         $this->write_file_to_local($packages, $decode_url.'.txt');
     124            // Security: Validate URL
     125            if (!$this->validate_external_url($url)) {
     126                return false;
     127            }
     128
     129            // Cache file name and transient key are derived from an md5 of the URL. (They used to
     130            // be base64, whose "=" padding was stripped when writing the file but not when reading
     131            // it, so every cached read of such a URL failed.)
     132            $cache_key = md5($url);
     133            $transient = 'demo_awesome_importer_packages_'.$cache_key;
     134            $cache_file = $cache_key.'.txt';
     135
     136            // Use the cached copy if it is fresh and still valid; otherwise download again.
     137            if (false !== get_transient($transient)) {
     138                $file_path = wp_upload_dir()['basedir'].DEMO_AWESOME_IMPORTER_FOLDER.$cache_file;
     139                if (file_exists($file_path) && is_readable($file_path)) {
     140                    $packages = file_get_contents($file_path);
     141                    if ($packages && $this->validate_response_content($packages)) {
     142                        return $packages;
    123143                    }
    124144                }
    125             } else {
    126                 $packages = file_get_contents(
    127                     wp_upload_dir()['basedir'].DEMO_AWESOME_IMPORTER_FOLDER.$decode_url.'.txt'
    128                 );
     145            }
     146
     147            // Security: Use wp_safe_remote_get with proper args
     148            $raw_packages = wp_safe_remote_get($url, array(
     149                'timeout' => 30,
     150                'redirection' => 3,
     151                'user-agent' => 'Demo Awesome Plugin',
     152                'sslverify' => true,
     153                'headers' => array(
     154                    'Accept' => 'application/json, text/plain, */*',
     155                )
     156            ));
     157
     158            if (is_wp_error($raw_packages) || wp_remote_retrieve_response_code($raw_packages) !== 200) {
     159                return false;
     160            }
     161
     162            $packages = wp_remote_retrieve_body($raw_packages);
     163
     164            // Security: Validate response content
     165            if (!$packages || !$this->validate_response_content($packages)) {
     166                return false;
     167            }
     168
     169            // Only mark the cache as fresh if the copy was actually written.
     170            if ($this->write_file_to_local($packages, $cache_file)) {
     171                set_transient($transient, time(), HOUR_IN_SECONDS);
    129172            }
    130173
    131174            return $packages;
     175        }
     176
     177        /**
     178         * Validate external URL to prevent SSRF attacks
     179         * @since 1.0.3
     180         */
     181        private function validate_external_url($url) {
     182            // Check if URL is valid
     183            if (!filter_var($url, FILTER_VALIDATE_URL)) {
     184                return false;
     185            }
     186           
     187            $parsed_url = wp_parse_url($url);
     188           
     189            // Check if URL has required components
     190            if (!isset($parsed_url['scheme']) || !isset($parsed_url['host'])) {
     191                return false;
     192            }
     193           
     194            // Only allow HTTPS
     195            if ($parsed_url['scheme'] !== 'https') {
     196                return false;
     197            }
     198           
     199            // Whitelist allowed hosts
     200            $allowed_hosts = ['demo.theme4press.com'];
     201            if (!in_array($parsed_url['host'], $allowed_hosts)) {
     202                return false;
     203            }
     204           
     205            // Check for localhost/private IP attempts
     206            $ip = gethostbyname($parsed_url['host']);
     207            if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false) {
     208                return false;
     209            }
     210           
     211            return true;
     212        }
     213
     214        /**
     215         * Validate response content from external requests
     216         * @since 1.0.3
     217         */
     218        private function validate_response_content($content) {
     219            // Check for empty content
     220            if (empty($content)) {
     221                return false;
     222            }
     223           
     224            // Check content length (prevent DoS). Same limit as validate_file_content().
     225            if (strlen($content) > 50 * 1024 * 1024) {
     226                return false;
     227            }
     228
     229            // No keyword filtering here: every response is cached and written through
     230            // write_file_to_local(), which validates it per file type (XML/JSON/serialized/ZIP)
     231            // and rejects PHP code. Blocking "<script", "javascript:" or "data:" rejected
     232            // legitimate demo content (e.g. cached Twitter/YouTube embeds in post meta),
     233            // which WordPress itself stores and imports as normal content.
     234            return true;
     235        }
     236
     237        /**
     238         * Whether a downloaded file contains a PHP opening tag.
     239         * Demo data never legitimately contains PHP code.
     240         * @since 1.0.6
     241         */
     242        private function contains_php_code($content) {
     243            return (bool) preg_match('/<\?php|<\?=/i', $content);
    132244        }
    133245
    … …  
    164276        function write_file_to_local($file_content, $file_name = 'content.xml')
    165277        {
     278            // Security: Validate and sanitize filename
     279            $file_name = $this->validate_and_sanitize_filename($file_name);
     280            if (!$file_name) {
     281                return false;
     282            }
     283
     284            // Security: Validate file content
     285            if (!$this->validate_file_content($file_content, $file_name)) {
     286                return false;
     287            }
    166288
    167289            global $wp_filesystem;
    … …  
    171293                WP_Filesystem();
    172294            }
     295           
    173296            $upload_dir = wp_upload_dir()['basedir'].DEMO_AWESOME_IMPORTER_FOLDER;
    174297            if (!is_dir($upload_dir)) {
    175                 mkdir($upload_dir, 0755);
    176             }
     298                // wp_mkdir_p() applies the correct, WordPress-managed directory permissions (FS_CHMOD_DIR).
     299                wp_mkdir_p($upload_dir);
     300            }
     301           
    177302            $file_path = $upload_dir.$file_name;
     303           
     304            // Security: Additional path validation
     305            $real_upload_dir = realpath($upload_dir);
     306            $real_file_path = realpath(dirname($file_path));
     307            if ($real_file_path === false || strpos($real_file_path, $real_upload_dir) !== 0) {
     308                return false;
     309            }
     310           
    178311            $result = $wp_filesystem->put_contents(
    179312                $file_path,
    … …  
    182315            );
    183316
    184             return $file_path;
     317            return $result ? $file_path : false;
     318        }
     319
     320        /**
     321         * Validate and sanitize filename to prevent path traversal and malicious files
     322         * @since 1.0.3
     323         */
     324        private function validate_and_sanitize_filename($filename) {
     325            // Remove any path components
     326            $filename = basename($filename);
     327           
     328            // Check for empty filename
     329            if (empty($filename)) {
     330                return false;
     331            }
     332           
     333            // Check for path traversal attempts
     334            if (strpos($filename, '..') !== false || strpos($filename, '/') !== false || strpos($filename, '\\') !== false) {
     335                return false;
     336            }
     337           
     338            // Check for null bytes
     339            if (strpos($filename, "\0") !== false) {
     340                return false;
     341            }
     342           
     343            // Sanitize filename
     344            $filename = sanitize_file_name($filename);
     345           
     346            // Validate file extension
     347            $allowed_extensions = array('xml', 'dat', 'wie', 'zip', 'txt', 'json');
     348            $file_extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
     349           
     350            if (!in_array($file_extension, $allowed_extensions)) {
     351                return false;
     352            }
     353           
     354            // Check filename length
     355            if (strlen($filename) > 255) {
     356                return false;
     357            }
     358           
     359            return $filename;
     360        }
     361
     362        /**
     363         * Validate file content to prevent malicious uploads
     364         * @since 1.0.3
     365         */
     366        private function validate_file_content($content, $filename) {
     367            // Check for empty content
     368            if (empty($content)) {
     369                return false;
     370            }
     371           
     372            // Check content length (prevent DoS)
     373            if (strlen($content) > 50 * 1024 * 1024) { // 50MB limit
     374                return false;
     375            }
     376           
     377            $file_extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
     378           
     379            // Content validation based on file type
     380            switch ($file_extension) {
     381                case 'xml':
     382                    return $this->validate_xml_content($content);
     383                case 'json':
     384                    return $this->validate_json_content($content);
     385                case 'dat':
     386                    return $this->validate_dat_content($content);
     387                case 'wie':
     388                    return $this->validate_wie_content($content);
     389                case 'zip':
     390                    return $this->validate_zip_content($content);
     391                case 'txt':
     392                    return $this->validate_txt_content($content);
     393                default:
     394                    return false;
     395            }
     396        }
     397
     398        /**
     399         * Validate XML content
     400         * @since 1.0.3
     401         */
     402        private function validate_xml_content($content) {
     403            // Check for PHP code injection
     404            if ($this->contains_php_code($content)) {
     405                return false;
     406            }
     407           
     408            // Basic XML structure validation.
     409            // Security: disable network access and external entity loading to
     410            // prevent XXE and entity-expansion (billion laughs) attacks. Never
     411            // use LIBXML_NOENT/LIBXML_DTDLOAD here, they enable the very attacks
     412            // this check is meant to guard against.
     413            if (PHP_VERSION_ID < 80000 && function_exists('libxml_disable_entity_loader')) {
     414                $previous_loader = libxml_disable_entity_loader(true);
     415            }
     416            $previous_errors = libxml_use_internal_errors(true);
     417
     418            $dom    = new DOMDocument();
     419            $loaded = $dom->loadXML($content, LIBXML_NONET);
     420
     421            libxml_clear_errors();
     422            libxml_use_internal_errors($previous_errors);
     423            if (PHP_VERSION_ID < 80000 && function_exists('libxml_disable_entity_loader') && isset($previous_loader)) {
     424                libxml_disable_entity_loader($previous_loader);
     425            }
     426
     427            return $loaded !== false;
     428        }
     429
     430        /**
     431         * Validate JSON content
     432         * @since 1.0.3
     433         */
     434        private function validate_json_content($content) {
     435            // Check for PHP code injection
     436            if ($this->contains_php_code($content)) {
     437                return false;
     438            }
     439           
     440            $decoded = json_decode($content, true);
     441            return json_last_error() === JSON_ERROR_NONE;
     442        }
     443
     444        /**
     445         * Validate DAT content (serialized data)
     446         * @since 1.0.3
     447         */
     448        private function validate_dat_content($content) {
     449            // Check for PHP code injection
     450            if ($this->contains_php_code($content)) {
     451                return false;
     452            }
     453           
     454            // Basic validation for serialized data. Disable object instantiation
     455            // so the validation step itself cannot trigger PHP object injection.
     456            if (!is_serialized($content)) {
     457                return false;
     458            }
     459            $unserialized = unserialize(trim($content), array('allowed_classes' => false));
     460            return $unserialized !== false;
     461        }
     462
     463        /**
     464         * Validate WIE content (widget import/export)
     465         * @since 1.0.3
     466         */
     467        private function validate_wie_content($content) {
     468            // Check for PHP code injection
     469            if ($this->contains_php_code($content)) {
     470                return false;
     471            }
     472           
     473            $decoded = json_decode($content, true);
     474            return json_last_error() === JSON_ERROR_NONE;
     475        }
     476
     477        /**
     478         * Validate ZIP content
     479         * @since 1.0.3
     480         */
     481        private function validate_zip_content($content) {
     482            // Check ZIP file signature
     483            if (substr($content, 0, 2) !== 'PK') {
     484                return false;
     485            }
     486           
     487            // Additional ZIP validation could be added here
     488            return true;
     489        }
     490
     491        /**
     492         * Validate TXT content
     493         * @since 1.0.3
     494         */
     495        private function validate_txt_content($content) {
     496            // Check for PHP code injection
     497            if ($this->contains_php_code($content)) {
     498                return false;
     499            }
     500           
     501            return true;
    185502        }
    186503
    … …  
    217534
    218535        /**
     536         * Enhanced validation and sanitization for demo data
     537         * @since 1.0.3
     538         */
     539        private function validate_and_sanitize_demo_data($data) {
     540            if (!is_array($data)) {
     541                return false;
     542            }
     543
     544            $allowed_keys = array(
     545                'folder_path', 'name', 'premium_demo', 'has_theme4press_slider_data',
     546                'has_slider_revolution_data', 'has_layerslider_data', 'plugins',
     547                'option_update', 'update_galleries', 'customizer_data_update',
     548                'widgets_data_update', 'require_ver_premium', 'require_ver_free'
     549            );
     550
     551            $sanitized_data = array();
     552           
     553            foreach ($data as $key => $value) {
     554                // Only allow whitelisted keys
     555                if (!in_array($key, $allowed_keys)) {
     556                    continue;
     557                }
     558
     559                if (is_array($value)) {
     560                    $sanitized_data[$key] = $this->sanitize_nested_array($value);
     561                } else {
     562                    $sanitized_data[$key] = sanitize_text_field($value);
     563                }
     564            }
     565
     566            return $sanitized_data;
     567        }
     568
     569        /**
     570         * Validate template name to prevent directory traversal
     571         * @since 1.0.3
     572         */
     573        private function validate_template_name($template_name) {
     574            if (empty($template_name)) {
     575                return false;
     576            }
     577
     578            // Check length
     579            if (strlen($template_name) > 100) {
     580                return false;
     581            }
     582
     583            // Demo folders are "<category>/<number>" (e.g. "business/1"), so one "/" between
     584            // two safe segments is allowed. The whitelist excludes "..", backslashes, null
     585            // bytes, leading/trailing slashes and anything else that could leave the demo folder.
     586            return (bool) preg_match('#^[a-zA-Z0-9_-]+(/[a-zA-Z0-9_-]+)?$#', $template_name);
     587        }
     588
     589        /**
     590         * Look up the demo the user picked in the demo list downloaded from the demo server.
     591         *
     592         * The browser only identifies the demo by its "index". Everything else (folder, required
     593         * plugins, options to update, slider flags) comes from the server-side list, never from
     594         * the request, so a forged request cannot change what gets downloaded or which options
     595         * get written.
     596         *
     597         * @since 1.0.6
     598         * @return array|false Normalized demo data, or false if the demo is not in the list.
     599         */
     600        private function get_requested_demo() {
     601            // Only called from AJAX handlers that verify the 'demo-awesome' nonce and the
     602            // manage_options capability before calling this method.
     603            // phpcs:disable WordPress.Security.NonceVerification.Missing
     604            $index = '';
     605            if (isset($_POST['demo_index'])) {
     606                $index = sanitize_text_field(wp_unslash($_POST['demo_index']));
     607            } elseif (isset($_POST['data_demo']['index'])) {
     608                // Older admin.js sends the whole demo object; only its index is used.
     609                $index = sanitize_text_field(wp_unslash($_POST['data_demo']['index']));
     610            }
     611            // phpcs:enable WordPress.Security.NonceVerification.Missing
     612            if ($index === '' || !preg_match('/^[0-9]+$/', $index)) {
     613                return false;
     614            }
     615
     616            $list = json_decode((string) $this->get_list_demos(), true);
     617            if (!is_array($list)) {
     618                return false;
     619            }
     620            foreach ($list as $category) {
     621                if (empty($category['items']) || !is_array($category['items'])) {
     622                    continue;
     623                }
     624                foreach ($category['items'] as $item) {
     625                    if (isset($item['index']) && (string) $item['index'] === $index) {
     626                        return $this->normalize_demo_data($item);
     627                    }
     628                }
     629            }
     630
     631            return false;
     632        }
     633
     634        /**
     635         * Fill in optional demo fields so later code can rely on them being set, and map the
     636         * demo list's "has_LayerSlider WP_data" key to the "has_layerslider_data" key used here.
     637         *
     638         * @since 1.0.6
     639         */
     640        private function normalize_demo_data($demo) {
     641            if (isset($demo['has_LayerSlider WP_data']) && !isset($demo['has_layerslider_data'])) {
     642                $demo['has_layerslider_data'] = $demo['has_LayerSlider WP_data'];
     643            }
     644            $defaults = array(
     645                'premium_demo' => false,
     646                'has_theme4press_slider_data' => false,
     647                'has_slider_revolution_data' => false,
     648                'has_layerslider_data' => false,
     649                'plugins' => array(),
     650                'option_update' => array(),
     651                'update_galleries' => array(),
     652                'customizer_data_update' => array(),
     653                'widgets_data_update' => array(),
     654            );
     655
     656            return $this->validate_and_sanitize_demo_data(array_merge($defaults, $demo));
     657        }
     658
     659        /**
     660         * Validate plugin name to prevent malicious plugin installation
     661         * @since 1.0.3
     662         */
     663        private function validate_plugin_name($plugin_name) {
     664            if (empty($plugin_name)) {
     665                return false;
     666            }
     667
     668            // Check for path traversal attempts
     669            if (strpos($plugin_name, '..') !== false ||
     670                strpos($plugin_name, '/') !== false ||
     671                strpos($plugin_name, '\\') !== false) {
     672                return false;
     673            }
     674
     675            // Check for null bytes
     676            if (strpos($plugin_name, "\0") !== false) {
     677                return false;
     678            }
     679
     680            // Check length
     681            if (strlen($plugin_name) > 100) {
     682                return false;
     683            }
     684
     685            // Only allow alphanumeric, hyphens, underscores, and spaces (covers both
     686            // plugin slugs and display names). The capability check
     687            // (install_plugins / activate_plugins) is the real authorization gate;
     688            // this only rejects path traversal, null bytes and regex-unsafe input.
     689            if (!preg_match('/^[a-zA-Z0-9_\- ]+$/', $plugin_name)) {
     690                return false;
     691            }
     692
     693            return true;
     694        }
     695
     696        /**
    219697         * @since    1.0.0
    220698         */
    221699        function call_import_function_from_ajax()
    222700        {
    223             if ( !wp_verify_nonce( $_POST['nonce'] ?? '', 'demo-awesome' ) ) {
    224                 wp_send_json_error( 'Invalid nonce' );
     701            // Security: Enhanced nonce verification
     702            if ( !wp_verify_nonce( isset($_POST['_nonce']) ? sanitize_text_field(wp_unslash($_POST['_nonce'])) : '', 'demo-awesome' ) ) {
     703                wp_send_json_error( array(
     704                    'message' => 'Security check failed. Please refresh the page and try again.',
     705                    'code' => 'invalid_nonce'
     706                ));
    225707                wp_die();
    226708            }
    227709
     710            // Security: Enhanced capability check
    228711            if ( !current_user_can('manage_options') ) {
    229                 wp_die('You do not have sufficient permissions to access this feature.');
    230             }       
    231             $data_demo_raw = isset($_REQUEST['data_demo']) ? $_REQUEST['data_demo'] : array();
    232             $data_demo = array();
    233 
    234             // Sanitize the data
    235             if (is_array($data_demo_raw)) {
    236                 $data_demo = $this->sanitize_nested_array($data_demo_raw);
    237             } else {
    238                 $data_demo = esc_attr($data_demo_raw);
     712                wp_send_json_error( array(
     713                    'message' => 'You do not have sufficient permissions to access this feature.',
     714                    'code' => 'insufficient_permissions'
     715                ));
     716                wp_die();
     717            }
     718
     719            // Security: the demo is looked up by index in the server-side demo list; no other
     720            // request data is used.
     721            $data_demo = $this->get_requested_demo();
     722            if ($data_demo === false) {
     723                wp_send_json_error( array(
     724                    'message' => esc_html__('The selected demo could not be found in the demo list. Please reload the page and try again. If it keeps happening, the demo server may be unreachable.', 'demo-awesome'),
     725                    'code' => 'demo_not_found'
     726                ));
     727                wp_die();
    239728            }
    240729
    241730            $template_name = isset($data_demo['folder_path']) ? $data_demo['folder_path'] : '';
    242731
    243             $this->remove_old_datas($data_demo, $template_name);
    244 
     732            // Security: Validate template name
     733            if (!$this->validate_template_name($template_name)) {
     734                wp_send_json_error( array(
     735                    'message' => esc_html__('Invalid demo folder.', 'demo-awesome'),
     736                    'code' => 'invalid_template'
     737                ));
     738                wp_die();
     739            }
     740
     741            // Check this before remove_old_datas(): refusing a premium demo must not
     742            // first wipe the site's theme settings, menus and widgets.
    245743            if (Demo_Awesome_Admin::is_premium_theme() == false && $data_demo['premium_demo']) {
    246                 wp_send_json_success(
     744                wp_send_json_error(
    247745                    array(
    248                         'success' => true,
    249                         'message' => sprintf(
    250                             '<span>%s</span>',
    251                             esc_html__('The premium demo requires the premium theme version', 'demo-awesome')
    252                         ),
     746                        'message' => esc_html__('The premium demo requires the premium theme version', 'demo-awesome'),
     747                        'code' => 'premium_required'
    253748                    )
    254749                );
    255750                wp_die();
    256751            }
     752
     753            // Download and validate the demo content before removing anything, so a failed
     754            // download leaves the site untouched. The file is cached, so the import step below
     755            // reuses it instead of downloading it again.
     756            if (!$this->get_import_file_path($template_name)) {
     757                wp_send_json_error( array(
     758                    'message' => esc_html__('The demo content could not be downloaded from the demo server, or it failed validation. Nothing on your site was changed. Please try again later.', 'demo-awesome'),
     759                    'code' => 'download_failed'
     760                ));
     761                wp_die();
     762            }
     763
     764            $this->remove_old_datas($data_demo, $template_name);
    257765            // Import content data
    258766            $this->import_content_theme($data_demo, $template_name);
    … …  
    343851        function required_plugins()
    344852        {
     853            // Security: Enhanced nonce verification
     854            if (!wp_verify_nonce(isset($_POST['_nonce']) ? sanitize_text_field(wp_unslash($_POST['_nonce'])) : '', 'demo-awesome')) {
     855                wp_die(esc_html__('Security check failed.', 'demo-awesome'));
     856            }
     857           
     858            // Security: Enhanced capability check
     859            if (!current_user_can('manage_options')) {
     860                wp_die(esc_html__('You do not have sufficient permissions.', 'demo-awesome'));
     861            }
     862
     863           
    345864            // Include the required plugins list
    346865            require dirname(__FILE__).'/required-plugins.php';
    347             $data_demo_raw = isset($_REQUEST['data_demo']) ? $_REQUEST['data_demo'] : array();
    348             $data_demo = array();
    349            
    350             //TODO (EvgenyViner): Look for a more elegant way to sanitize the data
    351 
    352             if (is_array($data_demo_raw)) {
    353                 foreach($data_demo_raw as $key => $item) {
    354                     if(is_array($data_demo_raw[$key])) {
    355                         foreach($data_demo_raw[$key] as $key2 => $item2) {
    356                             if(is_array($data_demo_raw[$key][$key2])) {
    357                                 foreach($data_demo_raw[$key][$key2] as $key3 => $item3) {
    358                                     $data_demo[$key][$key2][$key3] = esc_attr($item3);
    359                                 }
    360                             }
    361                             else $data_demo[$key][$key2] = esc_attr($item2);
    362                         }
    363                     }
    364                     else $data_demo[$key] = esc_attr($item);
    365                 }
    366             }
    367                 else {
    368                     $data_demo = htmlspecialchars((string)$data_demo_raw, ENT_QUOTES, 'UTF-8');
    369                 }
    370            
     866            // Security: the demo (and so its required-plugin list) comes from the server-side
     867            // demo list, looked up by index; no other request data is used.
     868            $data_demo = $this->get_requested_demo();
     869            if ($data_demo === false) {
     870                wp_die(esc_html__('The selected demo could not be found in the demo list. Please reload the page and try again.', 'demo-awesome'));
     871            }
     872
    371873            demo_awesome_required_plugins($data_demo);
    372874            wp_die(); // this is required to terminate immediately and return a proper response
    … …  
    375877        function evole_activate_plugin()
    376878        {
    377             $plugin = $_POST['plugin'];
     879            // Security: Enhanced nonce verification
     880            if (!wp_verify_nonce(isset($_POST['_nonce']) ? sanitize_text_field(wp_unslash($_POST['_nonce'])) : '', 'demo-awesome')) {
     881                wp_die(esc_html__('Security check failed.', 'demo-awesome'));
     882            }
     883   
     884            // Security: Enhanced capability check
     885            if (!current_user_can('activate_plugins')) {
     886                wp_die(esc_html__('Sorry, you are not allowed to activate plugins on this site.', 'demo-awesome'));
     887            }
     888
     889           
     890            // Security: Validate and sanitize plugin name
     891            $plugin = isset($_POST['plugin']) ? sanitize_text_field(wp_unslash($_POST['plugin'])) : '';
     892            if (!$this->validate_plugin_name($plugin)) {
     893                wp_die(esc_html__('Invalid plugin name provided.', 'demo-awesome'));
     894            }
     895           
    378896            $activate = isset($_POST['activate']) ? true : false;
    379897
    380898            if ($activate == false) {
    381899                if ($plugin == 'LayerSlider WP') {
    382                     evolve_get_update_plugin('layerslider');
     900                    if (function_exists('evolve_get_update_plugin')) {
     901                        evolve_get_update_plugin('layerslider');
     902                    }
    383903                    $plugin = 'LayerSlider';
    384904                } elseif ($plugin == 'slider-revolution') {
    385905                    $plugin = 'revslider';
    386906                } else {
    387                     evolve_get_update_plugin($plugin);
    388 
    389                 }
    390 
    391             }
    392             $html = str_replace('Not installed', 'Not active', stripslashes($_POST['html']));
     907                    if (function_exists('evolve_get_update_plugin')) {
     908                        evolve_get_update_plugin($plugin);
     909                    }
     910                }
     911
     912            }
     913            $html_raw = isset($_POST['html']) ? wp_kses_post(wp_unslash($_POST['html'])) : '';
     914            $html = str_replace('Not installed', 'Not active', $html_raw);
     915            // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- 'all_plugins' is a WordPress core filter.
    393916            $all_plugins = apply_filters('all_plugins', get_plugins());
    394917            foreach ($all_plugins as $k => $item) {
    395918
    396                 if (preg_match('#'.$plugin.'#', $k)) {
     919                if (preg_match('#'.preg_quote($plugin, '#').'#', $k)) {
    397920                    activate_plugin($k);
    398921                }
    … …  
    406929
    407930        function install_plugin()
    408         {
    409             $plugin = $_POST['plugin'];
     931        {   
     932            // Security: Enhanced nonce verification
     933            if (!wp_verify_nonce(isset($_POST['_nonce']) ? sanitize_text_field(wp_unslash($_POST['_nonce'])) : '', 'demo-awesome')) {
     934                wp_die(esc_html__('Security check failed.', 'demo-awesome'));
     935            }
     936
     937            // Security: Enhanced capability check
     938            if (!current_user_can('install_plugins')) {
     939                wp_die(esc_html__('Sorry, you are not allowed to install plugins on this site.', 'demo-awesome'));
     940            }
     941
     942
     943            // Security: Validate and sanitize plugin name
     944            $plugin = isset($_POST['plugin']) ? sanitize_text_field(wp_unslash($_POST['plugin'])) : '';
     945            if (!$this->validate_plugin_name($plugin)) {
     946                wp_die(esc_html__('Invalid plugin name provided.', 'demo-awesome'));
     947            }
     948           
    410949            $activate = isset($_POST['activate']) ? true : false;
    411950
    412951            if ($activate == false) {
    413952                if ($plugin == 'LayerSlider WP') {
    414                     evolve_get_update_plugin('layerslider');
     953                    if (function_exists('evolve_get_update_plugin')) {
     954                        evolve_get_update_plugin('layerslider');
     955                    }
    415956                    $plugin = 'LayerSlider';
    416957                } elseif ($plugin == 'slider-revolution') {
    417958                    $plugin = 'revslider';
    418959                } else {
    419                     evolve_get_update_plugin($plugin);
    420 
    421                 }
    422 
    423             }
    424 
     960                    if (function_exists('evolve_get_update_plugin')) {
     961                        evolve_get_update_plugin($plugin);
     962                    }
     963                }
     964
     965            }
     966
     967            // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- 'all_plugins' is a WordPress core filter.
    425968            $all_plugins = apply_filters('all_plugins', get_plugins());
    426969
    427970            foreach ($all_plugins as $k => $item) {
    428971
    429                 if (preg_match('#'.$plugin.'#', $k)) {
     972                if (preg_match('#'.preg_quote($plugin, '#').'#', $k)) {
    430973                    activate_plugin($k);
    431974                }
    432975            }
    433             $html = str_replace('Not installed', 'Not active', stripslashes($_POST['html']));
     976            $html_raw = isset($_POST['html']) ? wp_kses_post(wp_unslash($_POST['html'])) : '';
     977            $html = str_replace('Not installed', 'Not active', $html_raw);
    434978
    435979            echo wp_kses_post($html);
    … …  
    452996
    453997        /**
     998         * Determine whether an option name is too sensitive to be written from
     999         * remote demo data (prevents privilege escalation / takeover if the demo
     1000         * source is ever compromised or spoofed).
     1001         *
     1002         * @since 1.0.5
     1003         */
     1004        private function is_protected_option($option_name)
     1005        {
     1006            $protected = array(
     1007                'users_can_register', 'default_role', 'siteurl', 'home',
     1008                'admin_email', 'new_admin_email', 'template', 'stylesheet',
     1009                'active_plugins', 'mailserver_url', 'mailserver_login',
     1010                'mailserver_pass', 'mailserver_port', 'cron', 'rewrite_rules',
     1011                'ftp_credentials', 'auth_key', 'auth_salt', 'secret',
     1012                'db_version', 'WPLANG', 'fileupload_url',
     1013            );
     1014
     1015            return in_array($option_name, $protected, true);
     1016        }
     1017
     1018        /**
     1019         * Deprecation-safe replacement for get_page_by_title() (removed/deprecated
     1020         * in modern WordPress). Returns the first matching post object or null.
     1021         *
     1022         * @since 1.0.5
     1023         */
     1024        private function get_page_by_title_compat($title, $post_type = 'page')
     1025        {
     1026            $args = array(
     1027                'post_type'              => $post_type,
     1028                'title'                  => $title,
     1029                'posts_per_page'         => 1,
     1030                'no_found_rows'          => true,
     1031                'ignore_sticky_posts'    => true,
     1032                'update_post_term_cache' => false,
     1033                'update_post_meta_cache' => false,
     1034                'orderby'                => 'post_date ID',
     1035                'order'                  => 'ASC',
     1036            );
     1037
     1038            if ('attachment' === $post_type) {
     1039                $args['post_status'] = 'inherit';
     1040            }
     1041
     1042            $query = new WP_Query($args);
     1043
     1044            return !empty($query->posts) ? $query->posts[0] : null;
     1045        }
     1046
     1047        /**
    4541048         * @since    1.0.0
    4551049         */
    … …  
    4601054                    if ($data_type == 'update_pages' && $data_value && is_array($data_value) && count($data_value)) {
    4611055                        foreach ($data_value as $option_name => $option_value) {
    462                             $page = get_page_by_title($option_value);
     1056                            // Security: never let demo data target a protected option.
     1057                            if ($this->is_protected_option($option_name)) {
     1058                                continue;
     1059                            }
     1060                            $page = $this->get_page_by_title_compat($option_value);
    4631061                            if (is_object($page) && $page->ID) {
    4641062                                update_option($option_name, $page->ID);
    … …  
    4661064                        }
    4671065                    } else {
     1066                        // Security: never let demo data target a protected option.
     1067                        if ($this->is_protected_option($data_type)) {
     1068                            continue;
     1069                        }
    4681070                        update_option($data_type, $data_value);
    4691071                    }
    … …  
    4801082                foreach ($data_demo['update_galleries']['pages'] as $data_value) {
    4811083                    if (!empty($data_value['title'])) {
    482                         $page = get_page_by_title($data_value['title']);
     1084                        $page = $this->get_page_by_title_compat($data_value['title']);
    4831085                        if (is_object($page) && $page->ID) {
    4841086                            foreach ($data_value['items'] as $shortcode_values) {
    … …  
    4871089                                $new_ids = array();
    4881090                                foreach ($ids as $id_key => $id) {
    489                                     $attach = get_page_by_title($names[$id_key], OBJECT, 'attachment');
     1091                                    $attach = $this->get_page_by_title_compat($names[$id_key], 'attachment');
    4901092                                    if (is_object($attach) && $attach->ID) {
    4911093                                        $new_ids[] = $attach->ID;
    … …  
    5341136
    5351137            // Include Class Demo Awesome Importer
    536             require dirname(__FILE__).'/importer/class-demo-awesome-importer.php';
     1138            require_once dirname(__FILE__).'/importer/class-demo-awesome-importer.php';
    5371139
    5381140            if (is_file($import_file)) {
    … …  
    7031305                        foreach ($menu_items as $menu_item) {
    7041306                            if (isset($menu_item->url) && isset($menu_item->db_id) && 'custom' == $menu_item->type) {
    705                                 $site_parts = parse_url(home_url('/'));
    706                                 $menu_parts = parse_url($menu_item->url);
     1307                                $site_parts = wp_parse_url(home_url('/'));
     1308                                $menu_parts = wp_parse_url($menu_item->url);
    7071309
    7081310                                // Update existing custom nav menu item URL.
    … …  
    7551357                            foreach ($data_value as $option_key => $option_value) {
    7561358                                if (!empty($data['mods'][$option_key])) {
    757                                     $page = get_page_by_title($option_value);
     1359                                    $page = $this->get_page_by_title_compat($option_value);
    7581360
    7591361                                    if (is_object($page) && $page->ID) {
    … …  
    8251427                                if (!empty($widget_data[$instance_id]) && $widget_id == $widget_type) {
    8261428                                    foreach ($widget_data[$instance_id] as $widget_key => $widget_value) {
    827                                         $page = get_page_by_title($widget_value);
     1429                                        $page = $this->get_page_by_title_compat($widget_value);
    8281430
    8291431                                        if (is_object($page) && $page->ID) {
    … …  
    8861488            }
    8871489
    888             wp_enqueue_style('demo-awesome-notice', plugin_dir_url(__FILE__).'css/notice.css'); ?>
     1490            wp_enqueue_style('demo-awesome-notice', plugin_dir_url(__FILE__).'css/notice.css', array(), $this->version); ?>
    8891491
    8901492            <div class="notice demo-awesome-notice is-dismissible">
    8911493                <p>
    892                     <img src="<?php echo esc_url(plugin_dir_url(__FILE__)); ?>images/logo.png"/><?php echo sprintf(
     1494                    <img src="<?php echo esc_url(plugin_dir_url(__FILE__)); ?>images/logo.png"/>
     1495                    <?php
     1496                    echo wp_kses_post( sprintf(
     1497                        /* translators: 1: opening <strong> tag, 2: closing </strong> tag. */
    8931498                        esc_html__(
    8941499                            'Thank you for installing %1$sDemo Awesome%2$s plugin by Theme4Press. To start importing a demo content please visit the importer page',
    895                             'evolve'
     1500                            'demo-awesome'
    8961501                        ),
    8971502                        '<strong>',
    8981503                        '</strong>'
    899                     ); ?>
     1504                    ) ); ?>
    9001505                    <a class="button"
    9011506                       href="<?php echo esc_url(
    … …  
    9261531            }
    9271532
    928             wp_enqueue_style('demo-awesome-notice', plugin_dir_url(__FILE__).'css/notice.css'); ?>
     1533            wp_enqueue_style('demo-awesome-notice', plugin_dir_url(__FILE__).'css/notice.css', array(), $this->version); ?>
    9291534
    9301535            <div class="notice demo-awesome-notice is-dismissible">
    9311536                <p><?php echo wp_kses_post( Demo_Awesome_Admin::is_theme4press_theme_message()); ?><a
    9321537                            href="<?php echo esc_url(
    933                                 add_query_arg('hide-notice', 'demo_awesome_no_theme4press_theme_notice')
     1538                                wp_nonce_url(
     1539                                    add_query_arg('hide-notice', 'demo_awesome_no_theme4press_theme_notice'),
     1540                                    'demo_awesome_hide_notice',
     1541                                    '_demo_awesome_notice'
     1542                                )
    9341543                            ); ?>"><?php esc_html_e('Dismiss', 'demo-awesome'); ?></a>
    9351544                </p>
    … …  
    9451554            $message = '';
    9461555            if (!Demo_Awesome_Admin::is_theme4press_theme()) {
    947                 $message = "<span><img src='".plugin_dir_url(__FILE__)."images/logo.png' />".sprintf(
     1556                $message = "<span><img src='".esc_url(plugin_dir_url(__FILE__))."images/logo.png' />".sprintf(
     1557                        /* translators: 1,3: opening <strong> tag, 2,4: closing </strong> tag. */
    9481558                        esc_html__(
    9491559                            'The %1$sDemo Awesome%2$s plugin is designed only for %3$sTheme4Press%4$s themes',
    … …  
    10151625
    10161626        /**
     1627         * Allowlist for escaping markup that may contain inline SVG icons (from
     1628         * get_svg()). wp_kses_post() strips <svg>/<use>, so callers pass this list
     1629         * to wp_kses() to permit the icon markup in addition to standard post tags.
     1630         *
     1631         * Usage: echo wp_kses( $html, Demo_Awesome_Admin::allowed_svg_tags() );
     1632         *
     1633         * @since 1.0.5
     1634         * @return array Allowed HTML/SVG tags for wp_kses().
     1635         */
     1636        public static function allowed_svg_tags()
     1637        {
     1638            $svg_tags = array(
     1639                'svg'   => array(
     1640                    'class'           => true,
     1641                    'aria-hidden'     => true,
     1642                    'aria-labelledby' => true,
     1643                    'role'            => true,
     1644                    'xmlns'           => true,
     1645                    'width'           => true,
     1646                    'height'          => true,
     1647                    'viewbox'         => true,
     1648                    'fill'            => true,
     1649                    'focusable'       => true,
     1650                ),
     1651                'g'     => array('fill' => true),
     1652                'title' => array('title' => true),
     1653                'path'  => array('d' => true, 'fill' => true),
     1654                'use'   => array('href' => true, 'xlink:href' => true),
     1655            );
     1656
     1657            return array_merge(wp_kses_allowed_html('post'), $svg_tags);
     1658        }
     1659
     1660        /**
    10171661         * @since    1.0.0
    10181662         */
    … …  
    11071751            }
    11081752
    1109             wp_enqueue_style('demo-awesome', plugin_dir_url(__FILE__).'css/admin.css');
     1753            wp_enqueue_style('demo-awesome', plugin_dir_url(__FILE__).'css/admin.css', array(), $this->version);
    11101754        }
    11111755
    … …  
    11201764            }
    11211765
    1122             wp_enqueue_script('demo-awesome', plugin_dir_url(__FILE__).'js/admin.js');
    1123 
     1766            wp_enqueue_script('demo-awesome', plugin_dir_url(__FILE__).'js/admin.js', array('jquery'), $this->version, true);
     1767         
     1768         
    11241769            $local_variables = array(
    11251770                'close_button' => esc_html__('Close', 'demo-awesome'),
    … …  
    11341779                'is_free_version' => Demo_Awesome_Admin::is_free_theme(),
    11351780                'is_theme4press_theme' => Demo_Awesome_Admin::is_theme4press_theme(),
    1136                 'nonce'    => wp_create_nonce('demo-awesome')
     1781                '_nonce'    => wp_create_nonce('demo-awesome')
    11371782            );
    11381783
  • demo-awesome/tags/1.0.6/inc/admin/demo-browser.php

    r3081092 r3813524  
    99 */
    1010
     11// Exit if accessed directly.
     12if ( ! defined( 'ABSPATH' ) ) {
     13        exit;
     14}
     15
    1116if ( $demo_awesome_get_list_demos ) {
    1217        $demo_awesome_get_list_demos = json_decode( $demo_awesome_get_list_demos, true );
    … …  
    2631                                    data-filter="<?php echo esc_attr( $demo_awesome_item_key ); ?>"
    2732                                    href="#"
    28                                     aria-selected="false"><?php esc_html_e( $demo_awesome_item['name'] ); ?></a>
     33                                    aria-selected="false"><?php echo esc_html( $demo_awesome_item['name'] ); ?></a>
    2934            </li>
    3035                <?php }
    … …  
    5055                        }
    5156                        $demo_awesome_number_demos = count( $demo_awesome_list_demos );
    52                         for ( $i = 0; $i < $demo_awesome_number_demos; $i ++ ) {
    53                                 $demo_awesome_list_demos_sorted[] = $demo_awesome_list_demos[ $i ];
     57                        for ( $demo_awesome_i = 0; $demo_awesome_i < $demo_awesome_number_demos; $demo_awesome_i ++ ) {
     58                                $demo_awesome_list_demos_sorted[] = $demo_awesome_list_demos[ $demo_awesome_i ];
    5459                        }
    5560                }
    … …  
    8085                        <div class="demo-container">
    8186                            <h2 class="demo-name"
    82                                 id="demo-name"><?php esc_html_e( $demo_awesome_item_2['name'] ); ?></h2>
     87                                id="demo-name"><?php echo esc_html( $demo_awesome_item_2['name'] ); ?></h2>
    8388
    8489                            <div class="demo-actions"
    … …  
    127132                                                <?php esc_html_e( 'Minimum recommended theme version for this demo: ', 'demo-awesome' ); ?><span
    128133                                class="theme-required-version"></span><br/>
    129                         <h3><?php echo  esc_html( sprintf( esc_html__( 'Installed theme version: %s', 'demo-awesome' ), $demo_awesome_my_theme['Version'] )); ?></h3>
     134                        <h3><?php /* translators: %s: the installed theme version number. */ echo esc_html( sprintf( esc_html__( 'Installed theme version: %s', 'demo-awesome' ), $demo_awesome_my_theme->get('Version') )); ?></h3>
    130135
    131136                                                <?php if ( Demo_Awesome_Admin::is_theme4press_theme() ) {
    … …  
    139144                    <div class="wizard-step">
    140145                        <div class="alert" role="alert">
    141                             <span class="mr-1"><?php echo Demo_Awesome_Admin::get_svg( 'warning' ); ?></span><?php echo sprintf( ( '%1$s%2$s%3$s%4$s%5$s%6$s%7$s%8$s%9$s%10$s%11$s%12$s%13$s' ), esc_html__( 'The demo import may overwrite/remove many website options', 'demo-awesome' ), '<br /><br />- ', esc_html__( 'customizer settings', 'demo-awesome' ), '<br />- ', esc_html__( 'menus', 'demo-awesome' ), '<br />- ', esc_html__( 'widgets', 'demo-awesome' ), '<br />- ', esc_html__( 'posts/pages', 'demo-awesome' ), '<br />- ', esc_html__( 'set new front page', 'demo-awesome' ), '<br /><br />', esc_html__( 'Some demos can take few minutes to complete the import, depending on the complexity of the demo content.', 'demo-awesome' ) ); ?>
     146                            <span class="mr-1"><?php echo wp_kses( Demo_Awesome_Admin::get_svg( 'warning' ), Demo_Awesome_Admin::allowed_svg_tags() ); ?></span><?php echo sprintf( ( '%1$s%2$s%3$s%4$s%5$s%6$s%7$s%8$s%9$s%10$s%11$s%12$s%13$s' ), esc_html__( 'The demo import may overwrite/remove many website options', 'demo-awesome' ), '<br /><br />- ', esc_html__( 'customizer settings', 'demo-awesome' ), '<br />- ', esc_html__( 'menus', 'demo-awesome' ), '<br />- ', esc_html__( 'widgets', 'demo-awesome' ), '<br />- ', esc_html__( 'posts/pages', 'demo-awesome' ), '<br />- ', esc_html__( 'set new front page', 'demo-awesome' ), '<br /><br />', esc_html__( 'Some demos can take few minutes to complete the import, depending on the complexity of the demo content.', 'demo-awesome' ) ); ?>
    142147                        </div>
    143148
    … …  
    173178
    174179                    <div class="alert hide-content" role="alert">
    175                         <span class="mr-1"><?php echo Demo_Awesome_Admin::get_svg( 'warning' ); ?></span><?php esc_html_e( 'Please don\'t leave/refresh the page while importing. Some demos can take few minutes to complete the import, depending on the complexity of the demo content', 'demo-awesome' ); ?>
    176                     </div>
    177 
    178                     <h3 class="hide-content"><?php echo '<span class="svg-spin mr-1">' . Demo_Awesome_Admin::get_svg( 'loader' ) . '</span>';
     180                        <span class="mr-1"><?php echo wp_kses( Demo_Awesome_Admin::get_svg( 'warning' ), Demo_Awesome_Admin::allowed_svg_tags() ); ?></span><?php esc_html_e( 'Please don\'t leave/refresh the page while importing. Some demos can take few minutes to complete the import, depending on the complexity of the demo content', 'demo-awesome' ); ?>
     181                    </div>
     182
     183                    <h3 class="hide-content"><?php echo wp_kses( '<span class="svg-spin mr-1">' . Demo_Awesome_Admin::get_svg( 'loader' ) . '</span>', Demo_Awesome_Admin::allowed_svg_tags() );
    179184                                                esc_html_e( 'Importing the demo...', 'demo-awesome' ); ?>
    180185                    </h3>
    181186
    182187                    <div class="alert alert-success alert-message-from-importer hide show-content" role="alert">
    183                         <h3><?php echo '<span class="mr-1">' . Demo_Awesome_Admin::get_svg( 'check' ) . '</span>';
     188                        <h3><?php echo wp_kses( '<span class="mr-1">' . Demo_Awesome_Admin::get_svg( 'check' ) . '</span>', Demo_Awesome_Admin::allowed_svg_tags() );
    184189                                                        esc_html_e( 'Import finished', 'demo-awesome' ); ?>
    185190                        </h3>
    … …  
    191196                <div class="modal-footer hide show-content">
    192197                    <a type="button" class="button back" target="_blank"
    193                        href="<?php echo site_url(); ?>"><?php esc_html_e( 'View Website', 'demo-awesome' ); ?></a>
     198                       href="<?php echo esc_url( site_url() ); ?>"><?php esc_html_e( 'View Website', 'demo-awesome' ); ?></a>
    194199                    <a type="button" class="button back"
    195                        href="<?php echo admin_url( "customize.php" ); ?>"><?php esc_html_e( 'Customize', 'demo-awesome' ); ?></a>
     200                       href="<?php echo esc_url( admin_url( 'customize.php' ) ); ?>"><?php esc_html_e( 'Customize', 'demo-awesome' ); ?></a>
    196201                    <a role="button" class="button button-primary"
    197202                       data-dismiss="modal" href="#"
    … …  
    232237                                                                <?php esc_html_e( 'Minimum recommended theme version for this demo: ', 'demo-awesome' ); ?>
    233238                                <span class="theme-required-version"></span><br/>
    234                                 <h3><?php echo sprintf( esc_html__( 'Installed theme version: %s', 'demo-awesome' ), $demo_awesome_my_theme['Version'] ); ?></h3>
     239                                <h3><?php /* translators: %s: the installed theme version number. */ echo esc_html( sprintf( esc_html__( 'Installed theme version: %s', 'demo-awesome' ), $demo_awesome_my_theme->get('Version') ) ); ?></h3>
    235240                            </div>
    236241
    … …  
    240245                                                        if ( Demo_Awesome_Admin::is_free_theme() ) { ?>
    241246                                <p class="alert alert-info required-premium-text"><span
    242                                             class="mr-1"><?php echo Demo_Awesome_Admin::get_svg( 'info' ); ?></span><span><?php echo sprintf( esc_html__( 'This demo requires the %1$sPremium%2$s version of the theme', 'demo-awesome' ), '<strong>', '</strong>' ); ?></span>
     247                                            class="mr-1"><?php echo wp_kses( Demo_Awesome_Admin::get_svg( 'info' ), Demo_Awesome_Admin::allowed_svg_tags() ); ?></span><span><?php /* translators: 1: opening <strong> tag, 2: closing </strong> tag. */ echo wp_kses_post( sprintf( esc_html__( 'This demo requires the %1$sPremium%2$s version of the theme', 'demo-awesome' ), '<strong>', '</strong>' ) ); ?></span>
    243248                                    <a class="button button-primary demo-name-link-1"
    244249                                       target="_blank"
    … …  
    249254                                                        if ( ! Demo_Awesome_Admin::is_theme4press_theme() ) { ?>
    250255                                <p class="alert alert-info required-premium-text"><span
    251                                             class="mr-1"><?php echo Demo_Awesome_Admin::get_svg( 'info' ); ?></span><?php echo Demo_Awesome_Admin::is_theme4press_theme_message(); ?>
     256                                            class="mr-1"><?php echo wp_kses( Demo_Awesome_Admin::get_svg( 'info' ), Demo_Awesome_Admin::allowed_svg_tags() ); ?></span><?php echo wp_kses_post( Demo_Awesome_Admin::is_theme4press_theme_message() ); ?>
    252257                                </p>
    253258                                                        <?php } ?>
    … …  
    319324                                                                <?php esc_html_e( 'Minimum recommended theme version for this demo: ', 'demo-awesome' ); ?>
    320325                                <span class="theme-required-version"></span><br/>
    321                                 <h3><?php echo sprintf( esc_html__( 'Installed theme version: %s', 'demo-awesome' ), $demo_awesome_my_theme['Version'] ); ?></h3>
     326                                <h3><?php /* translators: %s: the installed theme version number. */ echo esc_html( sprintf( esc_html__( 'Installed theme version: %s', 'demo-awesome' ), $demo_awesome_my_theme->get('Version') ) ); ?></h3>
    322327                            </div>
    323328
    … …  
    327332                                                        if ( Demo_Awesome_Admin::is_free_theme() ) { ?>
    328333                                <p class="alert alert-info required-premium-text"><span
    329                                             class="mr-1"><?php echo Demo_Awesome_Admin::get_svg( 'info' ); ?></span><span><?php echo sprintf( esc_html__( 'This demo requires the %1$sPremium%2$s version of the theme', 'demo-awesome' ), '<strong>', '</strong>' ); ?></span>
     334                                            class="mr-1"><?php echo wp_kses( Demo_Awesome_Admin::get_svg( 'info' ), Demo_Awesome_Admin::allowed_svg_tags() ); ?></span><span><?php /* translators: 1: opening <strong> tag, 2: closing </strong> tag. */ echo wp_kses_post( sprintf( esc_html__( 'This demo requires the %1$sPremium%2$s version of the theme', 'demo-awesome' ), '<strong>', '</strong>' ) ); ?></span>
    330335                                    <a class="button button-primary demo-name-link-2"
    331336                                       target="_blank"
    … …  
    336341                                                        if ( ! Demo_Awesome_Admin::is_theme4press_theme() ) { ?>
    337342                                <p class="alert alert-info required-premium-text"><span
    338                                             class="mr-1"><?php echo wp_kses_post( Demo_Awesome_Admin::get_svg( 'info' )); ?></span>
     343                                            class="mr-1"><?php echo wp_kses( Demo_Awesome_Admin::get_svg( 'info' ), Demo_Awesome_Admin::allowed_svg_tags() ); ?></span>
    339344                                    <?php echo wp_kses_post(Demo_Awesome_Admin::is_theme4press_theme_message()); ?>
    340345                                </p>
  • demo-awesome/tags/1.0.6/inc/admin/importer/class-demo-awesome-customizer-importer.php

    r2158733 r3813524  
    3232                        global $wp_customize;
    3333
    34                         $data = maybe_unserialize( file_get_contents( $import_file ) );
     34                        // Security: Validate file path and content
     35                        if (!self::validate_import_file($import_file)) {
     36                                return new WP_Error( 'demo_awesome_customizer_import_file_error', esc_html__( 'Invalid import file.', 'demo-awesome' ) );
     37                        }
     38
     39                        $file_content = file_get_contents( $import_file );
     40                        if ($file_content === false) {
     41                                return new WP_Error( 'demo_awesome_customizer_import_file_error', esc_html__( 'Could not read import file.', 'demo-awesome' ) );
     42                        }
     43
     44                        // Security: Validate file content
     45                        if (!self::validate_file_content($file_content)) {
     46                                return new WP_Error( 'demo_awesome_customizer_import_content_error', esc_html__( 'Invalid file content detected.', 'demo-awesome' ) );
     47                        }
     48
     49                        // Security: never instantiate arbitrary PHP objects from the import file.
     50                        // Customizer data is always a serialized array, so unserialize with
     51                        // object instantiation disabled to prevent PHP object injection.
     52                        if ( is_serialized( $file_content ) ) {
     53                                $data = unserialize( trim( $file_content ), array( 'allowed_classes' => false ) );
     54                        } else {
     55                                $data = $file_content;
     56                        }
    3557
    3658                        // Data checks.
    … …  
    4567
    4668                        // Modify settings array.
    47                         $data = apply_filters( 'customizer_demo_import_settings', $data, $data_demo );
     69                        $data = apply_filters( 'demo_awesome_customizer_import_settings', $data, $data_demo );
    4870
    4971                        // Import custom options.
    … …  
    157179                                $id = media_handle_sideload( $file_array, 0 );
    158180
    159                                 // If error storing permanently, unlink.
     181                                // If error storing permanently, delete the temp file.
    160182                                if ( is_wp_error( $id ) ) {
    161                                         @unlink( $file_array['tmp_name'] );
     183                                        wp_delete_file( $file_array['tmp_name'] );
    162184
    163185                                        return $id;
    … …  
    175197                        return $data;
    176198                }
     199
     200                /**
     201                 * Validate import file path and permissions
     202                 * @since 1.0.3
     203                 */
     204                private static function validate_import_file($file_path) {
     205                        // Check if file exists
     206                        if (!file_exists($file_path)) {
     207                                return false;
     208                        }
     209
     210                        // Check if file is readable
     211                        if (!is_readable($file_path)) {
     212                                return false;
     213                        }
     214
     215                        // Check file extension
     216                        $allowed_extensions = array('dat');
     217                        $file_extension = strtolower(pathinfo($file_path, PATHINFO_EXTENSION));
     218                        if (!in_array($file_extension, $allowed_extensions)) {
     219                                return false;
     220                        }
     221
     222                        // Check file size (prevent DoS)
     223                        if (filesize($file_path) > 10 * 1024 * 1024) { // 10MB limit
     224                                return false;
     225                        }
     226
     227                        return true;
     228                }
     229
     230                /**
     231                 * Validate file content for security
     232                 * @since 1.0.3
     233                 */
     234                private static function validate_file_content($content) {
     235                        // Check for empty content
     236                        if (empty($content)) {
     237                                return false;
     238                        }
     239
     240                        // Check content length
     241                        if (strlen($content) > 10 * 1024 * 1024) { // 10MB limit
     242                                return false;
     243                        }
     244
     245                        // Check for malicious content
     246                        if (preg_match('/<\?php|<\?=|<script[^>]*>|javascript:|data:/i', $content)) {
     247                                return false;
     248                        }
     249
     250                        return true;
     251                }
    177252        }
    178253}
  • demo-awesome/tags/1.0.6/inc/admin/importer/class-demo-awesome-importer.php

    r3081092 r3813524  
    11<?php
    22/**
    3  * Demo Awesome importer based on WordPress importer core
     3 * Vendored copy of the official WordPress Importer (class-wp-import.php), version 0.8.3.
    44 *
    5  * @link       https://theme4press.com/demo-awesome-the-data-importer/
    6  * @since      1.0.0
    7  * @package    Demo Awesome
    8  * @author     Theme4Press
     5 * Upstream: https://wordpress.org/plugins/wordpress-importer/ (SVN tag 0.8.3)
     6 *
     7 * Local modifications (kept intentionally minimal):
     8 *  - Class names prefixed "Demo_Awesome_" to avoid collisions with the official plugin.
     9 *  - Text domain changed to "demo-awesome".
     10 *  - Direct-access guard added.
     11 *  - Backported the object-injection-safe maybe_unserialize() guard from importer 0.9.x
     12 *    and routed all WXR meta unserialization through it.
     13 *
     14 * This is third-party code maintained close to upstream; it is intentionally exempt
     15 * from this plugin's coding-standard checks (see phpcs:ignoreFile below).
     16 *
     17 * @package Demo Awesome
    918 */
    1019
    11 
     20// phpcs:ignoreFile
     21
     22// Exit if accessed directly.
     23if ( ! defined( 'ABSPATH' ) ) {
     24        exit;
     25}
     26
     27// The importer extends the WordPress core importer base class.
    1228if ( ! class_exists( 'WP_Importer' ) ) {
    1329        return;
    1430}
    1531
    16 // Display errors
    17 define( 'IMPORT_DEBUG', false );
    18 
    19 // Include WXR file parsers
    20 require dirname( __FILE__ ) . '/class-demo-awesome-parsers.php';
     32if ( ! defined( 'IMPORT_DEBUG' ) ) {
     33        define( 'IMPORT_DEBUG', false );
     34}
     35
     36// Load the WXR parsers (selector pulls in the SimpleXML/XML/Regex implementations).
     37require_once __DIR__ . '/parsers/class-demo-awesome-parser.php';
    2138
    2239/**
    23  * Demo Awesome importer class
     40 * WordPress Importer class for managing the import process of a WXR file
     41 *
     42 * @package WordPress
     43 * @subpackage Importer
    2444 */
    25 if ( ! class_exists( 'Demo_Awesome_Importer' ) ) {
    26         class Demo_Awesome_Importer extends WP_Importer {
    27                 var $max_wxr_version = 1.2; // max. supported WXR version
    28 
    29                 var $id; // WXR attachment ID
    30 
    31                 // information to import from WXR file
    32                 var $version;
    33                 var $authors = array();
    34                 var $posts = array();
    35                 var $terms = array();
    36                 var $categories = array();
    37                 var $tags = array();
    38                 var $base_url = '';
    39 
    40                 // mappings from old information to new
    41                 var $processed_authors = array();
    42                 var $author_mapping = array();
    43                 var $processed_terms = array();
    44                 var $processed_posts = array();
    45                 var $post_orphans = array();
    46                 var $processed_menu_items = array();
    47                 var $menu_item_orphans = array();
    48                 var $missing_menu_items = array();
    49 
    50                 var $fetch_attachments = false;
    51                 var $url_remap = array();
    52                 var $featured_images = array();
     45
     46/**
     47 * WordPress importer class.
     48 */
     49class Demo_Awesome_Importer extends WP_Importer {
     50        public $max_wxr_version = 1.2; // max. supported WXR version
     51
     52        public $id; // WXR attachment ID
     53
     54        // information to import from WXR file
     55        public $version;
     56        public $authors    = array();
     57        public $posts      = array();
     58        public $terms      = array();
     59        public $categories = array();
     60        public $tags       = array();
     61        public $base_url   = '';
     62
     63        // mappings from old information to new
     64        public $processed_authors    = array();
     65        public $author_mapping       = array();
     66        public $processed_terms      = array();
     67        public $processed_posts      = array();
     68        public $post_orphans         = array();
     69        public $processed_menu_items = array();
     70        public $menu_item_orphans    = array();
     71        public $missing_menu_items   = array();
     72
     73        public $fetch_attachments = false;
     74        public $url_remap         = array();
     75        public $featured_images   = array();
     76
     77        /**
     78         * Registered callback function for the WordPress Importer
     79         *
     80         * Manages the three separate stages of the WXR import process
     81         */
     82        public function dispatch() {
     83                $this->header();
     84
     85                $step = empty( $_GET['step'] ) ? 0 : (int) $_GET['step'];
     86                switch ( $step ) {
     87                        case 0:
     88                                $this->greet();
     89                                break;
     90                        case 1:
     91                                check_admin_referer( 'import-upload' );
     92                                if ( $this->handle_upload() ) {
     93                                        $this->import_options();
     94                                }
     95                                break;
     96                        case 2:
     97                                check_admin_referer( 'import-wordpress' );
     98                                $this->fetch_attachments = ( ! empty( $_POST['fetch_attachments'] ) && $this->allow_fetch_attachments() );
     99                                $this->id                = (int) $_POST['import_id'];
     100                                $file                    = get_attached_file( $this->id );
     101                                set_time_limit( 0 );
     102                                $this->import( $file );
     103                                break;
     104                }
     105
     106                $this->footer();
     107        }
     108
     109        /**
     110         * The main controller for the actual import stage.
     111         *
     112         * @param string $file Path to the WXR file for importing
     113         */
     114        public function import( $file ) {
     115                add_filter( 'import_post_meta_key', array( $this, 'is_valid_meta_key' ) );
     116                add_filter( 'http_request_timeout', array( &$this, 'bump_request_timeout' ) );
     117
     118                $this->import_start( $file );
     119
     120                $this->get_author_mapping();
     121
     122                wp_suspend_cache_invalidation( true );
     123                $this->process_categories();
     124                $this->process_tags();
     125                $this->process_terms();
     126                $this->process_posts();
     127                wp_suspend_cache_invalidation( false );
     128
     129                // update incorrect/missing information in the DB
     130                $this->backfill_parents();
     131                $this->backfill_attachment_urls();
     132                $this->remap_featured_images();
     133
     134                $this->import_end();
     135        }
     136
     137        /**
     138         * Parses the WXR file and prepares us for the task of processing parsed data
     139         *
     140         * @param string $file Path to the WXR file for importing
     141         */
     142        public function import_start( $file ) {
     143                if ( ! is_file( $file ) ) {
     144                        echo '<p><strong>' . __( 'Sorry, there has been an error.', 'demo-awesome' ) . '</strong><br />';
     145                        echo __( 'The file does not exist, please try again.', 'demo-awesome' ) . '</p>';
     146                        $this->footer();
     147                        die();
     148                }
     149
     150                $import_data = $this->parse( $file );
     151
     152                if ( is_wp_error( $import_data ) ) {
     153                        echo '<p><strong>' . __( 'Sorry, there has been an error.', 'demo-awesome' ) . '</strong><br />';
     154                        echo esc_html( $import_data->get_error_message() ) . '</p>';
     155                        $this->footer();
     156                        die();
     157                }
     158
     159                $this->version = $import_data['version'];
     160                $this->get_authors_from_import( $import_data );
     161                $this->posts      = $import_data['posts'];
     162                $this->terms      = $import_data['terms'];
     163                $this->categories = $import_data['categories'];
     164                $this->tags       = $import_data['tags'];
     165                $this->base_url   = esc_url( $import_data['base_url'] );
     166
     167                wp_defer_term_counting( true );
     168                wp_defer_comment_counting( true );
     169
     170                do_action( 'import_start' );
     171        }
     172
     173        /**
     174         * Performs post-import cleanup of files and the cache
     175         */
     176        public function import_end() {
     177                wp_import_cleanup( $this->id );
     178
     179                wp_cache_flush();
     180                foreach ( get_taxonomies() as $tax ) {
     181                        delete_option( "{$tax}_children" );
     182                        _get_term_hierarchy( $tax );
     183                }
     184
     185                wp_defer_term_counting( false );
     186                wp_defer_comment_counting( false );
     187
     188                echo '<p>' . __( 'All done.', 'demo-awesome' ) . ' <a href="' . admin_url() . '">' . __( 'Have fun!', 'demo-awesome' ) . '</a>' . '</p>';
     189                echo '<p>' . __( 'Remember to update the passwords and roles of imported users.', 'demo-awesome' ) . '</p>';
     190
     191                do_action( 'import_end' );
     192        }
     193
     194        /**
     195         * Handles the WXR upload and initial parsing of the file to prepare for
     196         * displaying author import options
     197         *
     198         * @return bool False if error uploading or invalid file, true otherwise
     199         */
     200        public function handle_upload() {
     201                $file = wp_import_handle_upload();
     202
     203                if ( isset( $file['error'] ) ) {
     204                        echo '<p><strong>' . __( 'Sorry, there has been an error.', 'demo-awesome' ) . '</strong><br />';
     205                        echo esc_html( $file['error'] ) . '</p>';
     206                        return false;
     207                } elseif ( ! file_exists( $file['file'] ) ) {
     208                        echo '<p><strong>' . __( 'Sorry, there has been an error.', 'demo-awesome' ) . '</strong><br />';
     209                        printf( __( 'The export file could not be found at <code>%s</code>. It is likely that this was caused by a permissions problem.', 'demo-awesome' ), esc_html( $file['file'] ) );
     210                        echo '</p>';
     211                        return false;
     212                }
     213
     214                $this->id    = (int) $file['id'];
     215                $import_data = $this->parse( $file['file'] );
     216                if ( is_wp_error( $import_data ) ) {
     217                        echo '<p><strong>' . __( 'Sorry, there has been an error.', 'demo-awesome' ) . '</strong><br />';
     218                        echo esc_html( $import_data->get_error_message() ) . '</p>';
     219                        return false;
     220                }
     221
     222                $this->version = $import_data['version'];
     223                if ( $this->version > $this->max_wxr_version ) {
     224                        echo '<div class="error"><p><strong>';
     225                        printf( __( 'This WXR file (version %s) may not be supported by this version of the importer. Please consider updating.', 'demo-awesome' ), esc_html( $import_data['version'] ) );
     226                        echo '</strong></p></div>';
     227                }
     228
     229                $this->get_authors_from_import( $import_data );
     230
     231                return true;
     232        }
     233
     234        /**
     235         * Retrieve authors from parsed WXR data
     236         *
     237         * Uses the provided author information from WXR 1.1 files
     238         * or extracts info from each post for WXR 1.0 files
     239         *
     240         * @param array $import_data Data returned by a WXR parser
     241         */
     242        public function get_authors_from_import( $import_data ) {
     243                if ( ! empty( $import_data['authors'] ) ) {
     244                        $this->authors = $import_data['authors'];
     245                        // no author information, grab it from the posts
     246                } else {
     247                        foreach ( $import_data['posts'] as $post ) {
     248                                $login = sanitize_user( $post['post_author'], true );
     249                                if ( empty( $login ) ) {
     250                                        printf( __( 'Failed to import author %s. Their posts will be attributed to the current user.', 'demo-awesome' ), esc_html( $post['post_author'] ) );
     251                                        echo '<br />';
     252                                        continue;
     253                                }
     254
     255                                if ( ! isset( $this->authors[ $login ] ) ) {
     256                                        $this->authors[ $login ] = array(
     257                                                'author_login'        => $login,
     258                                                'author_display_name' => $post['post_author'],
     259                                        );
     260                                }
     261                        }
     262                }
     263        }
     264
     265        /**
     266         * Display pre-import options, author importing/mapping and option to
     267         * fetch attachments
     268         */
     269        public function import_options() {
     270                $j = 0;
     271                // phpcs:disable Generic.WhiteSpace.ScopeIndent.Incorrect
     272                ?>
     273<form action="<?php echo admin_url( 'admin.php?import=wordpress&amp;step=2' ); ?>" method="post">
     274        <?php wp_nonce_field( 'import-wordpress' ); ?>
     275        <input type="hidden" name="import_id" value="<?php echo $this->id; ?>" />
     276
     277<?php if ( ! empty( $this->authors ) ) : ?>
     278        <h3><?php _e( 'Assign Authors', 'demo-awesome' ); ?></h3>
     279        <p><?php _e( 'To make it simpler for you to edit and save the imported content, you may want to reassign the author of the imported item to an existing user of this site, such as your primary administrator account.', 'demo-awesome' ); ?></p>
     280<?php if ( $this->allow_create_users() ) : ?>
     281        <p><?php printf( __( 'If a new user is created by WordPress, a new password will be randomly generated and the new user&#8217;s role will be set as %s. Manually changing the new user&#8217;s details will be necessary.', 'demo-awesome' ), esc_html( get_option( 'default_role' ) ) ); ?></p>
     282<?php endif; ?>
     283        <ol id="authors">
     284<?php foreach ( $this->authors as $author ) : ?>
     285                <li><?php $this->author_select( $j++, $author ); ?></li>
     286<?php endforeach; ?>
     287        </ol>
     288<?php endif; ?>
     289
     290<?php if ( $this->allow_fetch_attachments() ) : ?>
     291        <h3><?php _e( 'Import Attachments', 'demo-awesome' ); ?></h3>
     292        <p>
     293                <input type="checkbox" value="1" name="fetch_attachments" id="import-attachments" />
     294                <label for="import-attachments"><?php _e( 'Download and import file attachments', 'demo-awesome' ); ?></label>
     295        </p>
     296<?php endif; ?>
     297
     298        <p class="submit"><input type="submit" class="button" value="<?php esc_attr_e( 'Submit', 'demo-awesome' ); ?>" /></p>
     299</form>
     300                <?php
     301                // phpcs:enable Generic.WhiteSpace.ScopeIndent.Incorrect
     302        }
     303
     304        /**
     305         * Display import options for an individual author. That is, either create
     306         * a new user based on import info or map to an existing user
     307         *
     308         * @param int $n Index for each author in the form
     309         * @param array $author Author information, e.g. login, display name, email
     310         */
     311        public function author_select( $n, $author ) {
     312                _e( 'Import author:', 'demo-awesome' );
     313                echo ' <strong>' . esc_html( $author['author_display_name'] );
     314                if ( '1.0' != $this->version ) {
     315                        echo ' (' . esc_html( $author['author_login'] ) . ')';
     316                }
     317                echo '</strong><br />';
     318
     319                if ( '1.0' != $this->version ) {
     320                        echo '<div style="margin-left:18px">';
     321                }
     322
     323                $create_users = $this->allow_create_users();
     324                if ( $create_users ) {
     325                        echo '<label for="user_new_' . $n . '">';
     326                        if ( '1.0' != $this->version ) {
     327                                _e( 'or create new user with login name:', 'demo-awesome' );
     328                                $value = '';
     329                        } else {
     330                                _e( 'as a new user:', 'demo-awesome' );
     331                                $value = esc_attr( sanitize_user( $author['author_login'], true ) );
     332                        }
     333                        echo '</label>';
     334
     335                        echo ' <input type="text" id="user_new_' . $n . '" name="user_new[' . $n . ']" value="' . $value . '" /><br />';
     336                }
     337
     338                echo '<label for="imported_authors_' . $n . '">';
     339                if ( ! $create_users && '1.0' == $this->version ) {
     340                        _e( 'assign posts to an existing user:', 'demo-awesome' );
     341                } else {
     342                        _e( 'or assign posts to an existing user:', 'demo-awesome' );
     343                }
     344                echo '</label>';
     345
     346                echo ' ' . wp_dropdown_users(
     347                        array(
     348                                'name'            => "user_map[$n]",
     349                                'id'              => 'imported_authors_' . $n,
     350                                'multi'           => true,
     351                                'show_option_all' => __( '- Select -', 'demo-awesome' ),
     352                                'show'            => 'display_name_with_login',
     353                                'echo'            => 0,
     354                        )
     355                );
     356
     357                echo '<input type="hidden" name="imported_authors[' . $n . ']" value="' . esc_attr( $author['author_login'] ) . '" />';
     358
     359                if ( '1.0' != $this->version ) {
     360                        echo '</div>';
     361                }
     362        }
     363
     364        /**
     365         * Map old author logins to local user IDs based on decisions made
     366         * in import options form. Can map to an existing user, create a new user
     367         * or falls back to the current user in case of error with either of the previous
     368         */
     369        public function get_author_mapping() {
     370                if ( ! isset( $_POST['imported_authors'] ) ) {
     371                        return;
     372                }
     373
     374                $create_users = $this->allow_create_users();
     375
     376                foreach ( (array) $_POST['imported_authors'] as $i => $old_login ) {
     377                        // Multisite adds strtolower to sanitize_user. Need to sanitize here to stop breakage in process_posts.
     378                        $santized_old_login = sanitize_user( $old_login, true );
     379                        $old_id             = isset( $this->authors[ $old_login ]['author_id'] ) ? intval( $this->authors[ $old_login ]['author_id'] ) : false;
     380
     381                        if ( ! empty( $_POST['user_map'][ $i ] ) ) {
     382                                $user = get_userdata( intval( $_POST['user_map'][ $i ] ) );
     383                                if ( isset( $user->ID ) ) {
     384                                        if ( $old_id ) {
     385                                                $this->processed_authors[ $old_id ] = $user->ID;
     386                                        }
     387                                        $this->author_mapping[ $santized_old_login ] = $user->ID;
     388                                }
     389                        } elseif ( $create_users ) {
     390                                if ( ! empty( $_POST['user_new'][ $i ] ) ) {
     391                                        $user_id = wp_create_user( $_POST['user_new'][ $i ], wp_generate_password() );
     392                                } elseif ( '1.0' != $this->version ) {
     393                                        $user_data = array(
     394                                                'user_login'   => $old_login,
     395                                                'user_pass'    => wp_generate_password(),
     396                                                'user_email'   => isset( $this->authors[ $old_login ]['author_email'] ) ? $this->authors[ $old_login ]['author_email'] : '',
     397                                                'display_name' => $this->authors[ $old_login ]['author_display_name'],
     398                                                'first_name'   => isset( $this->authors[ $old_login ]['author_first_name'] ) ? $this->authors[ $old_login ]['author_first_name'] : '',
     399                                                'last_name'    => isset( $this->authors[ $old_login ]['author_last_name'] ) ? $this->authors[ $old_login ]['author_last_name'] : '',
     400                                        );
     401                                        $user_id   = wp_insert_user( $user_data );
     402                                }
     403
     404                                if ( ! is_wp_error( $user_id ) ) {
     405                                        if ( $old_id ) {
     406                                                $this->processed_authors[ $old_id ] = $user_id;
     407                                        }
     408                                        $this->author_mapping[ $santized_old_login ] = $user_id;
     409                                } else {
     410                                        printf( __( 'Failed to create new user for %s. Their posts will be attributed to the current user.', 'demo-awesome' ), esc_html( $this->authors[ $old_login ]['author_display_name'] ) );
     411                                        if ( defined( 'IMPORT_DEBUG' ) && IMPORT_DEBUG ) {
     412                                                echo ' ' . $user_id->get_error_message();
     413                                        }
     414                                        echo '<br />';
     415                                }
     416                        }
     417
     418                        // failsafe: if the user_id was invalid, default to the current user
     419                        if ( ! isset( $this->author_mapping[ $santized_old_login ] ) ) {
     420                                if ( $old_id ) {
     421                                        $this->processed_authors[ $old_id ] = (int) get_current_user_id();
     422                                }
     423                                $this->author_mapping[ $santized_old_login ] = (int) get_current_user_id();
     424                        }
     425                }
     426        }
     427
     428        /**
     429         * Create new categories based on import information
     430         *
     431         * Doesn't create a new category if its slug already exists
     432         */
     433        public function process_categories() {
     434                $this->categories = apply_filters( 'wp_import_categories', $this->categories );
     435
     436                if ( empty( $this->categories ) ) {
     437                        return;
     438                }
     439
     440                foreach ( $this->categories as $cat ) {
     441                        // if the category already exists leave it alone
     442                        $term_id = term_exists( $cat['category_nicename'], 'category' );
     443                        if ( $term_id ) {
     444                                if ( is_array( $term_id ) ) {
     445                                        $term_id = $term_id['term_id'];
     446                                }
     447                                if ( isset( $cat['term_id'] ) ) {
     448                                        $this->processed_terms[ intval( $cat['term_id'] ) ] = (int) $term_id;
     449                                }
     450                                continue;
     451                        }
     452
     453                        $parent      = empty( $cat['category_parent'] ) ? 0 : category_exists( $cat['category_parent'] );
     454                        $description = isset( $cat['category_description'] ) ? $cat['category_description'] : '';
     455
     456                        $data = array(
     457                                'category_nicename'    => $cat['category_nicename'],
     458                                'category_parent'      => $parent,
     459                                'cat_name'             => wp_slash( $cat['cat_name'] ),
     460                                'category_description' => wp_slash( $description ),
     461                        );
     462
     463                        $id = wp_insert_category( $data, true );
     464                        if ( ! is_wp_error( $id ) && $id > 0 ) {
     465                                if ( isset( $cat['term_id'] ) ) {
     466                                        $this->processed_terms[ intval( $cat['term_id'] ) ] = $id;
     467                                }
     468                        } else {
     469                                printf( __( 'Failed to import category %s', 'demo-awesome' ), esc_html( $cat['category_nicename'] ) );
     470                                if ( defined( 'IMPORT_DEBUG' ) && IMPORT_DEBUG ) {
     471                                        echo ': ' . $id->get_error_message();
     472                                }
     473                                echo '<br />';
     474                                continue;
     475                        }
     476
     477                        $this->process_termmeta( $cat, $id );
     478                }
     479
     480                unset( $this->categories );
     481        }
     482
     483        /**
     484         * Create new post tags based on import information
     485         *
     486         * Doesn't create a tag if its slug already exists
     487         */
     488        public function process_tags() {
     489                $this->tags = apply_filters( 'wp_import_tags', $this->tags );
     490
     491                if ( empty( $this->tags ) ) {
     492                        return;
     493                }
     494
     495                foreach ( $this->tags as $tag ) {
     496                        // if the tag already exists leave it alone
     497                        $term_id = term_exists( $tag['tag_slug'], 'post_tag' );
     498                        if ( $term_id ) {
     499                                if ( is_array( $term_id ) ) {
     500                                        $term_id = $term_id['term_id'];
     501                                }
     502                                if ( isset( $tag['term_id'] ) ) {
     503                                        $this->processed_terms[ intval( $tag['term_id'] ) ] = (int) $term_id;
     504                                }
     505                                continue;
     506                        }
     507
     508                        $description = isset( $tag['tag_description'] ) ? $tag['tag_description'] : '';
     509                        $args        = array(
     510                                'slug'        => $tag['tag_slug'],
     511                                'description' => wp_slash( $description ),
     512                        );
     513
     514                        $id = wp_insert_term( wp_slash( $tag['tag_name'] ), 'post_tag', $args );
     515                        if ( ! is_wp_error( $id ) ) {
     516                                if ( isset( $tag['term_id'] ) ) {
     517                                        $this->processed_terms[ intval( $tag['term_id'] ) ] = $id['term_id'];
     518                                }
     519                        } else {
     520                                printf( __( 'Failed to import post tag %s', 'demo-awesome' ), esc_html( $tag['tag_name'] ) );
     521                                if ( defined( 'IMPORT_DEBUG' ) && IMPORT_DEBUG ) {
     522                                        echo ': ' . $id->get_error_message();
     523                                }
     524                                echo '<br />';
     525                                continue;
     526                        }
     527
     528                        $this->process_termmeta( $tag, $id['term_id'] );
     529                }
     530
     531                unset( $this->tags );
     532        }
     533
     534        /**
     535         * Create new terms based on import information
     536         *
     537         * Doesn't create a term its slug already exists
     538         */
     539        public function process_terms() {
     540                $this->terms = apply_filters( 'wp_import_terms', $this->terms );
     541
     542                if ( empty( $this->terms ) ) {
     543                        return;
     544                }
     545
     546                foreach ( $this->terms as $term ) {
     547                        // if the term already exists in the correct taxonomy leave it alone
     548                        $term_id = term_exists( $term['slug'], $term['term_taxonomy'] );
     549                        if ( $term_id ) {
     550                                if ( is_array( $term_id ) ) {
     551                                        $term_id = $term_id['term_id'];
     552                                }
     553                                if ( isset( $term['term_id'] ) ) {
     554                                        $this->processed_terms[ intval( $term['term_id'] ) ] = (int) $term_id;
     555                                }
     556                                continue;
     557                        }
     558
     559                        if ( empty( $term['term_parent'] ) ) {
     560                                $parent = 0;
     561                        } else {
     562                                $parent = term_exists( $term['term_parent'], $term['term_taxonomy'] );
     563                                if ( is_array( $parent ) ) {
     564                                        $parent = $parent['term_id'];
     565                                }
     566                        }
     567
     568                        $description = isset( $term['term_description'] ) ? $term['term_description'] : '';
     569                        $args        = array(
     570                                'slug'        => $term['slug'],
     571                                'description' => wp_slash( $description ),
     572                                'parent'      => (int) $parent,
     573                        );
     574
     575                        $id = wp_insert_term( wp_slash( $term['term_name'] ), $term['term_taxonomy'], $args );
     576                        if ( ! is_wp_error( $id ) ) {
     577                                if ( isset( $term['term_id'] ) ) {
     578                                        $this->processed_terms[ intval( $term['term_id'] ) ] = $id['term_id'];
     579                                }
     580                        } else {
     581                                printf( __( 'Failed to import %1$s %2$s', 'demo-awesome' ), esc_html( $term['term_taxonomy'] ), esc_html( $term['term_name'] ) );
     582                                if ( defined( 'IMPORT_DEBUG' ) && IMPORT_DEBUG ) {
     583                                        echo ': ' . $id->get_error_message();
     584                                }
     585                                echo '<br />';
     586                                continue;
     587                        }
     588
     589                        $this->process_termmeta( $term, $id['term_id'] );
     590                }
     591
     592                unset( $this->terms );
     593        }
     594
     595        /**
     596         * Add metadata to imported term.
     597         *
     598         * @since 0.6.2
     599         *
     600         * @param array $term    Term data from WXR import.
     601         * @param int   $term_id ID of the newly created term.
     602         */
     603        protected function process_termmeta( $term, $term_id ) {
     604                if ( ! isset( $term['termmeta'] ) ) {
     605                        $term['termmeta'] = array();
     606                }
    53607
    54608                /**
    55                  * Registered callback function for the WordPress Importer
     609                 * Filters the metadata attached to an imported term.
    56610                 *
    57                  * Manages the three separate stages of the WXR import process
     611                 * @since 0.6.2
     612                 *
     613                 * @param array $termmeta Array of term meta.
     614                 * @param int   $term_id  ID of the newly created term.
     615                 * @param array $term     Term data from the WXR import.
    58616                 */
    59                 function dispatch() {
    60                         $this->header();
    61 
    62                         $step = empty( $_GET['step'] ) ? 0 : (int) $_GET['step'];
    63                         switch ( $step ) {
    64                                 case 0:
    65                                         $this->greet();
    66                                         break;
    67                                 case 1:
    68                                         check_admin_referer( 'import-upload' );
    69                                         if ( $this->handle_upload() ) {
    70                                                 $this->import_options();
     617                $term['termmeta'] = apply_filters( 'wp_import_term_meta', $term['termmeta'], $term_id, $term );
     618
     619                if ( empty( $term['termmeta'] ) ) {
     620                        return;
     621                }
     622
     623                foreach ( $term['termmeta'] as $meta ) {
     624                        /**
     625                         * Filters the meta key for an imported piece of term meta.
     626                         *
     627                         * @since 0.6.2
     628                         *
     629                         * @param string $meta_key Meta key.
     630                         * @param int    $term_id  ID of the newly created term.
     631                         * @param array  $term     Term data from the WXR import.
     632                         */
     633                        $key = apply_filters( 'import_term_meta_key', $meta['key'], $term_id, $term );
     634                        if ( ! $key ) {
     635                                continue;
     636                        }
     637
     638                        // Export gets meta straight from the DB so could have a serialized string
     639                        $value = $this->maybe_unserialize( $meta['value'] );
     640
     641                        add_term_meta( $term_id, wp_slash( $key ), wp_slash_strings_only( $value ) );
     642
     643                        /**
     644                         * Fires after term meta is imported.
     645                         *
     646                         * @since 0.6.2
     647                         *
     648                         * @param int    $term_id ID of the newly created term.
     649                         * @param string $key     Meta key.
     650                         * @param mixed  $value   Meta value.
     651                         */
     652                        do_action( 'import_term_meta', $term_id, $key, $value );
     653                }
     654        }
     655
     656        /**
     657         * Create new posts based on import information
     658         *
     659         * Posts marked as having a parent which doesn't exist will become top level items.
     660         * Doesn't create a new post if: the post type doesn't exist, the given post ID
     661         * is already noted as imported or a post with the same title and date already exists.
     662         * Note that new/updated terms, comments and meta are imported for the last of the above.
     663         */
     664        public function process_posts() {
     665                $this->posts = apply_filters( 'wp_import_posts', $this->posts );
     666
     667                foreach ( $this->posts as $post ) {
     668                        $post = apply_filters( 'wp_import_post_data_raw', $post );
     669
     670                        if ( ! post_type_exists( $post['post_type'] ) ) {
     671                                printf(
     672                                        __( 'Failed to import &#8220;%1$s&#8221;: Invalid post type %2$s', 'demo-awesome' ),
     673                                        esc_html( $post['post_title'] ),
     674                                        esc_html( $post['post_type'] )
     675                                );
     676                                echo '<br />';
     677                                do_action( 'wp_import_post_exists', $post );
     678                                continue;
     679                        }
     680
     681                        if ( isset( $this->processed_posts[ $post['post_id'] ] ) && ! empty( $post['post_id'] ) ) {
     682                                continue;
     683                        }
     684
     685                        if ( 'auto-draft' == $post['status'] ) {
     686                                continue;
     687                        }
     688
     689                        if ( 'nav_menu_item' == $post['post_type'] ) {
     690                                $this->process_menu_item( $post );
     691                                continue;
     692                        }
     693
     694                        $post_type_object = get_post_type_object( $post['post_type'] );
     695
     696                        $post_exists = post_exists( $post['post_title'], '', $post['post_date'], $post['post_type'] );
     697
     698                        /**
     699                        * Filter ID of the existing post corresponding to post currently importing.
     700                        *
     701                        * Return 0 to force the post to be imported. Filter the ID to be something else
     702                        * to override which existing post is mapped to the imported post.
     703                        *
     704                        * @see post_exists()
     705                        * @since 0.6.2
     706                        *
     707                        * @param int   $post_exists  Post ID, or 0 if post did not exist.
     708                        * @param array $post         The post array to be inserted.
     709                        */
     710                        $post_exists = apply_filters( 'wp_import_existing_post', $post_exists, $post );
     711
     712                        if ( $post_exists && get_post_type( $post_exists ) == $post['post_type'] ) {
     713                                printf( __( '%1$s &#8220;%2$s&#8221; already exists.', 'demo-awesome' ), $post_type_object->labels->singular_name, esc_html( $post['post_title'] ) );
     714                                echo '<br />';
     715                                $comment_post_id = $post_exists;
     716                                $post_id         = $post_exists;
     717                                $this->processed_posts[ intval( $post['post_id'] ) ] = intval( $post_exists );
     718                        } else {
     719                                $post_parent = (int) $post['post_parent'];
     720                                if ( $post_parent ) {
     721                                        // if we already know the parent, map it to the new local ID
     722                                        if ( isset( $this->processed_posts[ $post_parent ] ) ) {
     723                                                $post_parent = $this->processed_posts[ $post_parent ];
     724                                                // otherwise record the parent for later
     725                                        } else {
     726                                                $this->post_orphans[ intval( $post['post_id'] ) ] = $post_parent;
     727                                                $post_parent                                      = 0;
    71728                                        }
    72                                         break;
    73                                 case 2:
    74                                         check_admin_referer( 'import-wordpress' );
    75                                         $this->fetch_attachments = ( ! empty( $_POST['fetch_attachments'] ) && $this->allow_fetch_attachments() );
    76                                         $this->id                = (int) $_POST['import_id'];
    77                                         $file                    = get_attached_file( $this->id );
    78                                         set_time_limit( 0 );
    79                                         $this->import( $file );
    80                                         break;
    81                         }
    82 
    83                         $this->footer();
    84                 }
    85 
    86                 /**
    87                  * The main controller for the actual import stage.
    88                  *
    89                  * @param string $file Path to the WXR file for importing
    90                  */
    91                 function import( $file ) {
    92                         require dirname( __FILE__ ) . '/class-demo-awesome-parsers.php';
    93 
    94                         add_filter( 'import_post_meta_key', array( $this, 'is_valid_meta_key' ) );
    95                         add_filter( 'http_request_timeout', array( &$this, 'bump_request_timeout' ) );
    96 
    97                         $this->import_start( $file );
    98 
    99                         $this->get_author_mapping();
    100 
    101                         wp_suspend_cache_invalidation( true );
    102                         $this->process_categories();
    103                         $this->process_tags();
    104                         $this->process_terms();
    105                         $this->process_posts();
    106                         wp_suspend_cache_invalidation( false );
    107 
    108                         // update incorrect/missing information in the DB
    109                         $this->backfill_parents();
    110                         $this->backfill_attachment_urls();
    111                         $this->remap_featured_images();
    112 
    113                         $this->import_end();
    114                 }
    115 
    116                 /**
    117                  * Parses the WXR file and prepares us for the task of processing parsed data
    118                  *
    119                  * @param string $file Path to the WXR file for importing
    120                  */
    121                 function import_start( $file ) {
    122                         if ( ! is_file( $file ) ) {
    123                                 echo '<p><strong>' . esc_html__( 'Sorry, there has been an error.', 'demo-awesome' ) . '</strong><br />';
    124                                 echo esc_html__( 'The file does not exist, please try again.', 'demo-awesome' ) . '</p>';
    125                                 $this->footer();
    126                                 die();
    127                         }
    128 
    129                         $import_data = $this->parse( $file );
    130 
    131                         if ( is_wp_error( $import_data ) ) {
    132                                 echo '<p><strong>' . esc_html__( 'Sorry, there has been an error.', 'demo-awesome' ) . '</strong><br />';
    133                                 echo esc_html( $import_data->get_error_message() ) . '</p>';
    134                                 $this->footer();
    135                                 die();
    136                         }
    137 
    138                         $this->version = $import_data['version'];
    139                         $this->get_authors_from_import( $import_data );
    140                         $this->posts      = $import_data['posts'];
    141                         $this->terms      = $import_data['terms'];
    142                         $this->categories = $import_data['categories'];
    143                         $this->tags       = $import_data['tags'];
    144                         $this->base_url   = esc_url( $import_data['base_url'] );
    145 
    146                         wp_defer_term_counting( true );
    147                         wp_defer_comment_counting( true );
    148                         do_action( 'import_start' );
    149                 }
    150 
    151                 /**
    152                  * Performs post-import cleanup of files and the cache
    153                  */
    154                 function import_end() {
    155                         wp_import_cleanup( $this->id );
    156 
    157                         wp_cache_flush();
    158                         foreach ( get_taxonomies() as $tax ) {
    159                                 delete_option( "{$tax}_children" );
    160                                 _get_term_hierarchy( $tax );
    161                         }
    162 
    163                         wp_defer_term_counting( false );
    164                         wp_defer_comment_counting( false );
    165 
    166                         echo '<p>' . esc_html__( 'All done.', 'demo-awesome' ) . ' <a href="' . admin_url() . '">' . esc_html__( 'Have fun!', 'demo-awesome' ) . '</a>' . '</p>';
    167                         echo '<p>' . esc_html__( 'Remember to update the passwords and roles of imported users.', 'demo-awesome' ) . '</p>';
    168 
    169                         do_action( 'import_end' );
    170                 }
    171 
    172                 /**
    173                  * Handles the WXR upload and initial parsing of the file to prepare for
    174                  * displaying author import options
    175                  *
    176                  * @return bool False if error uploading or invalid file, true otherwise
    177                  */
    178                 function handle_upload() {
    179                         $file = wp_import_handle_upload();
    180 
    181                         if ( isset( $file['error'] ) ) {
    182                                 echo '<p><strong>' . esc_html__( 'Sorry, there has been an error.', 'demo-awesome' ) . '</strong><br />';
    183                                 echo esc_html( $file['error'] ) . '</p>';
    184 
    185                                 return false;
    186                         } else if ( ! file_exists( $file['file'] ) ) {
    187                                 echo '<p><strong>' . esc_html__( 'Sorry, there has been an error.', 'demo-awesome' ) . '</strong><br />';
    188                                 printf( esc_html__( 'The export file could not be found at <code>%s</code>. It is likely that this was caused by a permissions problem.', 'demo-awesome' ), esc_html( $file['file'] ) );
    189                                 echo '</p>';
    190 
    191                                 return false;
    192                         }
    193 
    194                         $this->id    = (int) $file['id'];
    195                         $import_data = $this->parse( $file['file'] );
    196                         if ( is_wp_error( $import_data ) ) {
    197                                 echo '<p><strong>' . esc_html__( 'Sorry, there has been an error.', 'demo-awesome' ) . '</strong><br />';
    198                                 echo esc_html( $import_data->get_error_message() ) . '</p>';
    199 
    200                                 return false;
    201                         }
    202 
    203                         $this->version = $import_data['version'];
    204                         if ( $this->version > $this->max_wxr_version ) {
    205                                 echo '<div class="error"><p><strong>';
    206                                 printf( esc_html__( 'This WXR file (version %s) may not be supported by this version of the importer. Please consider updating.', 'demo-awesome' ), esc_html( $import_data['version'] ) );
    207                                 echo '</strong></p></div>';
    208                         }
    209 
    210                         $this->get_authors_from_import( $import_data );
    211 
    212                         return true;
    213                 }
    214 
    215                 /**
    216                  * Retrieve authors from parsed WXR data
    217                  *
    218                  * Uses the provided author information from WXR 1.1 files
    219                  * or extracts info from each post for WXR 1.0 files
    220                  *
    221                  * @param array $import_data Data returned by a WXR parser
    222                  */
    223                 function get_authors_from_import( $import_data ) {
    224                         if ( ! empty( $import_data['authors'] ) ) {
    225                                 $this->authors = $import_data['authors'];
    226                                 // no author information, grab it from the posts
    227                         } else {
    228                                 foreach ( $import_data['posts'] as $post ) {
    229                                         $login = sanitize_user( $post['post_author'], true );
    230                                         if ( empty( $login ) ) {
    231                                                 printf( esc_html__( 'Failed to import author %s. Their posts will be attributed to the current user.', 'demo-awesome' ), esc_html( $post['post_author'] ) );
    232                                                 echo '<br />';
    233                                                 continue;
     729                                }
     730
     731                                // map the post author
     732                                $author = sanitize_user( $post['post_author'], true );
     733                                if ( isset( $this->author_mapping[ $author ] ) ) {
     734                                        $author = $this->author_mapping[ $author ];
     735                                } else {
     736                                        $author = (int) get_current_user_id();
     737                                }
     738
     739                                $postdata = array(
     740                                        'import_id'      => $post['post_id'],
     741                                        'post_author'    => $author,
     742                                        'post_date'      => $post['post_date'],
     743                                        'post_date_gmt'  => $post['post_date_gmt'],
     744                                        'post_content'   => $post['post_content'],
     745                                        'post_excerpt'   => $post['post_excerpt'],
     746                                        'post_title'     => $post['post_title'],
     747                                        'post_status'    => $post['status'],
     748                                        'post_name'      => $post['post_name'],
     749                                        'comment_status' => $post['comment_status'],
     750                                        'ping_status'    => $post['ping_status'],
     751                                        'guid'           => $post['guid'],
     752                                        'post_parent'    => $post_parent,
     753                                        'menu_order'     => $post['menu_order'],
     754                                        'post_type'      => $post['post_type'],
     755                                        'post_password'  => $post['post_password'],
     756                                );
     757
     758                                $original_post_id = $post['post_id'];
     759                                $postdata         = apply_filters( 'wp_import_post_data_processed', $postdata, $post );
     760
     761                                $postdata = wp_slash( $postdata );
     762
     763                                if ( 'attachment' == $postdata['post_type'] ) {
     764                                        $remote_url = ! empty( $post['attachment_url'] ) ? $post['attachment_url'] : $post['guid'];
     765
     766                                        // try to use _wp_attached file for upload folder placement to ensure the same location as the export site
     767                                        // e.g. location is 2003/05/image.jpg but the attachment post_date is 2010/09, see media_handle_upload()
     768                                        $postdata['upload_date'] = $post['post_date'];
     769                                        if ( isset( $post['postmeta'] ) ) {
     770                                                foreach ( $post['postmeta'] as $meta ) {
     771                                                        if ( '_wp_attached_file' == $meta['key'] ) {
     772                                                                if ( preg_match( '%^[0-9]{4}/[0-9]{2}%', $meta['value'], $matches ) ) {
     773                                                                        $postdata['upload_date'] = $matches[0];
     774                                                                }
     775                                                                break;
     776                                                        }
     777                                                }
    234778                                        }
    235779
    236                                         if ( ! isset( $this->authors[ $login ] ) ) {
    237                                                 $this->authors[ $login ] = array(
    238                                                         'author_login'        => $login,
    239                                                         'author_display_name' => $post['post_author']
    240                                                 );
    241                                         }
    242                                 }
    243                         }
    244                 }
    245 
    246                 /**
    247                  * Display pre-import options, author importing/mapping and option to
    248                  * fetch attachments
    249                  */
    250                 function import_options() {
    251                         $j = 0;
    252                         ?>
    253             <form action="<?php echo esc_url(admin_url( 'admin.php?import=wordpress&amp;step=2' )); ?>" method="post">
    254                                 <?php wp_nonce_field( 'import-wordpress' ); ?>
    255                 <input type="hidden" name="import_id" value="<?php echo  esc_attr($this->id); ?>"/>
    256 
    257                                 <?php if ( ! empty( $this->authors ) ) : ?>
    258                     <h3><?php esc_html_e( 'Assign Authors', 'demo-awesome' ); ?></h3>
    259                     <p><?php esc_html_e( 'To make it easier for you to edit and save the imported content, you may want to reassign the author of the imported item to an existing user of this site. For example, you may want to import all the entries as <code>admin</code>s entries.', 'demo-awesome' ); ?></p>
    260                                         <?php if ( $this->allow_create_users() ) : ?>
    261                         <p><?php printf( esc_html__( 'If a new user is created by WordPress, a new password will be randomly generated and the new user&#8217;s role will be set as %s. Manually changing the new user&#8217;s details will be necessary.', 'demo-awesome' ), esc_html( get_option( 'default_role' ) ) ); ?></p>
    262                                         <?php endif; ?>
    263                     <ol id="authors">
    264                                                 <?php foreach ( $this->authors as $author ) : ?>
    265                             <li><?php $this->author_select( $j ++, $author ); ?></li>
    266                                                 <?php endforeach; ?>
    267                     </ol>
    268                                 <?php endif; ?>
    269 
    270                                 <?php if ( $this->allow_fetch_attachments() ) : ?>
    271                     <h3><?php esc_html_e( 'Import Attachments', 'demo-awesome' ); ?></h3>
    272                     <p>
    273                         <input type="checkbox" value="1" name="fetch_attachments" id="import-attachments"/>
    274                         <label for="import-attachments"><?php esc_html_e( 'Download and import file attachments', 'demo-awesome' ); ?></label>
    275                     </p>
    276                                 <?php endif; ?>
    277 
    278                 <p class="submit"><input type="submit" class="button"
    279                                          value="<?php esc_attr_e( 'Submit', 'demo-awesome' ); ?>"/></p>
    280             </form>
    281                         <?php
    282                 }
    283 
    284                 /**
    285                  * Display import options for an individual author. That is, either create
    286                  * a new user based on import info or map to an existing user
    287                  *
    288                  * @param int $n Index for each author in the form
    289                  * @param array $author Author information, e.g. login, display name, email
    290                  */
    291                 function author_select( $n, $author ) {
    292             esc_html_e( 'Import author:', 'demo-awesome' );
    293                         echo ' <strong>' . esc_html( $author['author_display_name'] );
    294                         if ( $this->version != '1.0' ) {
    295                                 echo ' (' . esc_html( $author['author_login'] ) . ')';
    296                         }
    297                         echo '</strong><br />';
    298 
    299                         if ( $this->version != '1.0' ) {
    300                                 echo '<div style="margin-left:18px">';
    301                         }
    302 
    303                         $create_users = $this->allow_create_users();
    304                         if ( $create_users ) {
    305                                 if ( $this->version != '1.0' ) {
    306                                         _e( 'or create new user with login name:', 'demo-awesome' );
    307                                         $value = '';
     780                                        $comment_post_id = $this->process_attachment( $postdata, $remote_url );
     781                                        $post_id         = $comment_post_id;
    308782                                } else {
    309                                         _e( 'as a new user:', 'demo-awesome' );
    310                                         $value = esc_attr( sanitize_user( $author['author_login'], true ) );
    311                                 }
    312 
    313                                 echo ' <input type="text" name="user_new[' . $n . ']" value="' . $value . '" /><br />';
    314                         }
    315 
    316                         if ( ! $create_users && $this->version == '1.0' ) {
    317                                 _e( 'assign posts to an existing user:', 'demo-awesome' );
    318                         } else {
    319                                 _e( 'or assign posts to an existing user:', 'demo-awesome' );
    320                         }
    321                         wp_dropdown_users( array(
    322                                 'name'            => "user_map[$n]",
    323                                 'multi'           => true,
    324                                 'show_option_all' => esc_html__( '- Select -', 'demo-awesome' )
    325                         ) );
    326                         echo '<input type="hidden" name="imported_authors[' . $n . ']" value="' . esc_attr( $author['author_login'] ) . '" />';
    327 
    328                         if ( $this->version != '1.0' ) {
    329                                 echo '</div>';
    330                         }
    331                 }
    332 
    333                 /**
    334                  * Map old author logins to local user IDs based on decisions made
    335                  * in import options form. Can map to an existing user, create a new user
    336                  * or falls back to the current user in case of error with either of the previous
    337                  */
    338                 function get_author_mapping() {
    339                         if ( ! isset( $_POST['imported_authors'] ) ) {
    340                                 return;
    341                         }
    342 
    343                         $create_users = $this->allow_create_users();
    344 
    345                         foreach ( (array) $_POST['imported_authors'] as $i => $old_login ) {
    346                                 // Multisite adds strtolower to sanitize_user. Need to sanitize here to stop breakage in process_posts.
    347                                 $santized_old_login = sanitize_user( $old_login, true );
    348                                 $old_id             = isset( $this->authors[ $old_login ]['author_id'] ) ? intval( $this->authors[ $old_login ]['author_id'] ) : false;
    349 
    350                                 if ( ! empty( $_POST['user_map'][ $i ] ) ) {
    351                                         $user = get_userdata( intval( $_POST['user_map'][ $i ] ) );
    352                                         if ( isset( $user->ID ) ) {
    353                                                 if ( $old_id ) {
    354                                                         $this->processed_authors[ $old_id ] = $user->ID;
    355                                                 }
    356                                                 $this->author_mapping[ $santized_old_login ] = $user->ID;
    357                                         }
    358                                 } else if ( $create_users ) {
    359                                         if ( ! empty( $_POST['user_new'][ $i ] ) ) {
    360                                                 $user_id = wp_create_user( $_POST['user_new'][ $i ], wp_generate_password() );
    361                                         } else if ( $this->version != '1.0' ) {
    362                                                 $user_data = array(
    363                                                         'user_login'   => $old_login,
    364                                                         'user_pass'    => wp_generate_password(),
    365                                                         'user_email'   => isset( $this->authors[ $old_login ]['author_email'] ) ? $this->authors[ $old_login ]['author_email'] : '',
    366                                                         'display_name' => $this->authors[ $old_login ]['author_display_name'],
    367                                                         'first_name'   => isset( $this->authors[ $old_login ]['author_first_name'] ) ? $this->authors[ $old_login ]['author_first_name'] : '',
    368                                                         'last_name'    => isset( $this->authors[ $old_login ]['author_last_name'] ) ? $this->authors[ $old_login ]['author_last_name'] : '',
    369                                                 );
    370                                                 $user_id   = wp_insert_user( $user_data );
    371                                         }
    372 
    373                                         if ( ! is_wp_error( $user_id ) ) {
    374                                                 if ( $old_id ) {
    375                                                         $this->processed_authors[ $old_id ] = $user_id;
    376                                                 }
    377                                                 $this->author_mapping[ $santized_old_login ] = $user_id;
    378                                         } else {
    379                                                 printf( esc_html__( 'Failed to create new user for %s. Their posts will be attributed to the current user.', 'demo-awesome' ), esc_html( $this->authors[ $old_login ]['author_display_name'] ) );
    380                                                 if ( defined( 'IMPORT_DEBUG' ) && IMPORT_DEBUG ) {
    381                                                         echo ' ' . esc_html($user_id->get_error_message());
    382                                                 }
    383                                                 echo '<br />';
    384                                         }
    385                                 }
    386 
    387                                 // failsafe: if the user_id was invalid, default to the current user
    388                                 if ( ! isset( $this->author_mapping[ $santized_old_login ] ) ) {
    389                                         if ( $old_id ) {
    390                                                 $this->processed_authors[ $old_id ] = (int) get_current_user_id();
    391                                         }
    392                                         $this->author_mapping[ $santized_old_login ] = (int) get_current_user_id();
    393                                 }
    394                         }
    395                 }
    396 
    397                 /**
    398                  * Create new categories based on import information
    399                  *
    400                  * Doesn't create a new category if its slug already exists
    401                  */
    402                 function process_categories() {
    403                         $this->categories = apply_filters( 'wp_import_categories', $this->categories );
    404 
    405                         if ( empty( $this->categories ) ) {
    406                                 return;
    407                         }
    408 
    409                         foreach ( $this->categories as $cat ) {
    410                                 // if the category already exists leave it alone
    411                                 $term_id = term_exists( $cat['category_nicename'], 'category' );
    412                                 if ( $term_id ) {
    413                                         if ( is_array( $term_id ) ) {
    414                                                 $term_id = $term_id['term_id'];
    415                                         }
    416                                         if ( isset( $cat['term_id'] ) ) {
    417                                                 $this->processed_terms[ intval( $cat['term_id'] ) ] = (int) $term_id;
    418                                         }
    419                                         continue;
    420                                 }
    421 
    422                                 $category_parent      = empty( $cat['category_parent'] ) ? 0 : category_exists( $cat['category_parent'] );
    423                                 $category_description = isset( $cat['category_description'] ) ? $cat['category_description'] : '';
    424                                 $catarr               = array(
    425                                         'category_nicename'    => $cat['category_nicename'],
    426                                         'category_parent'      => $category_parent,
    427                                         'cat_name'             => $cat['cat_name'],
    428                                         'category_description' => $category_description
    429                                 );
    430                                 $catarr               = wp_slash( $catarr );
    431 
    432                                 $id = wp_insert_category( $catarr );
    433                                 if ( ! is_wp_error( $id ) ) {
    434                                         if ( isset( $cat['term_id'] ) ) {
    435                                                 $this->processed_terms[ intval( $cat['term_id'] ) ] = $id;
    436                                         }
    437                                 } else {
    438                                         printf( esc_html__( 'Failed to import category %s', 'demo-awesome' ), esc_html( $cat['category_nicename'] ) );
     783                                        $comment_post_id = wp_insert_post( $postdata, true );
     784                                        $post_id         = $comment_post_id;
     785                                        do_action( 'wp_import_insert_post', $post_id, $original_post_id, $postdata, $post );
     786                                }
     787
     788                                if ( is_wp_error( $post_id ) ) {
     789                                        printf(
     790                                                __( 'Failed to import %1$s &#8220;%2$s&#8221;', 'demo-awesome' ),
     791                                                $post_type_object->labels->singular_name,
     792                                                esc_html( $post['post_title'] )
     793                                        );
    439794                                        if ( defined( 'IMPORT_DEBUG' ) && IMPORT_DEBUG ) {
    440                                                 echo ': ' .  esc_html($id->get_error_message());
     795                                                echo ': ' . $post_id->get_error_message();
    441796                                        }
    442797                                        echo '<br />';
    … …  
    444799                                }
    445800
    446                                 $this->process_termmeta( $cat, $id['term_id'] );
    447                         }
    448 
    449                         unset( $this->categories );
    450                 }
    451 
    452                 /**
    453                  * Create new post tags based on import information
    454                  *
    455                  * Doesn't create a tag if its slug already exists
    456                  */
    457                 function process_tags() {
    458                         $this->tags = apply_filters( 'wp_import_tags', $this->tags );
    459 
    460                         if ( empty( $this->tags ) ) {
    461                                 return;
    462                         }
    463 
    464                         foreach ( $this->tags as $tag ) {
    465                                 // if the tag already exists leave it alone
    466                                 $term_id = term_exists( $tag['tag_slug'], 'post_tag' );
    467                                 if ( $term_id ) {
    468                                         if ( is_array( $term_id ) ) {
    469                                                 $term_id = $term_id['term_id'];
    470                                         }
    471                                         if ( isset( $tag['term_id'] ) ) {
    472                                                 $this->processed_terms[ intval( $tag['term_id'] ) ] = (int) $term_id;
    473                                         }
    474                                         continue;
    475                                 }
    476 
    477                                 $tag      = wp_slash( $tag );
    478                                 $tag_desc = isset( $tag['tag_description'] ) ? $tag['tag_description'] : '';
    479                                 $tagarr   = array( 'slug' => $tag['tag_slug'], 'description' => $tag_desc );
    480 
    481                                 $id = wp_insert_term( $tag['tag_name'], 'post_tag', $tagarr );
    482                                 if ( ! is_wp_error( $id ) ) {
    483                                         if ( isset( $tag['term_id'] ) ) {
    484                                                 $this->processed_terms[ intval( $tag['term_id'] ) ] = $id['term_id'];
    485                                         }
    486                                 } else {
    487                                         printf( esc_html__( 'Failed to import post tag %s', 'demo-awesome' ), esc_html( $tag['tag_name'] ) );
    488                                         if ( defined( 'IMPORT_DEBUG' ) && IMPORT_DEBUG ) {
    489                                                 echo ': ' . esc_html($id->get_error_message());
    490                                         }
    491                                         echo '<br />';
    492                                         continue;
    493                                 }
    494 
    495                                 $this->process_termmeta( $tag, $id['term_id'] );
    496                         }
    497 
    498                         unset( $this->tags );
    499                 }
    500 
    501                 /**
    502                  * Create new terms based on import information
    503                  *
    504                  * Doesn't create a term its slug already exists
    505                  */
    506                 function process_terms() {
    507                         $this->terms = apply_filters( 'wp_import_terms', $this->terms );
    508 
    509                         if ( empty( $this->terms ) ) {
    510                                 return;
    511                         }
    512 
    513                         foreach ( $this->terms as $term ) {
    514                                 // if the term already exists in the correct taxonomy leave it alone
    515                                 $term_id = term_exists( $term['slug'], $term['term_taxonomy'] );
    516                                 if ( $term_id ) {
    517                                         if ( is_array( $term_id ) ) {
    518                                                 $term_id = $term_id['term_id'];
    519                                         }
    520                                         if ( isset( $term['term_id'] ) ) {
    521                                                 $this->processed_terms[ intval( $term['term_id'] ) ] = (int) $term_id;
    522                                         }
    523                                         continue;
    524                                 }
    525 
    526                                 if ( empty( $term['term_parent'] ) ) {
    527                                         $parent = 0;
    528                                 } else {
    529                                         $parent = term_exists( $term['term_parent'], $term['term_taxonomy'] );
    530                                         if ( is_array( $parent ) ) {
    531                                                 $parent = $parent['term_id'];
    532                                         }
    533                                 }
    534                                 $term        = wp_slash( $term );
    535                                 $description = isset( $term['term_description'] ) ? $term['term_description'] : '';
    536                                 $termarr     = array(
    537                                         'slug'        => $term['slug'],
    538                                         'description' => $description,
    539                                         'parent'      => intval( $parent )
    540                                 );
    541 
    542                                 $id = wp_insert_term( $term['term_name'], $term['term_taxonomy'], $termarr );
    543                                 if ( ! is_wp_error( $id ) ) {
    544                                         if ( isset( $term['term_id'] ) ) {
    545                                                 $this->processed_terms[ intval( $term['term_id'] ) ] = $id['term_id'];
    546                                         }
    547                                 } else {
    548                                         printf( esc_html__( 'Failed to import %s %s', 'demo-awesome' ), esc_html( $term['term_taxonomy'] ), esc_html( $term['term_name'] ) );
    549                                         if ( defined( 'IMPORT_DEBUG' ) && IMPORT_DEBUG ) {
    550                                                 echo ': ' . $id->get_error_message();
    551                                         }
    552                                         echo '<br />';
    553                                         continue;
    554                                 }
    555 
    556                                 $this->process_termmeta( $term, $id['term_id'] );
    557                         }
    558 
    559                         unset( $this->terms );
    560                 }
    561 
    562                 /**
    563                  * Add metadata to imported term.
    564                  *
    565                  * @since 0.6.2
    566                  *
    567                  * @param array $term Term data from WXR import.
    568                  * @param int $term_id ID of the newly created term.
    569                  */
    570                 protected function process_termmeta( $term, $term_id ) {
    571                         if ( ! isset( $term['termmeta'] ) ) {
    572                                 $term['termmeta'] = array();
    573                         }
    574 
    575                         /**
    576                          * Filters the metadata attached to an imported term.
    577                          *
    578                          * @since 0.6.2
    579                          *
    580                          * @param array $termmeta Array of term meta.
    581                          * @param int $term_id ID of the newly created term.
    582                          * @param array $term Term data from the WXR import.
    583                          */
    584                         $term['termmeta'] = apply_filters( 'wp_import_term_meta', $term['termmeta'], $term_id, $term );
    585 
    586                         if ( empty( $term['termmeta'] ) ) {
    587                                 return;
    588                         }
    589 
    590                         foreach ( $term['termmeta'] as $meta ) {
    591                                 /**
    592                                  * Filters the meta key for an imported piece of term meta.
    593                                  *
    594                                  * @since 0.6.2
    595                                  *
    596                                  * @param string $meta_key Meta key.
    597                                  * @param int $term_id ID of the newly created term.
    598                                  * @param array $term Term data from the WXR import.
    599                                  */
    600                                 $key = apply_filters( 'import_term_meta_key', $meta['key'], $term_id, $term );
    601                                 if ( ! $key ) {
    602                                         continue;
    603                                 }
    604 
    605                                 // Export gets meta straight from the DB so could have a serialized string
    606                                 $value = maybe_unserialize( $meta['value'] );
    607 
    608                                 add_term_meta( $term_id, $key, $value );
    609 
    610                                 /**
    611                                  * Fires after term meta is imported.
    612                                  *
    613                                  * @since 0.6.2
    614                                  *
    615                                  * @param int $term_id ID of the newly created term.
    616                                  * @param string $key Meta key.
    617                                  * @param mixed $value Meta value.
    618                                  */
    619                                 do_action( 'import_term_meta', $term_id, $key, $value );
    620                         }
    621                 }
    622 
    623                 /**
    624                  * Create new posts based on import information
    625                  *
    626                  * Posts marked as having a parent which doesn't exist will become top level items.
    627                  * Doesn't create a new post if: the post type doesn't exist, the given post ID
    628                  * is already noted as imported or a post with the same title and date already exists.
    629                  * Note that new/updated terms, comments and meta are imported for the last of the above.
    630                  */
    631                 function process_posts() {
    632                         $this->posts = apply_filters( 'wp_import_posts', $this->posts );
    633 
    634                         foreach ( $this->posts as $post ) {
    635                                 $post = apply_filters( 'wp_import_post_data_raw', $post );
    636 
    637                                 if ( ! post_type_exists( $post['post_type'] ) ) {
    638                                         printf( esc_html__( 'Failed to import &#8220;%s&#8221;: Invalid post type %s', 'demo-awesome' ),
    639                                                 esc_html( $post['post_title'] ), esc_html( $post['post_type'] ) );
    640                                         echo '<br />';
    641                                         do_action( 'wp_import_post_exists', $post );
    642                                         continue;
    643                                 }
    644 
    645                                 if ( isset( $this->processed_posts[ $post['post_id'] ] ) && ! empty( $post['post_id'] ) ) {
    646                                         continue;
    647                                 }
    648 
    649                                 if ( $post['status'] == 'auto-draft' ) {
    650                                         continue;
    651                                 }
    652 
    653                                 if ( 'nav_menu_item' == $post['post_type'] ) {
    654                                         $this->process_menu_item( $post );
    655                                         continue;
    656                                 }
    657 
    658                                 $post_type_object = get_post_type_object( $post['post_type'] );
    659 
    660                                 $post_exists = post_exists( $post['post_title'], '', $post['post_date'] );
    661 
    662                                 /**
    663                                  * Filter ID of the existing post corresponding to post currently importing.
    664                                  *
    665                                  * Return 0 to force the post to be imported. Filter the ID to be something else
    666                                  * to override which existing post is mapped to the imported post.
    667                                  *
    668                                  * @see post_exists()
    669                                  * @since 0.6.2
    670                                  *
    671                                  * @param int $post_exists Post ID, or 0 if post did not exist.
    672                                  * @param array $post The post array to be inserted.
    673                                  */
    674                                 $post_exists = apply_filters( 'wp_import_existing_post', $post_exists, $post );
    675 
    676                                 if ( $post_exists && get_post_type( $post_exists ) == $post['post_type'] ) {
    677                                         printf( esc_html__( '%s &#8220;%s&#8221; already exists.', 'demo-awesome' ), $post_type_object->labels->singular_name, esc_html( $post['post_title'] ) );
    678                                         echo '<br />';
    679                                         $comment_post_ID                                     = $post_id = $post_exists;
    680                                         $this->processed_posts[ intval( $post['post_id'] ) ] = intval( $post_exists );
    681                                 } else {
    682                                         $post_parent = (int) $post['post_parent'];
    683                                         if ( $post_parent ) {
    684                                                 // if we already know the parent, map it to the new local ID
    685                                                 if ( isset( $this->processed_posts[ $post_parent ] ) ) {
    686                                                         $post_parent = $this->processed_posts[ $post_parent ];
    687                                                         // otherwise record the parent for later
     801                                if ( 1 == $post['is_sticky'] ) {
     802                                        stick_post( $post_id );
     803                                }
     804                        }
     805
     806                        // map pre-import ID to local ID
     807                        $this->processed_posts[ intval( $post['post_id'] ) ] = (int) $post_id;
     808
     809                        if ( ! isset( $post['terms'] ) ) {
     810                                $post['terms'] = array();
     811                        }
     812
     813                        $post['terms'] = apply_filters( 'wp_import_post_terms', $post['terms'], $post_id, $post );
     814
     815                        // add categories, tags and other terms
     816                        if ( ! empty( $post['terms'] ) ) {
     817                                $terms_to_set = array();
     818                                foreach ( $post['terms'] as $term ) {
     819                                        // back compat with WXR 1.0 map 'tag' to 'post_tag'
     820                                        $taxonomy    = ( 'tag' == $term['domain'] ) ? 'post_tag' : $term['domain'];
     821                                        $term_exists = term_exists( $term['slug'], $taxonomy );
     822                                        $term_id     = is_array( $term_exists ) ? $term_exists['term_id'] : $term_exists;
     823                                        if ( ! $term_id ) {
     824                                                $t = wp_insert_term( $term['name'], $taxonomy, array( 'slug' => $term['slug'] ) );
     825                                                if ( ! is_wp_error( $t ) ) {
     826                                                        $term_id = $t['term_id'];
     827                                                        do_action( 'wp_import_insert_term', $t, $term, $post_id, $post );
    688828                                                } else {
    689                                                         $this->post_orphans[ intval( $post['post_id'] ) ] = $post_parent;
    690                                                         $post_parent                                      = 0;
     829                                                        printf( __( 'Failed to import %1$s %2$s', 'demo-awesome' ), esc_html( $taxonomy ), esc_html( $term['name'] ) );
     830                                                        if ( defined( 'IMPORT_DEBUG' ) && IMPORT_DEBUG ) {
     831                                                                echo ': ' . $t->get_error_message();
     832                                                        }
     833                                                        echo '<br />';
     834                                                        do_action( 'wp_import_insert_term_failed', $t, $term, $post_id, $post );
     835                                                        continue;
    691836                                                }
    692837                                        }
    693 
    694                                         // map the post author
    695                                         $author = sanitize_user( $post['post_author'], true );
    696                                         if ( isset( $this->author_mapping[ $author ] ) ) {
    697                                                 $author = $this->author_mapping[ $author ];
    698                                         } else {
    699                                                 $author = (int) get_current_user_id();
     838                                        $terms_to_set[ $taxonomy ][] = intval( $term_id );
     839                                }
     840
     841                                foreach ( $terms_to_set as $tax => $ids ) {
     842                                        $tt_ids = wp_set_post_terms( $post_id, $ids, $tax );
     843                                        do_action( 'wp_import_set_post_terms', $tt_ids, $ids, $tax, $post_id, $post );
     844                                }
     845                                unset( $post['terms'], $terms_to_set );
     846                        }
     847
     848                        if ( ! isset( $post['comments'] ) ) {
     849                                $post['comments'] = array();
     850                        }
     851
     852                        $post['comments'] = apply_filters( 'wp_import_post_comments', $post['comments'], $post_id, $post );
     853
     854                        // add/update comments
     855                        if ( ! empty( $post['comments'] ) ) {
     856                                $num_comments      = 0;
     857                                $inserted_comments = array();
     858                                foreach ( $post['comments'] as $comment ) {
     859                                        $comment_id                                    = $comment['comment_id'];
     860                                        $newcomments[ $comment_id ]['comment_post_ID'] = $comment_post_id;
     861                                        $newcomments[ $comment_id ]['comment_author']  = $comment['comment_author'];
     862                                        $newcomments[ $comment_id ]['comment_author_email'] = $comment['comment_author_email'];
     863                                        $newcomments[ $comment_id ]['comment_author_IP']    = $comment['comment_author_IP'];
     864                                        $newcomments[ $comment_id ]['comment_author_url']   = $comment['comment_author_url'];
     865                                        $newcomments[ $comment_id ]['comment_date']         = $comment['comment_date'];
     866                                        $newcomments[ $comment_id ]['comment_date_gmt']     = $comment['comment_date_gmt'];
     867                                        $newcomments[ $comment_id ]['comment_content']      = $comment['comment_content'];
     868                                        $newcomments[ $comment_id ]['comment_approved']     = $comment['comment_approved'];
     869                                        $newcomments[ $comment_id ]['comment_type']         = $comment['comment_type'];
     870                                        $newcomments[ $comment_id ]['comment_parent']       = $comment['comment_parent'];
     871                                        $newcomments[ $comment_id ]['commentmeta']          = isset( $comment['commentmeta'] ) ? $comment['commentmeta'] : array();
     872                                        if ( isset( $this->processed_authors[ $comment['comment_user_id'] ] ) ) {
     873                                                $newcomments[ $comment_id ]['user_id'] = $this->processed_authors[ $comment['comment_user_id'] ];
    700874                                        }
    701 
    702                                         $postdata = array(
    703                                                 'import_id'      => $post['post_id'],
    704                                                 'post_author'    => $author,
    705                                                 'post_date'      => $post['post_date'],
    706                                                 'post_date_gmt'  => $post['post_date_gmt'],
    707                                                 'post_content'   => $post['post_content'],
    708                                                 'post_excerpt'   => $post['post_excerpt'],
    709                                                 'post_title'     => $post['post_title'],
    710                                                 'post_status'    => $post['status'],
    711                                                 'post_name'      => $post['post_name'],
    712                                                 'comment_status' => $post['comment_status'],
    713                                                 'ping_status'    => $post['ping_status'],
    714                                                 'guid'           => $post['guid'],
    715                                                 'post_parent'    => $post_parent,
    716                                                 'menu_order'     => $post['menu_order'],
    717                                                 'post_type'      => $post['post_type'],
    718                                                 'post_password'  => $post['post_password']
    719                                         );
    720 
    721                                         $original_post_ID = $post['post_id'];
    722                                         $postdata         = apply_filters( 'wp_import_post_data_processed', $postdata, $post );
    723 
    724                                         $postdata = wp_slash( $postdata );
    725 
    726                                         if ( 'attachment' == $postdata['post_type'] ) {
    727                                                 $remote_url = ! empty( $post['attachment_url'] ) ? $post['attachment_url'] : $post['guid'];
    728 
    729                                                 // try to use _wp_attached file for upload folder placement to ensure the same location as the export site
    730                                                 // e.g. location is 2003/05/image.jpg but the attachment post_date is 2010/09, see media_handle_upload()
    731                                                 $postdata['upload_date'] = $post['post_date'];
    732                                                 if ( isset( $post['postmeta'] ) ) {
    733                                                         foreach ( $post['postmeta'] as $meta ) {
    734                                                                 if ( $meta['key'] == '_wp_attached_file' ) {
    735                                                                         if ( preg_match( '%^[0-9]{4}/[0-9]{2}%', $meta['value'], $matches ) ) {
    736                                                                                 $postdata['upload_date'] = $matches[0];
    737                                                                         }
    738                                                                         break;
    739                                                                 }
    740                                                         }
     875                                }
     876                                ksort( $newcomments );
     877
     878                                foreach ( $newcomments as $key => $comment ) {
     879                                        // if this is a new post we can skip the comment_exists() check
     880                                        if ( ! $post_exists || ! comment_exists( $comment['comment_author'], $comment['comment_date'] ) ) {
     881                                                if ( isset( $inserted_comments[ $comment['comment_parent'] ] ) ) {
     882                                                        $comment['comment_parent'] = $inserted_comments[ $comment['comment_parent'] ];
    741883                                                }
    742884
    743                                                 $comment_post_ID = $post_id = $this->process_attachment( $postdata, $remote_url );
    744                                         } else {
    745                                                 $comment_post_ID = $post_id = wp_insert_post( $postdata, true );
    746                                                 do_action( 'wp_import_insert_post', $post_id, $original_post_ID, $postdata, $post );
     885                                                $comment_data = wp_slash( $comment );
     886                                                unset( $comment_data['commentmeta'] ); // Handled separately, wp_insert_comment() also expects `comment_meta`.
     887                                                $comment_data = wp_filter_comment( $comment_data );
     888
     889                                                $inserted_comments[ $key ] = wp_insert_comment( $comment_data );
     890
     891                                                do_action( 'wp_import_insert_comment', $inserted_comments[ $key ], $comment, $comment_post_id, $post );
     892
     893                                                foreach ( $comment['commentmeta'] as $meta ) {
     894                                                        $value = $this->maybe_unserialize( $meta['value'] );
     895
     896                                                        add_comment_meta( $inserted_comments[ $key ], wp_slash( $meta['key'] ), wp_slash_strings_only( $value ) );
     897                                                }
     898
     899                                                ++$num_comments;
    747900                                        }
    748 
    749                                         if ( is_wp_error( $post_id ) ) {
    750                                                 printf( esc_html__( 'Failed to import %s &#8220;%s&#8221;', 'demo-awesome' ),
    751                                                         $post_type_object->labels->singular_name, esc_html( $post['post_title'] ) );
    752                                                 if ( defined( 'IMPORT_DEBUG' ) && IMPORT_DEBUG ) {
    753                                                         echo ': ' . esc_html( $post_id->get_error_message());
    754                                                 }
    755                                                 echo '<br />';
    756                                                 continue;
    757                                         }
    758 
    759                                         if ( $post['is_sticky'] == 1 ) {
    760                                                 stick_post( $post_id );
    761                                         }
    762                                 }
    763 
    764                                 // map pre-import ID to local ID
    765                                 $this->processed_posts[ intval( $post['post_id'] ) ] = (int) $post_id;
    766 
    767                                 if ( ! isset( $post['terms'] ) ) {
    768                                         $post['terms'] = array();
    769                                 }
    770 
    771                                 $post['terms'] = apply_filters( 'wp_import_post_terms', $post['terms'], $post_id, $post );
    772 
    773                                 // add categories, tags and other terms
    774                                 if ( ! empty( $post['terms'] ) ) {
    775                                         $terms_to_set = array();
    776                                         foreach ( $post['terms'] as $term ) {
    777                                                 // back compat with WXR 1.0 map 'tag' to 'post_tag'
    778                                                 $taxonomy    = ( 'tag' == $term['domain'] ) ? 'post_tag' : $term['domain'];
    779                                                 $term_exists = term_exists( $term['slug'], $taxonomy );
    780                                                 $term_id     = is_array( $term_exists ) ? $term_exists['term_id'] : $term_exists;
    781                                                 if ( ! $term_id ) {
    782                                                         $t = wp_insert_term( $term['name'], $taxonomy, array( 'slug' => $term['slug'] ) );
    783                                                         if ( ! is_wp_error( $t ) ) {
    784                                                                 $term_id = $t['term_id'];
    785                                                                 do_action( 'wp_import_insert_term', $t, $term, $post_id, $post );
    786                                                         } else {
    787                                                                 printf( esc_html__( 'Failed to import %s %s', 'demo-awesome' ), esc_html( $taxonomy ), esc_html( $term['name'] ) );
    788                                                                 if ( defined( 'IMPORT_DEBUG' ) && IMPORT_DEBUG ) {
    789                                                                         echo ': ' . $t->get_error_message();
    790                                                                 }
    791                                                                 echo '<br />';
    792                                                                 do_action( 'wp_import_insert_term_failed', $t, $term, $post_id, $post );
    793                                                                 continue;
    794                                                         }
    795                                                 }
    796                                                 $terms_to_set[ $taxonomy ][] = intval( $term_id );
    797                                         }
    798 
    799                                         foreach ( $terms_to_set as $tax => $ids ) {
    800                                                 $tt_ids = wp_set_post_terms( $post_id, $ids, $tax );
    801                                                 do_action( 'wp_import_set_post_terms', $tt_ids, $ids, $tax, $post_id, $post );
    802                                         }
    803                                         unset( $post['terms'], $terms_to_set );
    804                                 }
    805 
    806                                 if ( ! isset( $post['comments'] ) ) {
    807                                         $post['comments'] = array();
    808                                 }
    809 
    810                                 $post['comments'] = apply_filters( 'wp_import_post_comments', $post['comments'], $post_id, $post );
    811 
    812                                 // add/update comments
    813                                 if ( ! empty( $post['comments'] ) ) {
    814                                         $num_comments      = 0;
    815                                         $inserted_comments = array();
    816                                         foreach ( $post['comments'] as $comment ) {
    817                                                 $comment_id                                         = $comment['comment_id'];
    818                                                 $newcomments[ $comment_id ]['comment_post_ID']      = $comment_post_ID;
    819                                                 $newcomments[ $comment_id ]['comment_author']       = $comment['comment_author'];
    820                                                 $newcomments[ $comment_id ]['comment_author_email'] = $comment['comment_author_email'];
    821                                                 $newcomments[ $comment_id ]['comment_author_IP']    = $comment['comment_author_IP'];
    822                                                 $newcomments[ $comment_id ]['comment_author_url']   = $comment['comment_author_url'];
    823                                                 $newcomments[ $comment_id ]['comment_date']         = $comment['comment_date'];
    824                                                 $newcomments[ $comment_id ]['comment_date_gmt']     = $comment['comment_date_gmt'];
    825                                                 $newcomments[ $comment_id ]['comment_content']      = $comment['comment_content'];
    826                                                 $newcomments[ $comment_id ]['comment_approved']     = $comment['comment_approved'];
    827                                                 $newcomments[ $comment_id ]['comment_type']         = $comment['comment_type'];
    828                                                 $newcomments[ $comment_id ]['comment_parent']       = $comment['comment_parent'];
    829                                                 $newcomments[ $comment_id ]['commentmeta']          = isset( $comment['commentmeta'] ) ? $comment['commentmeta'] : array();
    830                                                 if ( isset( $this->processed_authors[ $comment['comment_user_id'] ] ) ) {
    831                                                         $newcomments[ $comment_id ]['user_id'] = $this->processed_authors[ $comment['comment_user_id'] ];
     901                                }
     902                                unset( $newcomments, $inserted_comments, $post['comments'] );
     903                        }
     904
     905                        if ( ! isset( $post['postmeta'] ) ) {
     906                                $post['postmeta'] = array();
     907                        }
     908
     909                        $post['postmeta'] = apply_filters( 'wp_import_post_meta', $post['postmeta'], $post_id, $post );
     910
     911                        // add/update post meta
     912                        if ( ! empty( $post['postmeta'] ) ) {
     913                                foreach ( $post['postmeta'] as $meta ) {
     914                                        $key   = apply_filters( 'import_post_meta_key', $meta['key'], $post_id, $post );
     915                                        $value = false;
     916
     917                                        if ( '_edit_last' == $key ) {
     918                                                if ( isset( $this->processed_authors[ intval( $meta['value'] ) ] ) ) {
     919                                                        $value = $this->processed_authors[ intval( $meta['value'] ) ];
     920                                                } else {
     921                                                        $key = false;
    832922                                                }
    833923                                        }
    834                                         ksort( $newcomments );
    835 
    836                                         foreach ( $newcomments as $key => $comment ) {
    837                                                 // if this is a new post we can skip the comment_exists() check
    838                                                 if ( ! $post_exists || ! comment_exists( $comment['comment_author'], $comment['comment_date'] ) ) {
    839                                                         if ( isset( $inserted_comments[ $comment['comment_parent'] ] ) ) {
    840                                                                 $comment['comment_parent'] = $inserted_comments[ $comment['comment_parent'] ];
    841                                                         }
    842                                                         $comment                   = wp_slash( $comment );
    843                                                         $comment                   = wp_filter_comment( $comment );
    844                                                         $inserted_comments[ $key ] = wp_insert_comment( $comment );
    845                                                         do_action( 'wp_import_insert_comment', $inserted_comments[ $key ], $comment, $comment_post_ID, $post );
    846 
    847                                                         foreach ( $comment['commentmeta'] as $meta ) {
    848                                                                 $value = maybe_unserialize( $meta['value'] );
    849                                                                 add_comment_meta( $inserted_comments[ $key ], $meta['key'], $value );
    850                                                         }
    851 
    852                                                         $num_comments ++;
     924
     925                                        if ( $key ) {
     926                                                // export gets meta straight from the DB so could have a serialized string
     927                                                if ( ! $value ) {
     928                                                        $value = $this->maybe_unserialize( $meta['value'] );
     929                                                }
     930
     931                                                add_post_meta( $post_id, wp_slash( $key ), wp_slash_strings_only( $value ) );
     932
     933                                                do_action( 'import_post_meta', $post_id, $key, $value );
     934
     935                                                // if the post has a featured image, take note of this in case of remap
     936                                                if ( '_thumbnail_id' == $key ) {
     937                                                        $this->featured_images[ $post_id ] = (int) $value;
    853938                                                }
    854939                                        }
    855                                         unset( $newcomments, $inserted_comments, $post['comments'] );
    856                                 }
    857 
    858                                 if ( ! isset( $post['postmeta'] ) ) {
    859                                         $post['postmeta'] = array();
    860                                 }
    861 
    862                                 $post['postmeta'] = apply_filters( 'wp_import_post_meta', $post['postmeta'], $post_id, $post );
    863 
    864                                 // add/update post meta
    865                                 if ( ! empty( $post['postmeta'] ) ) {
    866                                         foreach ( $post['postmeta'] as $meta ) {
    867                                                 $key   = apply_filters( 'import_post_meta_key', $meta['key'], $post_id, $post );
    868                                                 $value = false;
    869 
    870                                                 if ( '_edit_last' == $key ) {
    871                                                         if ( isset( $this->processed_authors[ intval( $meta['value'] ) ] ) ) {
    872                                                                 $value = $this->processed_authors[ intval( $meta['value'] ) ];
    873                                                         } else {
    874                                                                 $key = false;
    875                                                         }
    876                                                 }
    877 
    878                                                 if ( $key ) {
    879                                                         // export gets meta straight from the DB so could have a serialized string
    880                                                         if ( ! $value ) {
    881                                                                 $value = maybe_unserialize( $meta['value'] );
    882                                                         }
    883 
    884                                                         add_post_meta( $post_id, $key, $value );
    885                                                         do_action( 'import_post_meta', $post_id, $key, $value );
    886 
    887                                                         // if the post has a featured image, take note of this in case of remap
    888                                                         if ( '_thumbnail_id' == $key ) {
    889                                                                 $this->featured_images[ $post_id ] = (int) $value;
    890                                                         }
    891                                                 }
    892                                         }
    893                                 }
    894                         }
    895 
    896                         unset( $this->posts );
    897                 }
    898 
    899                 /**
    900                  * Attempt to create a new menu item from import data
    901                  *
    902                  * Fails for draft, orphaned menu items and those without an associated nav_menu
    903                  * or an invalid nav_menu term. If the post type or term object which the menu item
    904                  * represents doesn't exist then the menu item will not be imported (waits until the
    905                  * end of the import to retry again before discarding).
    906                  *
    907                  * @param array $item Menu item details from WXR file
    908                  */
    909                 function process_menu_item( $item ) {
    910                         // skip draft, orphaned menu items
    911                         if ( 'draft' == $item['status'] ) {
    912                                 return;
    913                         }
    914 
    915                         $menu_slug = false;
    916                         if ( isset( $item['terms'] ) ) {
    917                                 // loop through terms, assume first nav_menu term is correct menu
    918                                 foreach ( $item['terms'] as $term ) {
    919                                         if ( 'nav_menu' == $term['domain'] ) {
    920                                                 $menu_slug = $term['slug'];
    921                                                 break;
    922                                         }
    923                                 }
    924                         }
    925 
    926                         // no nav_menu term associated with this menu item
    927                         if ( ! $menu_slug ) {
    928                                 _e( 'Menu item skipped due to missing menu slug', 'demo-awesome' );
    929                                 echo '<br />';
    930 
    931                                 return;
    932                         }
    933 
    934                         $menu_id = term_exists( $menu_slug, 'nav_menu' );
    935                         if ( ! $menu_id ) {
    936                                 printf( esc_html__( 'Menu item skipped due to invalid menu slug: %s', 'demo-awesome' ), esc_html( $menu_slug ) );
    937                                 echo '<br />';
    938 
    939                                 return;
    940                         } else {
    941                                 $menu_id = is_array( $menu_id ) ? $menu_id['term_id'] : $menu_id;
    942                         }
    943                         foreach ( $item['postmeta'] as $meta ) {
    944                                 if ( version_compare( PHP_VERSION, '7.0.0' ) >= 0 ) {
    945                                         ${$meta['key']} = $meta['value'];
    946                                 } else {
    947                                         $$meta['key'] = $meta['value'];
    948                                 }
    949                         }
    950 
    951                         if ( 'taxonomy' == $_menu_item_type && isset( $this->processed_terms[ intval( $_menu_item_object_id ) ] ) ) {
    952                                 $_menu_item_object_id = $this->processed_terms[ intval( $_menu_item_object_id ) ];     
    953                         } else if ( 'post_type' == $_menu_item_type && isset( $this->processed_posts[ intval( $_menu_item_object_id ) ] ) ) {
    954                                 $_menu_item_object_id = $this->processed_posts[ intval( $_menu_item_object_id ) ];
    955                         } else if ( 'custom' != $_menu_item_type ) {
    956                                 // associated object is missing or not imported yet, we'll retry later
    957                                 $this->missing_menu_items[] = $item;
    958 
    959                                 return;
    960                         }
    961 
    962                         if ( isset( $this->processed_menu_items[ intval( $_menu_item_menu_item_parent ) ] ) ) {
    963                                 $_menu_item_menu_item_parent = $this->processed_menu_items[ intval( $_menu_item_menu_item_parent ) ];
    964                         } else if ( $_menu_item_menu_item_parent ) {
    965                                 $this->menu_item_orphans[ intval( $item['post_id'] ) ] = (int) $_menu_item_menu_item_parent;
    966                                 $_menu_item_menu_item_parent                           = 0;
    967                         }
    968 
    969                         // wp_update_nav_menu_item expects CSS classes as a space separated string
    970                         $_menu_item_classes = maybe_unserialize( $_menu_item_classes );
    971                         if ( is_array( $_menu_item_classes ) ) {
    972                                 $_menu_item_classes = implode( ' ', $_menu_item_classes );
    973                         }
    974 
    975                         $args = array(
    976                                 'menu-item-object-id'   => $_menu_item_object_id,
    977                                 'menu-item-object'      => $_menu_item_object,
    978                                 'menu-item-parent-id'   => $_menu_item_menu_item_parent,
    979                                 'menu-item-position'    => intval( $item['menu_order'] ),
    980                                 'menu-item-type'        => $_menu_item_type,
    981                                 'menu-item-title'       => $item['post_title'],
    982                                 'menu-item-url'         => $_menu_item_url,
    983                                 'menu-item-description' => $item['post_content'],
    984                                 'menu-item-attr-title'  => $item['post_excerpt'],
    985                                 'menu-item-target'      => $_menu_item_target,
    986                                 'menu-item-classes'     => $_menu_item_classes,
    987                                 'menu-item-xfn'         => $_menu_item_xfn,
    988                                 'menu-item-status'      => $item['status']
     940                                }
     941                        }
     942                }
     943
     944                unset( $this->posts );
     945        }
     946
     947        /**
     948         * Attempt to create a new menu item from import data
     949         *
     950         * Fails for draft, orphaned menu items and those without an associated nav_menu
     951         * or an invalid nav_menu term. If the post type or term object which the menu item
     952         * represents doesn't exist then the menu item will not be imported (waits until the
     953         * end of the import to retry again before discarding).
     954         *
     955         * @param array $item Menu item details from WXR file
     956         */
     957        public function process_menu_item( $item ) {
     958                // skip draft, orphaned menu items
     959                if ( 'draft' == $item['status'] ) {
     960                        return;
     961                }
     962
     963                $menu_slug = false;
     964                if ( isset( $item['terms'] ) ) {
     965                        // loop through terms, assume first nav_menu term is correct menu
     966                        foreach ( $item['terms'] as $term ) {
     967                                if ( 'nav_menu' == $term['domain'] ) {
     968                                        $menu_slug = $term['slug'];
     969                                        break;
     970                                }
     971                        }
     972                }
     973
     974                // no nav_menu term associated with this menu item
     975                if ( ! $menu_slug ) {
     976                        _e( 'Menu item skipped due to missing menu slug', 'demo-awesome' );
     977                        echo '<br />';
     978                        return;
     979                }
     980
     981                $menu_id = term_exists( $menu_slug, 'nav_menu' );
     982                if ( ! $menu_id ) {
     983                        printf( __( 'Menu item skipped due to invalid menu slug: %s', 'demo-awesome' ), esc_html( $menu_slug ) );
     984                        echo '<br />';
     985                        return;
     986                } else {
     987                        $menu_id = is_array( $menu_id ) ? $menu_id['term_id'] : $menu_id;
     988                }
     989
     990                foreach ( $item['postmeta'] as $meta ) {
     991                        ${$meta['key']} = $meta['value'];
     992                }
     993
     994                if ( 'taxonomy' == $_menu_item_type && isset( $this->processed_terms[ intval( $_menu_item_object_id ) ] ) ) {
     995                        $_menu_item_object_id = $this->processed_terms[ intval( $_menu_item_object_id ) ];
     996                } elseif ( 'post_type' == $_menu_item_type && isset( $this->processed_posts[ intval( $_menu_item_object_id ) ] ) ) {
     997                        $_menu_item_object_id = $this->processed_posts[ intval( $_menu_item_object_id ) ];
     998                } elseif ( 'custom' != $_menu_item_type ) {
     999                        // associated object is missing or not imported yet, we'll retry later
     1000                        $this->missing_menu_items[] = $item;
     1001                        return;
     1002                }
     1003
     1004                if ( isset( $this->processed_menu_items[ intval( $_menu_item_menu_item_parent ) ] ) ) {
     1005                        $_menu_item_menu_item_parent = $this->processed_menu_items[ intval( $_menu_item_menu_item_parent ) ];
     1006                } elseif ( $_menu_item_menu_item_parent ) {
     1007                        $this->menu_item_orphans[ intval( $item['post_id'] ) ] = (int) $_menu_item_menu_item_parent;
     1008                        $_menu_item_menu_item_parent                           = 0;
     1009                }
     1010
     1011                // wp_update_nav_menu_item expects CSS classes as a space separated string
     1012                $_menu_item_classes = $this->maybe_unserialize( $_menu_item_classes );
     1013                if ( is_array( $_menu_item_classes ) ) {
     1014                        $_menu_item_classes = implode( ' ', $_menu_item_classes );
     1015                }
     1016
     1017                $args = array(
     1018                        'menu-item-object-id'   => $_menu_item_object_id,
     1019                        'menu-item-object'      => $_menu_item_object,
     1020                        'menu-item-parent-id'   => $_menu_item_menu_item_parent,
     1021                        'menu-item-position'    => intval( $item['menu_order'] ),
     1022                        'menu-item-type'        => $_menu_item_type,
     1023                        'menu-item-title'       => $item['post_title'],
     1024                        'menu-item-url'         => $_menu_item_url,
     1025                        'menu-item-description' => $item['post_content'],
     1026                        'menu-item-attr-title'  => $item['post_excerpt'],
     1027                        'menu-item-target'      => $_menu_item_target,
     1028                        'menu-item-classes'     => $_menu_item_classes,
     1029                        'menu-item-xfn'         => $_menu_item_xfn,
     1030                        'menu-item-status'      => $item['status'],
     1031                );
     1032
     1033                $id = wp_update_nav_menu_item( $menu_id, 0, $args );
     1034                if ( $id && ! is_wp_error( $id ) ) {
     1035                        $this->processed_menu_items[ intval( $item['post_id'] ) ] = (int) $id;
     1036                }
     1037        }
     1038
     1039        /**
     1040         * If fetching attachments is enabled then attempt to create a new attachment
     1041         *
     1042         * @param array $post Attachment post details from WXR
     1043         * @param string $url URL to fetch attachment from
     1044         * @return int|WP_Error Post ID on success, WP_Error otherwise
     1045         */
     1046        public function process_attachment( $post, $url ) {
     1047                if ( ! $this->fetch_attachments ) {
     1048                        return new WP_Error(
     1049                                'attachment_processing_error',
     1050                                __( 'Fetching attachments is not enabled', 'demo-awesome' )
    9891051                        );
    990 
    991                         $id = wp_update_nav_menu_item( $menu_id, 0, $args );
    992                         if ( $id && ! is_wp_error( $id ) ) {
    993                                 //fix to update mega menu data
    994                                 foreach ( $item['postmeta'] as $meta ) {
    995                                         if (strpos($meta['key'],'evolve_mega') !== false) {
    996                                                 update_post_meta($id, $meta['key'], maybe_unserialize($meta['value']));
    997                                         }
    998                                 }
    999                                 $this->processed_menu_items[ intval( $item['post_id'] ) ] = (int) $id;
    1000                         }
    1001                 }
    1002 
    1003                 /**
    1004                  * If fetching attachments is enabled then attempt to create a new attachment
    1005                  *
    1006                  * @param array $post Attachment post details from WXR
    1007                  * @param string $url URL to fetch attachment from
    1008                  *
    1009                  * @return int|WP_Error Post ID on success, WP_Error otherwise
    1010                  */
    1011                 function process_attachment( $post, $url ) {
    1012                         if ( ! $this->fetch_attachments ) {
    1013                                 return new WP_Error( 'attachment_processing_error',
    1014                                         esc_html__( 'Fetching attachments is not enabled', 'demo-awesome' ) );
    1015                         }
    1016 
    1017                         // if the URL is absolute, but does not contain address, then upload it assuming base_site_url
    1018                         if ( preg_match( '|^/[\w\W]+$|', $url ) ) {
    1019                                 $url = rtrim( $this->base_url, '/' ) . $url;
    1020                         }
    1021 
    1022                         $upload = $this->fetch_remote_file( $url, $post );
    1023                         if ( is_wp_error( $upload ) ) {
    1024                                 return $upload;
    1025                         }
    1026 
    1027                         if ( $info = wp_check_filetype( $upload['file'] ) ) {
    1028                                 $post['post_mime_type'] = $info['type'];
    1029                         } else {
    1030                                 return new WP_Error( 'attachment_processing_error', esc_html__( 'Invalid file type', 'demo-awesome' ) );
    1031                         }
    1032 
    1033                         $post['guid'] = $upload['url'];
    1034 
    1035                         // as per wp-admin/includes/upload.php
    1036                         $post_id = wp_insert_attachment( $post, $upload['file'] );
    1037                         wp_update_attachment_metadata( $post_id, wp_generate_attachment_metadata( $post_id, $upload['file'] ) );
    1038 
    1039                         // remap resized image URLs, works by stripping the extension and remapping the URL stub.
    1040                         if ( preg_match( '!^image/!', $info['type'] ) ) {
    1041                                 $parts = pathinfo( $url );
    1042                                 $name  = basename( $parts['basename'], ".{$parts['extension']}" ); // PATHINFO_FILENAME in PHP 5.2
    1043 
    1044                                 $parts_new = pathinfo( $upload['url'] );
    1045                                 $name_new  = basename( $parts_new['basename'], ".{$parts_new['extension']}" );
    1046 
    1047                                 $this->url_remap[ $parts['dirname'] . '/' . $name ] = $parts_new['dirname'] . '/' . $name_new;
    1048                         }
    1049 
    1050                         return $post_id;
    1051                 }
    1052 
    1053                 /**
    1054                  * Attempt to download a remote file attachment
    1055                  *
    1056                  * @param string $url URL of item to fetch
    1057                  * @param array $post Attachment details
    1058                  *
    1059                  * @return array|WP_Error Local file location details on success, WP_Error otherwise
    1060                  */
    1061                 function fetch_remote_file( $url, $post ) {
    1062                         // extract the file name and extension from the url
    1063                         $file_name = basename( $url );
    1064 
    1065                         // get placeholder file in the upload dir with a unique, sanitized filename
    1066                         $upload = wp_upload_bits( $file_name, 0, '', $post['upload_date'] );
    1067                         if ( $upload['error'] ) {
    1068                                 return new WP_Error( 'upload_dir_error', $upload['error'] );
    1069                         }
    1070 
    1071                         // fetch the remote url and write it to the placeholder file
    1072                         $remote_response = wp_safe_remote_get( $url, array(
     1052                }
     1053
     1054                // if the URL is absolute, but does not contain address, then upload it assuming base_site_url
     1055                if ( preg_match( '|^/[\w\W]+$|', $url ) ) {
     1056                        $url = rtrim( $this->base_url, '/' ) . $url;
     1057                }
     1058
     1059                $upload = $this->fetch_remote_file( $url, $post );
     1060                if ( is_wp_error( $upload ) ) {
     1061                        return $upload;
     1062                }
     1063
     1064                $info = wp_check_filetype( $upload['file'] );
     1065                if ( $info ) {
     1066                        $post['post_mime_type'] = $info['type'];
     1067                } else {
     1068                        return new WP_Error( 'attachment_processing_error', __( 'Invalid file type', 'demo-awesome' ) );
     1069                }
     1070
     1071                $post['guid'] = $upload['url'];
     1072
     1073                // as per wp-admin/includes/upload.php
     1074                $post_id = wp_insert_attachment( $post, $upload['file'] );
     1075                wp_update_attachment_metadata( $post_id, wp_generate_attachment_metadata( $post_id, $upload['file'] ) );
     1076
     1077                // remap resized image URLs, works by stripping the extension and remapping the URL stub.
     1078                if ( preg_match( '!^image/!', $info['type'] ) ) {
     1079                        $parts = pathinfo( $url );
     1080                        $name  = basename( $parts['basename'], ".{$parts['extension']}" ); // PATHINFO_FILENAME in PHP 5.2
     1081
     1082                        $parts_new = pathinfo( $upload['url'] );
     1083                        $name_new  = basename( $parts_new['basename'], ".{$parts_new['extension']}" );
     1084
     1085                        $this->url_remap[ $parts['dirname'] . '/' . $name ] = $parts_new['dirname'] . '/' . $name_new;
     1086                }
     1087
     1088                return $post_id;
     1089        }
     1090
     1091        /**
     1092         * Attempt to download a remote file attachment
     1093         *
     1094         * @param string $url URL of item to fetch
     1095         * @param array $post Attachment details
     1096         * @return array|WP_Error Local file location details on success, WP_Error otherwise
     1097         */
     1098        public function fetch_remote_file( $url, $post ) {
     1099                // Extract the file name from the URL.
     1100                $path      = parse_url( $url, PHP_URL_PATH );
     1101                $file_name = '';
     1102                if ( is_string( $path ) ) {
     1103                        $file_name = basename( $path );
     1104                }
     1105
     1106                if ( ! $file_name ) {
     1107                        $file_name = md5( $url );
     1108                }
     1109
     1110                $tmp_file_name = wp_tempnam( $file_name );
     1111                if ( ! $tmp_file_name ) {
     1112                        return new WP_Error( 'import_no_file', __( 'Could not create temporary file.', 'demo-awesome' ) );
     1113                }
     1114
     1115                // Fetch the remote URL and write it to the placeholder file.
     1116                $remote_response = wp_safe_remote_get(
     1117                        $url,
     1118                        array(
    10731119                                'timeout'  => 300,
    10741120                                'stream'   => true,
    1075                                 'filename' => $upload['file'],
    1076                         ) );
    1077 
    1078                         $headers = wp_remote_retrieve_headers( $remote_response );
    1079 
    1080                         // request failed
    1081                         if ( ! $headers ) {
    1082                                 @unlink( $upload['file'] );
    1083 
    1084                                 return new WP_Error( 'import_file_error', esc_html__( 'Remote server did not respond', 'demo-awesome' ) );
    1085                         }
    1086 
    1087                         $remote_response_code = wp_remote_retrieve_response_code( $remote_response );
    1088 
    1089                         // make sure the fetch was successful
    1090                         if ( $remote_response_code != '200' ) {
    1091                                 @unlink( $upload['file'] );
    1092 
    1093                                 return new WP_Error( 'import_file_error', sprintf( esc_html__( 'Remote server returned error response %1$d %2$s', 'demo-awesome' ), esc_html( $remote_response_code ), get_status_header_desc( $remote_response_code ) ) );
    1094                         }
    1095 
    1096                         $filesize = filesize( $upload['file'] );
    1097 
    1098                         if ( isset( $headers['content-length'] ) && $filesize != $headers['content-length'] ) {
    1099                                 @unlink( $upload['file'] );
    1100 
    1101                                 return new WP_Error( 'import_file_error', esc_html__( 'Remote file is incorrect size', 'demo-awesome' ) );
    1102                         }
    1103 
    1104                         if ( 0 == $filesize ) {
    1105                                 @unlink( $upload['file'] );
    1106 
    1107                                 return new WP_Error( 'import_file_error', esc_html__( 'Zero size file downloaded', 'demo-awesome' ) );
    1108                         }
    1109 
    1110                         $max_size = (int) $this->max_attachment_size();
    1111                         if ( ! empty( $max_size ) && $filesize > $max_size ) {
    1112                                 @unlink( $upload['file'] );
    1113 
    1114                                 return new WP_Error( 'import_file_error', sprintf( esc_html__( 'Remote file is too large, limit is %s', 'demo-awesome' ), size_format( $max_size ) ) );
    1115                         }
    1116 
    1117                         // keep track of the old and new urls so we can substitute them later
    1118                         $this->url_remap[ $url ]          = $upload['url'];
    1119                         $this->url_remap[ $post['guid'] ] = $upload['url']; // r13735, really needed?
    1120                         // keep track of the destination if the remote url is redirected somewhere else
    1121                         if ( isset( $headers['x-final-location'] ) && $headers['x-final-location'] != $url ) {
    1122                                 $this->url_remap[ $headers['x-final-location'] ] = $upload['url'];
    1123                         }
    1124 
    1125                         return $upload;
    1126                 }
    1127 
    1128                 /**
    1129                  * Attempt to associate posts and menu items with previously missing parents
    1130                  *
    1131                  * An imported post's parent may not have been imported when it was first created
    1132                  * so try again. Similarly for child menu items and menu items which were missing
    1133                  * the object (e.g. post) they represent in the menu
    1134                  */
    1135                 function backfill_parents() {
    1136                         global $wpdb;
    1137 
    1138                         // find parents for post orphans
    1139                         foreach ( $this->post_orphans as $child_id => $parent_id ) {
    1140                                 $local_child_id = $local_parent_id = false;
    1141                                 if ( isset( $this->processed_posts[ $child_id ] ) ) {
    1142                                         $local_child_id = $this->processed_posts[ $child_id ];
    1143                                 }
    1144                                 if ( isset( $this->processed_posts[ $parent_id ] ) ) {
    1145                                         $local_parent_id = $this->processed_posts[ $parent_id ];
    1146                                 }
    1147 
    1148                                 if ( $local_child_id && $local_parent_id ) {
    1149                                         $wpdb->update( $wpdb->posts, array( 'post_parent' => $local_parent_id ), array( 'ID' => $local_child_id ), '%d', '%d' );
    1150                                         clean_post_cache( $local_child_id );
    1151                                 }
    1152                         }
    1153 
    1154                         // all other posts/terms are imported, retry menu items with missing associated object
    1155                         $missing_menu_items = $this->missing_menu_items;
    1156                         foreach ( $missing_menu_items as $item ) {
    1157                                 $this->process_menu_item( $item );
    1158                         }
    1159 
    1160                         // find parents for menu item orphans
    1161                         foreach ( $this->menu_item_orphans as $child_id => $parent_id ) {
    1162                                 $local_child_id = $local_parent_id = 0;
    1163                                 if ( isset( $this->processed_menu_items[ $child_id ] ) ) {
    1164                                         $local_child_id = $this->processed_menu_items[ $child_id ];
    1165                                 }
    1166                                 if ( isset( $this->processed_menu_items[ $parent_id ] ) ) {
    1167                                         $local_parent_id = $this->processed_menu_items[ $parent_id ];
    1168                                 }
    1169 
    1170                                 if ( $local_child_id && $local_parent_id ) {
    1171                                         update_post_meta( $local_child_id, '_menu_item_menu_item_parent', (int) $local_parent_id );
    1172                                 }
    1173                         }
    1174                 }
    1175 
    1176                 /**
    1177                  * Use stored mapping information to update old attachment URLs
    1178                  */
    1179                 function backfill_attachment_urls() {
    1180                         global $wpdb;
    1181                         // make sure we do the longest urls first, in case one is a substring of another
    1182                         uksort( $this->url_remap, array( &$this, 'cmpr_strlen' ) );
    1183 
    1184                         foreach ( $this->url_remap as $from_url => $to_url ) {
    1185                                 // remap urls in post_content
    1186                                 $wpdb->query( $wpdb->prepare( "UPDATE {$wpdb->posts} SET post_content = REPLACE(post_content, %s, %s)", $from_url, $to_url ) );
    1187                                 // remap enclosure urls
    1188                                 $result = $wpdb->query( $wpdb->prepare( "UPDATE {$wpdb->postmeta} SET meta_value = REPLACE(meta_value, %s, %s) WHERE meta_key='enclosure'", $from_url, $to_url ) );
    1189                         }
    1190                 }
    1191 
    1192                 /**
    1193                  * Update _thumbnail_id meta to new, imported attachment IDs
    1194                  */
    1195                 function remap_featured_images() {
    1196                         // cycle through posts that have a featured image
    1197                         foreach ( $this->featured_images as $post_id => $value ) {
    1198                                 if ( isset( $this->processed_posts[ $value ] ) ) {
    1199                                         $new_id = $this->processed_posts[ $value ];
    1200                                         // only update if there's a difference
    1201                                         if ( $new_id != $value ) {
    1202                                                 update_post_meta( $post_id, '_thumbnail_id', $new_id );
    1203                                         }
    1204                                 }
    1205                         }
    1206                 }
    1207 
    1208                 /**
    1209                  * Parse a WXR file
    1210                  *
    1211                  * @param string $file Path to WXR file for parsing
    1212                  *
    1213                  * @return array Information gathered from the WXR file
    1214                  */
    1215                 function parse( $file ) {
    1216                         $parser = new Demo_Awesome_Parser();
    1217 
    1218                         return $parser->parse( $file );
    1219                 }
    1220 
    1221                 // Display import page title
    1222                 function header() {
    1223                         echo '<div class="wrap">';
    1224                         echo '<h2>' . esc_html__( 'Import WordPress', 'demo-awesome' ) . '</h2>';
    1225 
    1226                         $updates  = get_plugin_updates();
    1227                         $basename = plugin_basename( __FILE__ );
    1228                         if ( isset( $updates[ $basename ] ) ) {
    1229                                 $update = $updates[ $basename ];
    1230                                 echo '<div class="error"><p><strong>';
    1231                                 printf( esc_html__( 'A new version of this importer is available. Please update to version %s to ensure compatibility with newer export files.', 'demo-awesome' ), $update->update->new_version );
    1232                                 echo '</strong></p></div>';
    1233                         }
    1234                 }
    1235 
    1236                 // Close div.wrap
    1237                 function footer() {
    1238                         echo '</div>';
    1239                 }
    1240 
    1241                 /**
    1242                  * Display introductory text and file upload form
    1243                  */
    1244                 function greet() {
    1245                         echo '<div class="narrow">';
    1246                         echo '<p>' . esc_html__( 'Howdy! Upload your WordPress eXtended RSS (WXR) file and we&#8217;ll import the posts, pages, comments, custom fields, categories, and tags into this site.', 'demo-awesome' ) . '</p>';
    1247                         echo '<p>' . esc_html__( 'Choose a WXR (.xml) file to upload, then click Upload file and import.', 'demo-awesome' ) . '</p>';
    1248                         wp_import_upload_form( 'admin.php?import=wordpress&amp;step=1' );
    1249                         echo '</div>';
    1250                 }
    1251 
    1252                 /**
    1253                  * Decide if the given meta key maps to information we will want to import
    1254                  *
    1255                  * @param string $key The meta key to check
    1256                  *
    1257                  * @return string|bool The key if we do want to import, false if not
    1258                  */
    1259                 function is_valid_meta_key( $key ) {
    1260                         // skip attachment metadata since we'll regenerate it from scratch
    1261                         // skip _edit_lock as not relevant for import
    1262                         if ( in_array( $key, array( '_wp_attached_file', '_wp_attachment_metadata', '_edit_lock' ) ) ) {
    1263                                 return false;
    1264                         }
    1265 
    1266                         return $key;
    1267                 }
    1268 
    1269                 /**
    1270                  * Decide whether or not the importer is allowed to create users.
    1271                  * Default is true, can be filtered via import_allow_create_users
    1272                  *
    1273                  * @return bool True if creating users is allowed
    1274                  */
    1275                 function allow_create_users() {
    1276                         return apply_filters( 'import_allow_create_users', true );
    1277                 }
    1278 
    1279                 /**
    1280                  * Decide whether or not the importer should attempt to download attachment files.
    1281                  * Default is true, can be filtered via import_allow_fetch_attachments. The choice
    1282                  * made at the import options screen must also be true, false here hides that checkbox.
    1283                  *
    1284                  * @return bool True if downloading attachments is allowed
    1285                  */
    1286                 function allow_fetch_attachments() {
    1287                         return apply_filters( 'import_allow_fetch_attachments', true );
    1288                 }
    1289 
    1290                 /**
    1291                  * Decide what the maximum file size for downloaded attachments is.
    1292                  * Default is 0 (unlimited), can be filtered via import_attachment_size_limit
    1293                  *
    1294                  * @return int Maximum attachment file size to import
    1295                  */
    1296                 function max_attachment_size() {
    1297                         return apply_filters( 'import_attachment_size_limit', 0 );
    1298                 }
    1299 
    1300                 /**
    1301                  * Added to http_request_timeout filter to force timeout at 60 seconds during import
    1302                  * @return int 60
    1303                  */
    1304                 function bump_request_timeout( $val ) {
    1305                         return 60;
    1306                 }
    1307 
    1308                 // return the difference in length between two strings
    1309                 function cmpr_strlen( $a, $b ) {
    1310                         return strlen( $b ) - strlen( $a );
    1311                 }
     1121                                'filename' => $tmp_file_name,
     1122                                'headers'  => array(
     1123                                        'Accept-Encoding' => 'identity',
     1124                                ),
     1125                        )
     1126                );
     1127
     1128                if ( is_wp_error( $remote_response ) ) {
     1129                        @unlink( $tmp_file_name );
     1130                        return new WP_Error(
     1131                                'import_file_error',
     1132                                sprintf(
     1133                                        /* translators: 1: The WordPress error message. 2: The WordPress error code. */
     1134                                        __( 'Request failed due to an error: %1$s (%2$s)', 'demo-awesome' ),
     1135                                        esc_html( $remote_response->get_error_message() ),
     1136                                        esc_html( $remote_response->get_error_code() )
     1137                                )
     1138                        );
     1139                }
     1140
     1141                $remote_response_code = (int) wp_remote_retrieve_response_code( $remote_response );
     1142
     1143                // Make sure the fetch was successful.
     1144                if ( 200 !== $remote_response_code ) {
     1145                        @unlink( $tmp_file_name );
     1146                        return new WP_Error(
     1147                                'import_file_error',
     1148                                sprintf(
     1149                                        /* translators: 1: The HTTP error message. 2: The HTTP error code. */
     1150                                        __( 'Remote server returned the following unexpected result: %1$s (%2$s)', 'demo-awesome' ),
     1151                                        get_status_header_desc( $remote_response_code ),
     1152                                        esc_html( $remote_response_code )
     1153                                )
     1154                        );
     1155                }
     1156
     1157                $headers = wp_remote_retrieve_headers( $remote_response );
     1158
     1159                // Request failed.
     1160                if ( ! $headers ) {
     1161                        @unlink( $tmp_file_name );
     1162                        return new WP_Error( 'import_file_error', __( 'Remote server did not respond', 'demo-awesome' ) );
     1163                }
     1164
     1165                $filesize = (int) filesize( $tmp_file_name );
     1166
     1167                if ( 0 === $filesize ) {
     1168                        @unlink( $tmp_file_name );
     1169                        return new WP_Error( 'import_file_error', __( 'Zero size file downloaded', 'demo-awesome' ) );
     1170                }
     1171
     1172                if ( ! isset( $headers['content-encoding'] ) && isset( $headers['content-length'] ) && $filesize !== (int) $headers['content-length'] ) {
     1173                        @unlink( $tmp_file_name );
     1174                        return new WP_Error( 'import_file_error', __( 'Downloaded file has incorrect size', 'demo-awesome' ) );
     1175                }
     1176
     1177                $max_size = (int) $this->max_attachment_size();
     1178                if ( ! empty( $max_size ) && $filesize > $max_size ) {
     1179                        @unlink( $tmp_file_name );
     1180                        return new WP_Error( 'import_file_error', sprintf( __( 'Remote file is too large, limit is %s', 'demo-awesome' ), size_format( $max_size ) ) );
     1181                }
     1182
     1183                // Override file name with Content-Disposition header value.
     1184                if ( ! empty( $headers['content-disposition'] ) ) {
     1185                        $file_name_from_disposition = self::get_filename_from_disposition( (array) $headers['content-disposition'] );
     1186                        if ( $file_name_from_disposition ) {
     1187                                $file_name = $file_name_from_disposition;
     1188                        }
     1189                }
     1190
     1191                // Set file extension if missing.
     1192                $file_ext = pathinfo( $file_name, PATHINFO_EXTENSION );
     1193                if ( ! $file_ext && ! empty( $headers['content-type'] ) ) {
     1194                        $extension = self::get_file_extension_by_mime_type( $headers['content-type'] );
     1195                        if ( $extension ) {
     1196                                $file_name = "{$file_name}.{$extension}";
     1197                        }
     1198                }
     1199
     1200                // Handle the upload like _wp_handle_upload() does.
     1201                $wp_filetype     = wp_check_filetype_and_ext( $tmp_file_name, $file_name );
     1202                $ext             = empty( $wp_filetype['ext'] ) ? '' : $wp_filetype['ext'];
     1203                $type            = empty( $wp_filetype['type'] ) ? '' : $wp_filetype['type'];
     1204                $proper_filename = empty( $wp_filetype['proper_filename'] ) ? '' : $wp_filetype['proper_filename'];
     1205
     1206                // Check to see if wp_check_filetype_and_ext() determined the filename was incorrect.
     1207                if ( $proper_filename ) {
     1208                        $file_name = $proper_filename;
     1209                }
     1210
     1211                if ( ( ! $type || ! $ext ) && ! current_user_can( 'unfiltered_upload' ) ) {
     1212                        return new WP_Error( 'import_file_error', __( 'Sorry, this file type is not permitted for security reasons.', 'demo-awesome' ) );
     1213                }
     1214
     1215                $uploads = wp_upload_dir( $post['upload_date'] );
     1216                if ( ! ( $uploads && false === $uploads['error'] ) ) {
     1217                        return new WP_Error( 'upload_dir_error', $uploads['error'] );
     1218                }
     1219
     1220                // Move the file to the uploads dir.
     1221                $file_name     = wp_unique_filename( $uploads['path'], $file_name );
     1222                $new_file      = $uploads['path'] . "/$file_name";
     1223                $move_new_file = copy( $tmp_file_name, $new_file );
     1224
     1225                if ( ! $move_new_file ) {
     1226                        @unlink( $tmp_file_name );
     1227                        return new WP_Error( 'import_file_error', __( 'The uploaded file could not be moved', 'demo-awesome' ) );
     1228                }
     1229
     1230                // Set correct file permissions.
     1231                $stat  = stat( dirname( $new_file ) );
     1232                $perms = $stat['mode'] & 0000666;
     1233                chmod( $new_file, $perms );
     1234
     1235                $upload = array(
     1236                        'file'  => $new_file,
     1237                        'url'   => $uploads['url'] . "/$file_name",
     1238                        'type'  => $wp_filetype['type'],
     1239                        'error' => false,
     1240                );
     1241
     1242                // keep track of the old and new urls so we can substitute them later
     1243                $this->url_remap[ $url ]          = $upload['url'];
     1244                $this->url_remap[ $post['guid'] ] = $upload['url']; // r13735, really needed?
     1245                // keep track of the destination if the remote url is redirected somewhere else
     1246                if ( isset( $headers['x-final-location'] ) && $headers['x-final-location'] != $url ) {
     1247                        $this->url_remap[ $headers['x-final-location'] ] = $upload['url'];
     1248                }
     1249
     1250                return $upload;
     1251        }
     1252
     1253        /**
     1254         * Attempt to associate posts and menu items with previously missing parents
     1255         *
     1256         * An imported post's parent may not have been imported when it was first created
     1257         * so try again. Similarly for child menu items and menu items which were missing
     1258         * the object (e.g. post) they represent in the menu
     1259         */
     1260        public function backfill_parents() {
     1261                global $wpdb;
     1262
     1263                // find parents for post orphans
     1264                foreach ( $this->post_orphans as $child_id => $parent_id ) {
     1265                        $local_child_id  = false;
     1266                        $local_parent_id = false;
     1267                        if ( isset( $this->processed_posts[ $child_id ] ) ) {
     1268                                $local_child_id = $this->processed_posts[ $child_id ];
     1269                        }
     1270                        if ( isset( $this->processed_posts[ $parent_id ] ) ) {
     1271                                $local_parent_id = $this->processed_posts[ $parent_id ];
     1272                        }
     1273
     1274                        if ( $local_child_id && $local_parent_id ) {
     1275                                $wpdb->update( $wpdb->posts, array( 'post_parent' => $local_parent_id ), array( 'ID' => $local_child_id ), '%d', '%d' );
     1276                                clean_post_cache( $local_child_id );
     1277                        }
     1278                }
     1279
     1280                // all other posts/terms are imported, retry menu items with missing associated object
     1281                $missing_menu_items = $this->missing_menu_items;
     1282                foreach ( $missing_menu_items as $item ) {
     1283                        $this->process_menu_item( $item );
     1284                }
     1285
     1286                // find parents for menu item orphans
     1287                foreach ( $this->menu_item_orphans as $child_id => $parent_id ) {
     1288                        $local_child_id  = 0;
     1289                        $local_parent_id = 0;
     1290                        if ( isset( $this->processed_menu_items[ $child_id ] ) ) {
     1291                                $local_child_id = $this->processed_menu_items[ $child_id ];
     1292                        }
     1293                        if ( isset( $this->processed_menu_items[ $parent_id ] ) ) {
     1294                                $local_parent_id = $this->processed_menu_items[ $parent_id ];
     1295                        }
     1296
     1297                        if ( $local_child_id && $local_parent_id ) {
     1298                                update_post_meta( $local_child_id, '_menu_item_menu_item_parent', (int) $local_parent_id );
     1299                        }
     1300                }
     1301        }
     1302
     1303        /**
     1304         * Use stored mapping information to update old attachment URLs
     1305         */
     1306        public function backfill_attachment_urls() {
     1307                global $wpdb;
     1308                // make sure we do the longest urls first, in case one is a substring of another
     1309                uksort( $this->url_remap, array( &$this, 'cmpr_strlen' ) );
     1310
     1311                foreach ( $this->url_remap as $from_url => $to_url ) {
     1312                        // remap urls in post_content
     1313                        $wpdb->query( $wpdb->prepare( "UPDATE {$wpdb->posts} SET post_content = REPLACE(post_content, %s, %s)", $from_url, $to_url ) );
     1314                        // remap enclosure urls
     1315                        $result = $wpdb->query( $wpdb->prepare( "UPDATE {$wpdb->postmeta} SET meta_value = REPLACE(meta_value, %s, %s) WHERE meta_key='enclosure'", $from_url, $to_url ) );
     1316                }
     1317        }
     1318
     1319        /**
     1320         * Update _thumbnail_id meta to new, imported attachment IDs
     1321         */
     1322        public function remap_featured_images() {
     1323                // cycle through posts that have a featured image
     1324                foreach ( $this->featured_images as $post_id => $value ) {
     1325                        if ( isset( $this->processed_posts[ $value ] ) ) {
     1326                                $new_id = $this->processed_posts[ $value ];
     1327                                // only update if there's a difference
     1328                                if ( $new_id != $value ) {
     1329                                        update_post_meta( $post_id, '_thumbnail_id', $new_id );
     1330                                }
     1331                        }
     1332                }
     1333        }
     1334
     1335        /**
     1336         * Unserialize WXR meta safely.
     1337         *
     1338         * Backported from WordPress Importer 0.9.x. Neutralizes any serialized PHP
     1339         * object in the data by rewriting it to a harmless stdClass before
     1340         * unserializing, preventing PHP object injection from a malicious WXR file.
     1341         *
     1342         * @param string $data Serialized (or plain) meta value from the WXR file.
     1343         * @return mixed The unserialized value, with objects coerced to stdClass.
     1344         */
     1345        protected function maybe_unserialize( $data ) {
     1346                if ( is_serialized( $data ) ) {
     1347                        // Transform any serialized objects into a stdClass object.
     1348                        $data = preg_replace( '/O:\d+:"[^"]+":/', 'O:8:"stdClass":', $data );
     1349
     1350                        return maybe_unserialize( $data );
     1351                }
     1352
     1353                return $data;
     1354        }
     1355
     1356        /**
     1357         * Parse a WXR file
     1358         *
     1359         * @param string $file Path to WXR file for parsing
     1360         * @return array Information gathered from the WXR file
     1361         */
     1362        public function parse( $file ) {
     1363                $parser = new Demo_Awesome_Parser();
     1364                return $parser->parse( $file );
     1365        }
     1366
     1367        // Display import page title
     1368        public function header() {
     1369                echo '<div class="wrap">';
     1370                echo '<h2>' . __( 'Import WordPress', 'demo-awesome' ) . '</h2>';
     1371
     1372                $updates  = get_plugin_updates();
     1373                $basename = plugin_basename( __FILE__ );
     1374                if ( isset( $updates[ $basename ] ) ) {
     1375                        $update = $updates[ $basename ];
     1376                        echo '<div class="error"><p><strong>';
     1377                        printf( __( 'A new version of this importer is available. Please update to version %s to ensure compatibility with newer export files.', 'demo-awesome' ), $update->update->new_version );
     1378                        echo '</strong></p></div>';
     1379                }
     1380        }
     1381
     1382        // Close div.wrap
     1383        public function footer() {
     1384                echo '</div>';
     1385        }
     1386
     1387        /**
     1388         * Display introductory text and file upload form
     1389         */
     1390        public function greet() {
     1391                echo '<div class="narrow">';
     1392                echo '<p>' . __( 'Howdy! Upload your WordPress eXtended RSS (WXR) file and we&#8217;ll import the posts, pages, comments, custom fields, categories, and tags into this site.', 'demo-awesome' ) . '</p>';
     1393                echo '<p>' . __( 'Choose a WXR (.xml) file to upload, then click Upload file and import.', 'demo-awesome' ) . '</p>';
     1394                wp_import_upload_form( 'admin.php?import=wordpress&amp;step=1' );
     1395                echo '</div>';
     1396        }
     1397
     1398        /**
     1399         * Decide if the given meta key maps to information we will want to import
     1400         *
     1401         * @param string $key The meta key to check
     1402         * @return string|bool The key if we do want to import, false if not
     1403         */
     1404        public function is_valid_meta_key( $key ) {
     1405                // skip attachment metadata since we'll regenerate it from scratch
     1406                // skip _edit_lock as not relevant for import
     1407                if ( in_array( $key, array( '_wp_attached_file', '_wp_attachment_metadata', '_edit_lock' ), true ) ) {
     1408                        return false;
     1409                }
     1410                return $key;
     1411        }
     1412
     1413        /**
     1414         * Decide whether or not the importer is allowed to create users.
     1415         * Default is true, can be filtered via import_allow_create_users
     1416         *
     1417         * @return bool True if creating users is allowed
     1418         */
     1419        public function allow_create_users() {
     1420                return apply_filters( 'import_allow_create_users', true );
     1421        }
     1422
     1423        /**
     1424         * Decide whether or not the importer should attempt to download attachment files.
     1425         * Default is true, can be filtered via import_allow_fetch_attachments. The choice
     1426         * made at the import options screen must also be true, false here hides that checkbox.
     1427         *
     1428         * @return bool True if downloading attachments is allowed
     1429         */
     1430        public function allow_fetch_attachments() {
     1431                return apply_filters( 'import_allow_fetch_attachments', true );
     1432        }
     1433
     1434        /**
     1435         * Decide what the maximum file size for downloaded attachments is.
     1436         * Default is 0 (unlimited), can be filtered via import_attachment_size_limit
     1437         *
     1438         * @return int Maximum attachment file size to import
     1439         */
     1440        public function max_attachment_size() {
     1441                return apply_filters( 'import_attachment_size_limit', 0 );
     1442        }
     1443
     1444        /**
     1445         * Added to http_request_timeout filter to force timeout at 60 seconds during import
     1446         * @return int 60
     1447         */
     1448        public function bump_request_timeout( $val ) {
     1449                return 60;
     1450        }
     1451
     1452        // return the difference in length between two strings
     1453        public function cmpr_strlen( $a, $b ) {
     1454                return strlen( $b ) - strlen( $a );
     1455        }
     1456
     1457        /**
     1458         * Parses filename from a Content-Disposition header value.
     1459         *
     1460         * As per RFC6266:
     1461         *
     1462         *     content-disposition = "Content-Disposition" ":"
     1463         *                            disposition-type *( ";" disposition-parm )
     1464         *
     1465         *     disposition-type    = "inline" | "attachment" | disp-ext-type
     1466         *                         ; case-insensitive
     1467         *     disp-ext-type       = token
     1468         *
     1469         *     disposition-parm    = filename-parm | disp-ext-parm
     1470         *
     1471         *     filename-parm       = "filename" "=" value
     1472         *                         | "filename*" "=" ext-value
     1473         *
     1474         *     disp-ext-parm       = token "=" value
     1475         *                         | ext-token "=" ext-value
     1476         *     ext-token           = <the characters in token, followed by "*">
     1477         *
     1478         * @since 0.7.0
     1479         *
     1480         * @see WP_REST_Attachments_Controller::get_filename_from_disposition()
     1481         *
     1482         * @link http://tools.ietf.org/html/rfc2388
     1483         * @link http://tools.ietf.org/html/rfc6266
     1484         *
     1485         * @param string[] $disposition_header List of Content-Disposition header values.
     1486         * @return string|null Filename if available, or null if not found.
     1487         */
     1488        protected static function get_filename_from_disposition( $disposition_header ) {
     1489                // Get the filename.
     1490                $filename = null;
     1491
     1492                foreach ( $disposition_header as $value ) {
     1493                        $value = trim( $value );
     1494
     1495                        if ( strpos( $value, ';' ) === false ) {
     1496                                continue;
     1497                        }
     1498
     1499                        list( $type, $attr_parts ) = explode( ';', $value, 2 );
     1500
     1501                        $attr_parts = explode( ';', $attr_parts );
     1502                        $attributes = array();
     1503
     1504                        foreach ( $attr_parts as $part ) {
     1505                                if ( strpos( $part, '=' ) === false ) {
     1506                                        continue;
     1507                                }
     1508
     1509                                list( $key, $value ) = explode( '=', $part, 2 );
     1510
     1511                                $attributes[ trim( $key ) ] = trim( $value );
     1512                        }
     1513
     1514                        if ( empty( $attributes['filename'] ) ) {
     1515                                continue;
     1516                        }
     1517
     1518                        $filename = trim( $attributes['filename'] );
     1519
     1520                        // Unquote quoted filename, but after trimming.
     1521                        if ( substr( $filename, 0, 1 ) === '"' && substr( $filename, -1, 1 ) === '"' ) {
     1522                                $filename = substr( $filename, 1, -1 );
     1523                        }
     1524                }
     1525
     1526                return $filename;
     1527        }
     1528
     1529        /**
     1530         * Retrieves file extension by mime type.
     1531         *
     1532         * @since 0.7.0
     1533         *
     1534         * @param string $mime_type Mime type to search extension for.
     1535         * @return string|null File extension if available, or null if not found.
     1536         */
     1537        protected static function get_file_extension_by_mime_type( $mime_type ) {
     1538                static $map = null;
     1539
     1540                if ( is_array( $map ) ) {
     1541                        return isset( $map[ $mime_type ] ) ? $map[ $mime_type ] : null;
     1542                }
     1543
     1544                $mime_types = wp_get_mime_types();
     1545                $map        = array_flip( $mime_types );
     1546
     1547                // Some types have multiple extensions, use only the first one.
     1548                foreach ( $map as $type => $extensions ) {
     1549                        $map[ $type ] = strtok( $extensions, '|' );
     1550                }
     1551
     1552                return isset( $map[ $mime_type ] ) ? $map[ $mime_type ] : null;
    13121553        }
    13131554}
  • demo-awesome/tags/1.0.6/inc/admin/importer/class-demo-awesome-widget-importer.php

    r2158733 r3813524  
    3131                        global $wp_registered_sidebars;
    3232
    33                         $data = json_decode( file_get_contents( $import_file ) );
     33                        // Security: Validate file path and content
     34                        if (!self::validate_import_file($import_file)) {
     35                                return new WP_Error( 'demo_awesome_widget_import_file_error', esc_html__( 'Invalid import file.', 'demo-awesome' ) );
     36                        }
     37
     38                        $file_content = file_get_contents( $import_file );
     39                        if ($file_content === false) {
     40                                return new WP_Error( 'demo_awesome_widget_import_file_error', esc_html__( 'Could not read import file.', 'demo-awesome' ) );
     41                        }
     42
     43                        // Security: Validate file content
     44                        if (!self::validate_file_content($file_content)) {
     45                                return new WP_Error( 'demo_awesome_widget_import_content_error', esc_html__( 'Invalid file content detected.', 'demo-awesome' ) );
     46                        }
     47
     48                        $data = json_decode( $file_content );
    3449
    3550                        // Have valid data? If no data or could not decode.
    … …  
    112127                                         * Do before identical check because changes may make it identical to end result (such as URL replacements).
    113128                                         */
    114                                         $widget = apply_filters( 'widget_demo_import_settings', $widget, $id_base, $instance_id_number, $data_demo );
     129                                        $widget = apply_filters( 'demo_awesome_widget_import_settings', $widget, $id_base, $instance_id_number, $data_demo );
    115130
    116131                                        // Does widget with identical settings already exist in same sidebar?
    … …  
    167182
    168183                                                // Assign widget instance to sidebar.
    169                                                 $sidebars_widgets                      = get_option( 'sidebars_widgets' ); // Which sidebars have which widgets, get fresh every time.
     184                                                $sidebars_widgets                      = (array) get_option( 'sidebars_widgets', array() ); // Which sidebars have which widgets, get fresh every time.
    170185                                                $new_instance_id                       = $id_base . '-' . $new_instance_id_number; // Use ID number from new widget instance.
    171186                                                $sidebars_widgets[ $use_sidebar_id ][] = $new_instance_id; // Add new instance to sidebar.
    … …  
    233248                        return apply_filters( 'demo_awesome_widget_importer_available_widgets', $available_widgets );
    234249                }
     250
     251                /**
     252                 * Validate import file path and permissions
     253                 * @since 1.0.3
     254                 */
     255                private static function validate_import_file($file_path) {
     256                        // Check if file exists
     257                        if (!file_exists($file_path)) {
     258                                return false;
     259                        }
     260
     261                        // Check if file is readable
     262                        if (!is_readable($file_path)) {
     263                                return false;
     264                        }
     265
     266                        // Check file extension
     267                        $allowed_extensions = array('wie', 'json');
     268                        $file_extension = strtolower(pathinfo($file_path, PATHINFO_EXTENSION));
     269                        if (!in_array($file_extension, $allowed_extensions)) {
     270                                return false;
     271                        }
     272
     273                        // Check file size (prevent DoS)
     274                        if (filesize($file_path) > 5 * 1024 * 1024) { // 5MB limit
     275                                return false;
     276                        }
     277
     278                        return true;
     279                }
     280
     281                /**
     282                 * Validate file content for security
     283                 * @since 1.0.3
     284                 */
     285                private static function validate_file_content($content) {
     286                        // Check for empty content
     287                        if (empty($content)) {
     288                                return false;
     289                        }
     290
     291                        // Check content length
     292                        if (strlen($content) > 5 * 1024 * 1024) { // 5MB limit
     293                                return false;
     294                        }
     295
     296                        // Check for malicious content
     297                        if (preg_match('/<\?php|<\?=|<script[^>]*>|javascript:|data:/i', $content)) {
     298                                return false;
     299                        }
     300
     301                        // Validate JSON structure
     302                        $decoded = json_decode($content, true);
     303                        if (json_last_error() !== JSON_ERROR_NONE) {
     304                                return false;
     305                        }
     306
     307                        return true;
     308                }
    235309        }
    236310}
  • demo-awesome/tags/1.0.6/inc/admin/importer/class-extends-customize-demo-importer-setting.php

    r2158733 r3813524  
    1010 * @author     Theme4Press
    1111 */
     12
     13// Exit if accessed directly.
     14if ( ! defined( 'ABSPATH' ) ) {
     15        exit;
     16}
    1217
    1318/**
  • demo-awesome/tags/1.0.6/inc/admin/js/admin.js

    r3081092 r3813524  
    15831583        var data = {
    15841584            'action': 'call_import_function_from_ajax',
    1585             'data_demo': data_demo,
    1586             'nonce': demo_awesome_js_local_vars.nonce
     1585            'demo_index': data_demo.index,
     1586            '_nonce': demo_awesome_js_local_vars._nonce
     1587        };
     1588        var $alert = $('#finish-import-modal .alert-message-from-importer');
     1589        var showError = function (message) {
     1590            $(".hide-content").fadeOut(1500);
     1591            $alert.removeClass('alert-success').addClass('alert-danger').text(message);
     1592            $(".show-content").fadeIn(1500).css("display", "flex");
    15871593        };
    15881594        jQuery.post(ajaxurl, data, function (response) {
    1589             $(".hide-content").fadeOut(1500);
    15901595            if (response && response.success) {
    1591                 $('#finish-import-modal .alert-message-from-importer').removeClass('alert-danger').addClass('alert-success').text('').wrapInner(response.data.message);
     1596                $(".hide-content").fadeOut(1500);
     1597                $alert.removeClass('alert-danger').addClass('alert-success').text('').wrapInner(response.data.message);
     1598                $(".show-content").fadeIn(1500).css("display", "flex");
    15921599            }
    15931600            else {
    1594                 $('#finish-import-modal .alert-message-from-importer').removeClass('alert-success').addClass('alert-danger').text('').wrapInner(response);
     1601                var d = (response && response.data) || {};
     1602                showError(d.message || d.errorMessage || 'The import failed. Please check the PHP error log for details.');
    15951603            }
    1596             $(".show-content").fadeIn(1500).css("display", "flex");
    1597 
     1604        }).fail(function (xhr) {
     1605            showError('The import request failed (HTTP ' + xhr.status + '). The server may have run out of time or memory; please check the PHP error log.');
    15981606        });
    15991607    });
    … …  
    16741682            data: {
    16751683                action: 'required_plugins',
    1676                 data_demo: data_demo
     1684                demo_index: data_demo.index,
     1685                 '_nonce': demo_awesome_js_local_vars._nonce
    16771686            },
    16781687            success: function (data) {
    … …  
    16971706                plugin: plugin,
    16981707                html: html,
     1708                '_nonce': demo_awesome_js_local_vars._nonce
    16991709            },
    17001710            success: function (data) {
    … …  
    17071717                        plugin: plugin,
    17081718                        html: html,
     1719                        '_nonce': demo_awesome_js_local_vars._nonce
    17091720                    },
    17101721                    success: function (data) {
  • demo-awesome/tags/1.0.6/inc/admin/required-plugins.php

    r3081092 r3813524  
    88 * @author     Theme4Press
    99 */
     10
     11// Exit if accessed directly.
     12if (!defined('ABSPATH')) {
     13    exit;
     14}
    1015
    1116if (!function_exists('demo_awesome_required_plugins')) {
    … …  
    2429        <div class="refresh-container-box">
    2530            <?php
    26             if (isset($_POST['action']) && $_POST['action'] == 'required_plugins') {
     31            // phpcs:ignore WordPress.Security.NonceVerification.Missing -- The calling AJAX handler (required_plugins()) verifies the nonce before this template is included.
     32            if (isset($_POST['action']) && 'required_plugins' === sanitize_text_field(wp_unslash($_POST['action']))) {
    2733                $requred_message = [];
    2834                if ($data_demo) {
    … …  
    4551
    4652
    47                         <span class="mr-1"><?php echo Demo_Awesome_Admin::get_svg('warning'); ?></span><?php esc_html_e(
     53                        <span class="mr-1"><?php echo wp_kses( Demo_Awesome_Admin::get_svg('warning'), Demo_Awesome_Admin::allowed_svg_tags() ); ?></span><?php esc_html_e(
    4854                            'This demo import requires additional plugins',
    4955                            'demo-awesome'
    … …  
    5258                        <button class="button button-primary refresh-required"><span
    5359                                    class="mr-1"
    54                                     name="refresh-required"><?php echo Demo_Awesome_Admin::get_svg('refresh'); ?></span>
     60                                    name="refresh-required"><?php echo wp_kses( Demo_Awesome_Admin::get_svg('refresh'), Demo_Awesome_Admin::allowed_svg_tags() ); ?></span>
    5561                            <?php esc_html_e('Refresh', 'demo-awesome'); ?>
    5662                        </button>
    … …  
    6672
    6773
    68                     <span class="mr-1"><?php echo Demo_Awesome_Admin::get_svg('warning'); ?></span><?php esc_html_e(
     74                    <span class="mr-1"><?php echo wp_kses( Demo_Awesome_Admin::get_svg('warning'), Demo_Awesome_Admin::allowed_svg_tags() ); ?></span><?php esc_html_e(
    6975                        'This demo import requires additional plugins',
    7076                        'demo-awesome'
    … …  
    7379                    <button class="button button-primary refresh-required"><span
    7480                                class="mr-1"
    75                                 name="refresh-required"><?php echo wp_kses_post( Demo_Awesome_Admin::get_svg(
     81                                name="refresh-required"><?php echo wp_kses( Demo_Awesome_Admin::get_svg(
    7682                                'refresh'
    77                             )); ?></span><?php esc_html_e('Refresh', 'demo-awesome'); ?>
     83                            ), Demo_Awesome_Admin::allowed_svg_tags() ); ?></span><?php esc_html_e('Refresh', 'demo-awesome'); ?>
    7884                    </button>
    7985
    … …  
    124130                                        $premium_plugin = sprintf(
    125131                                            '<div class="badge badge-premium">%s</div>',
    126                                             $plugin['disable_description']
     132                                           esc_html($plugin['disable_description'])
    127133                                        );
    128134                                     //   var_dump($plugin);
    129                                             $plugin['slug'] =  isset( $plugin['slug']{1} ) ? $plugin['slug'] : $plugin['keyword'];
    130                                         $premium_plugin = sprintf(
    131                                             '<a class="button evole-install-plugin button-proceed" target="_blank"
    132                                  data-plugin="'.$plugin['slug'].'" href="'.self_admin_url('#%s">%s</a>'),
    133                                             $plugin['keyword'],
    134                                             esc_html__('Install', 'demo-awesome')
    135                                         );
     135                                            $plugin['slug'] =  isset( $plugin['slug'][1] ) ? $plugin['slug'] : $plugin['keyword'];
     136
     137                                //         $premium_plugin = sprintf(
     138                                //             '<a class="button evole-install-plugin button-proceed" target="_blank"
     139                                //  data-plugin="'.$plugin['slug'].'" href="'.self_admin_url('#%s">%s</a>'),
     140                                //             $plugin['keyword'],
     141                                //             esc_html__('Install', 'demo-awesome')
     142                                //         );
     143                                $install_url = self_admin_url( sprintf( '#%s', rawurlencode( $plugin['keyword'] ) ) );
     144
     145                                $premium_plugin = sprintf(
     146                                    '<a class="button evole-install-plugin button-proceed" target="_blank" data-plugin="%1$s" href="%2$s">%3$s</a>',
     147                                    esc_attr( $plugin['slug'] ),
     148                                    esc_url( $install_url ),
     149                                    esc_html__( 'Install', 'demo-awesome' )
     150                                );
     151
     152
    136153                                    } else {
    137154                                        $premium_plugin = sprintf(
    … …  
    149166                                <li>
    150167                                    <strong><?php
    151                                         echo wp_kses_post($plugin['name'].'<br />'.$required_plugin); ?></strong>
     168                                        echo wp_kses($plugin['name'].'<br />'.$required_plugin, Demo_Awesome_Admin::allowed_svg_tags()); ?></strong>
    152169                                    <?php if (current_user_can(  'install_plugins' ) || current_user_can( 'update_plugins' )) {
    153                                         echo wp_kses_post($premium_plugin);
     170                                        echo wp_kses($premium_plugin, Demo_Awesome_Admin::allowed_svg_tags());
    154171                                    } ?>
    155172                                </li>
    … …  
    160177                    <?php if ($show_required_description) { ?>
    161178                        <p class="alert alert-info required-description-text"><span
    162                                     class="mr-1"><?php echo wp_kses_post( Demo_Awesome_Admin::get_svg('info')); ?></span><?php esc_html_e(
     179                                    class="mr-1"><?php echo wp_kses( Demo_Awesome_Admin::get_svg('info'), Demo_Awesome_Admin::allowed_svg_tags() ); ?></span><?php esc_html_e(
    163180                                'You can install/activate the required plugin(s) before import or import the demo content now. Importing content without enabled required plugin(s) may result in broken page layout or not importing the data supported by the plugin(s).',
    164181                                'demo-awesome'
  • demo-awesome/tags/1.0.6/inc/class-demo-awesome-i18n.php

    r2003923 r3813524  
    99 */
    1010
     11// Exit if accessed directly.
     12if ( ! defined( 'ABSPATH' ) ) {
     13        exit;
     14}
     15
    1116if ( ! class_exists( 'Demo_Awesome_i18n' ) ) {
    1217        class Demo_Awesome_i18n {
    … …  
    1722                public function load_plugin_textdomain() {
    1823
     24                        // phpcs:ignore PluginCheck.CodeAnalysis.DiscouragedFunctions.load_plugin_textdomainFound -- Retained so bundled translations also load on non-wordpress.org installs.
    1925                        load_plugin_textdomain(
    2026                                'demo-awesome',
  • demo-awesome/tags/1.0.6/inc/class-demo-awesome-loader.php

    r2003923 r3813524  
    88 * @author     Theme4Press
    99 */
     10
     11// Exit if accessed directly.
     12if ( ! defined( 'ABSPATH' ) ) {
     13        exit;
     14}
    1015
    1116if ( ! class_exists( 'Demo_Awesome_Loader' ) ) {
  • demo-awesome/tags/1.0.6/inc/class-demo-awesome.php

    r2158733 r3813524  
    88 * @author     Theme4Press
    99 */
     10
     11// Exit if accessed directly.
     12if ( ! defined( 'ABSPATH' ) ) {
     13        exit;
     14}
    1015
    1116if ( ! class_exists( 'Demo_Awesome' ) ) {
  • demo-awesome/trunk/README.txt

    r3081092 r3813524  
    11=== Demo Awesome ===
    22Contributors: evgenyviner
    3 Tags: theme4press, data importer, one-click demo import, theme demo, demos, importer, theme4press demo
    4 Requires at least: 4.7
    5 Tested up to: 6.5.2
    6 Requires PHP: 7.0
    7 Stable tag: trunk
     3Tags: data importer, one-click demo import, theme demo, demos, importer
     4Requires at least: 5.5
     5Tested up to: 7.1
     6Requires PHP: 7.4
     7Stable tag: 1.0.6
    88License: GPLv2 or later
    99License URI: http://www.gnu.org/licenses/gpl-2.0.html
    … …  
    4040We strongly recommend using these demos for newly created websites, development websites, etc. as the plugin will change or remove much existing content of your website like posts, pages, widgets, theme settings, etc.
    4141
     42== External services ==
     43
     44This plugin connects to the Theme4Press demo server, **demo.theme4press.com**, operated by Theme4Press. The demos are stored there, so the plugin cannot work without it.
     45
     46What is requested and when:
     47
     48* **Opening the demo browser** (Appearance > Demo Awesome): the plugin downloads the list of available demos (`get-list-demos.json`). Your browser loads each demo's screenshot image from the demo server.
     49* **Live preview** of a demo: the demo website on demo.theme4press.com is shown in a frame, so it is loaded by your browser.
     50* **Importing a demo**: the plugin downloads that demo's content, widget and theme-settings files (and slider files for demos that have them), and WordPress downloads the demo's images.
     51
     52No personal data, account data or content from your site is sent. As with any web request, the demo server receives the requesting IP address and browser or server details; image downloads made by WordPress also include your site's address in the standard WordPress user-agent header.
     53
     54Premium demos may require premium plugins. With the evolve Plus theme, these are downloaded by the theme from Theme4Press using the theme's license key; Demo Awesome itself does not send the key. Free required plugins are installed from WordPress.org.
     55
     56Theme4Press terms and conditions: https://theme4press.com/terms-conditions/
     57Theme4Press privacy policy: https://theme4press.com/privacy-policy/
     58
    4259== Screenshots ==
    4360
    … …  
    4966== Changelog ==
    5067
     68= 1.0.6 =
     69* Fixed the demo import doing nothing but showing "requires additional plugins" (a stray duplicate AJAX action introduced by an earlier release)
     70* Removed the over-aggressive request rate limit that blocked legitimate importing/plugin installation
     71* Allowed required-plugin installation for any valid plugin slug (was limited to a small hardcoded list); hardened the activation match against regex injection
     72* Fixed every import failing with "Invalid template name" (demo folders such as "business/1" were rejected)
     73* Fixed 12 of the 20 demos being rejected because their content contains ordinary embed scripts; downloads are now validated by file format and rejected only if they contain PHP code
     74* Security: the demo to import is now looked up by its index in the demo list from the demo server; folder, options and required plugins are no longer taken from the browser request
     75* Fixed a premium demo, or a failed download, removing the site's theme settings, menus and widgets before the import was refused; nothing is removed until the demo content has been downloaded and validated
     76* Fixed the download cache: cached files of some demos (App 1, App 2, Blog 1, Portfolio 1) could never be read back, so any repeat import within an hour failed; a missing or invalid cached copy is now downloaded again
     77* Import errors are now shown in the import window instead of failing silently
     78* Fixed LayerSlider data never being imported (demo list key mismatch) and PHP warnings for demos without slider data
     79
     80= 1.0.5 =
     81* Security: prevented PHP object injection when importing customizer (.dat) data
     82* Security: hardened XML validation against XXE / entity-expansion attacks
     83* Security: blocked demo data from overwriting sensitive WordPress options
     84* Updated the bundled WordPress Importer to 0.8.3 (security & bug fixes, incl. safer attachment downloads and object-injection-safe meta handling)
     85* Fixed a bug that disabled the remote demo list cache (every admin page load re-fetched it)
     86* Replaced the deprecated get_page_by_title() with a WP_Query-based helper
     87* Prevented a fatal error in the plugin install/activate handlers when the theme helper is unavailable
     88* Various WordPress coding-standard fixes (text domains, output escaping, script/style enqueue)
     89
    5190= 1.0.2 =
    5291* Fixed some security vulnerablities
  • demo-awesome/trunk/demo-awesome.php

    r3081092 r3813524  
    1010 * Plugin URI:        https://theme4press.com/demo-awesome-the-data-importer/
    1111 * Description:       Import the Theme4Press theme demo content including theme settings, menus, widgets, sliders, and much more with just one click. Awesome!
    12  * Version:           1.0.3
     12 * Version:           1.0.6
    1313 * Author:            Theme4Press
    1414 * Author URI:        https://theme4press.com
    … …  
    2727 * @since    1.0.0
    2828 */
    29 define( 'DEMO_AWESOME_VERSION', '1.0.0' );
     29define( 'DEMO_AWESOME_VERSION', '1.0.6' );
    3030
    3131/**
    … …  
    4444        }
    4545}
    46 // Allow SVG in wp_kses_post()
    47 function demo_awesome_allow_svg_in_wp_kses_post( $allowed_post_tags ) {
    48     $allowed_post_tags['svg'] = array(
    49         'xmlns' => true,
    50         'width' => true,
    51         'height' => true,
    52         'viewBox' => true,
    53         'fill' => true,
    54         'class' => true,
    55         'aria-hidden' => true,
    56         'role' => true,
    57         'focusable' => true,
    58         'style' => true,
    59     );
    60     $allowed_post_tags['path'] = array(
    61         'd' => true,
    62         'fill' => true,
    63     );
    64     return $allowed_post_tags;
    65 }
    66 add_filter( 'wp_kses_allowed_html', 'demo_awesome_allow_svg_in_wp_kses_post', 10, 1 );
     46// Security: SVG support removed due to XSS vulnerability
     47// SVG files can contain malicious JavaScript and are not safe for upload
     48// Use PNG, JPG, or other safe image formats instead
    6749
    6850
  • demo-awesome/trunk/inc/admin/class-demo-awesome-admin.php

    r3081092 r3813524  
    99 */
    1010
     11// Exit if accessed directly.
     12if (!defined('ABSPATH')) {
     13    exit;
     14}
     15
    1116if (!defined('DEMO_AWESOME_IMPORTER_FOLDER')) {
    1217    define('DEMO_AWESOME_IMPORTER_FOLDER', '/demo-awesome-import/');
    … …  
    4853            add_action('wp_loaded', array($this, 'hide_notice'));
    4954            add_filter(
    50                 'customizer_demo_import_settings',
     55                'demo_awesome_customizer_import_settings',
    5156                array(
    5257                    $this,
    … …  
    5661                2
    5762            );
    58             add_filter('widget_demo_import_settings', array($this, 'update_widget_data'), 10, 4);
    59 
    60             if (isset($_GET['hide-notice']) && $_GET['hide-notice'] == 'demo_awesome_no_theme4press_theme_notice') {
     63            add_filter('demo_awesome_widget_import_settings', array($this, 'update_widget_data'), 10, 4);
     64
     65            if (isset($_GET['hide-notice'])
     66                && 'demo_awesome_no_theme4press_theme_notice' === sanitize_text_field(wp_unslash($_GET['hide-notice']))
     67                && isset($_GET['_demo_awesome_notice'])
     68                && wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['_demo_awesome_notice'])), 'demo_awesome_hide_notice')
     69                && current_user_can('edit_theme_options')) {
    6170                update_option('demo_awesome_no_theme4press_theme_notice', 0);
    6271            }
    … …  
    8594        public static function hide_notice()
    8695        {
    87             if (isset($_GET['demo-awesome-hide-notice']) && $_GET['demo-awesome-hide-notice'] == 'activation_notice') {
    88                 if (!wp_verify_nonce($_GET['_demo_awesome_notice'], 'demo_awesome_hide_notice')) {
    89                     wp_die(__('Action failed. Please refresh the page and retry.', 'evolve'));
     96            if (isset($_GET['demo-awesome-hide-notice']) && 'activation_notice' === sanitize_text_field(wp_unslash($_GET['demo-awesome-hide-notice']))) {
     97                $notice_nonce = isset($_GET['_demo_awesome_notice']) ? sanitize_text_field(wp_unslash($_GET['_demo_awesome_notice'])) : '';
     98                if (!wp_verify_nonce($notice_nonce, 'demo_awesome_hide_notice')) {
     99                    wp_die(esc_html__('Action failed. Please refresh the page and retry.', 'demo-awesome'));
    90100                }
    91101
    92102                if (!current_user_can('manage_options')) {
    93                     wp_die(__('Cheatin&#8217; huh?', 'evolve'));
    94                 }
    95 
    96                 $hide_notice = sanitize_text_field($_GET['demo-awesome-hide-notice']);
     103                    wp_die(esc_html__('Cheatin&#8217; huh?', 'demo-awesome'));
     104                }
     105
     106                $hide_notice = sanitize_text_field(wp_unslash($_GET['demo-awesome-hide-notice']));
    97107                update_option('demo_awesome_'.$hide_notice, 1);
    98108            }
    … …  
    112122        function get_demo_packages($url, $template_name = '', $save_cache = true)
    113123        {
    114             $packages = '';
    115             $decode_url = base64_encode($url);
    116             if (true || false === ($create_time = get_transient('demo_awesome_importer_packages_'.$decode_url))) {
    117                 $raw_packages = wp_safe_remote_get($url);
    118                 if (!is_wp_error($raw_packages)) {
    119                     $packages = wp_remote_retrieve_body($raw_packages);
    120                     if ($packages) {
    121                         set_transient('demo_awesome_importer_packages_'.$decode_url, time(), HOUR_IN_SECONDS);
    122                         $this->write_file_to_local($packages, $decode_url.'.txt');
     124            // Security: Validate URL
     125            if (!$this->validate_external_url($url)) {
     126                return false;
     127            }
     128
     129            // Cache file name and transient key are derived from an md5 of the URL. (They used to
     130            // be base64, whose "=" padding was stripped when writing the file but not when reading
     131            // it, so every cached read of such a URL failed.)
     132            $cache_key = md5($url);
     133            $transient = 'demo_awesome_importer_packages_'.$cache_key;
     134            $cache_file = $cache_key.'.txt';
     135
     136            // Use the cached copy if it is fresh and still valid; otherwise download again.
     137            if (false !== get_transient($transient)) {
     138                $file_path = wp_upload_dir()['basedir'].DEMO_AWESOME_IMPORTER_FOLDER.$cache_file;
     139                if (file_exists($file_path) && is_readable($file_path)) {
     140                    $packages = file_get_contents($file_path);
     141                    if ($packages && $this->validate_response_content($packages)) {
     142                        return $packages;
    123143                    }
    124144                }
    125             } else {
    126                 $packages = file_get_contents(
    127                     wp_upload_dir()['basedir'].DEMO_AWESOME_IMPORTER_FOLDER.$decode_url.'.txt'
    128                 );
     145            }
     146
     147            // Security: Use wp_safe_remote_get with proper args
     148            $raw_packages = wp_safe_remote_get($url, array(
     149                'timeout' => 30,
     150                'redirection' => 3,
     151                'user-agent' => 'Demo Awesome Plugin',
     152                'sslverify' => true,
     153                'headers' => array(
     154                    'Accept' => 'application/json, text/plain, */*',
     155                )
     156            ));
     157
     158            if (is_wp_error($raw_packages) || wp_remote_retrieve_response_code($raw_packages) !== 200) {
     159                return false;
     160            }
     161
     162            $packages = wp_remote_retrieve_body($raw_packages);
     163
     164            // Security: Validate response content
     165            if (!$packages || !$this->validate_response_content($packages)) {
     166                return false;
     167            }
     168
     169            // Only mark the cache as fresh if the copy was actually written.
     170            if ($this->write_file_to_local($packages, $cache_file)) {
     171                set_transient($transient, time(), HOUR_IN_SECONDS);
    129172            }
    130173
    131174            return $packages;
     175        }
     176
     177        /**
     178         * Validate external URL to prevent SSRF attacks
     179         * @since 1.0.3
     180         */
     181        private function validate_external_url($url) {
     182            // Check if URL is valid
     183            if (!filter_var($url, FILTER_VALIDATE_URL)) {
     184                return false;
     185            }
     186           
     187            $parsed_url = wp_parse_url($url);
     188           
     189            // Check if URL has required components
     190            if (!isset($parsed_url['scheme']) || !isset($parsed_url['host'])) {
     191                return false;
     192            }
     193           
     194            // Only allow HTTPS
     195            if ($parsed_url['scheme'] !== 'https') {
     196                return false;
     197            }
     198           
     199            // Whitelist allowed hosts
     200            $allowed_hosts = ['demo.theme4press.com'];
     201            if (!in_array($parsed_url['host'], $allowed_hosts)) {
     202                return false;
     203            }
     204           
     205            // Check for localhost/private IP attempts
     206            $ip = gethostbyname($parsed_url['host']);
     207            if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false) {
     208                return false;
     209            }
     210           
     211            return true;
     212        }
     213
     214        /**
     215         * Validate response content from external requests
     216         * @since 1.0.3
     217         */
     218        private function validate_response_content($content) {
     219            // Check for empty content
     220            if (empty($content)) {
     221                return false;
     222            }
     223           
     224            // Check content length (prevent DoS). Same limit as validate_file_content().
     225            if (strlen($content) > 50 * 1024 * 1024) {
     226                return false;
     227            }
     228
     229            // No keyword filtering here: every response is cached and written through
     230            // write_file_to_local(), which validates it per file type (XML/JSON/serialized/ZIP)
     231            // and rejects PHP code. Blocking "<script", "javascript:" or "data:" rejected
     232            // legitimate demo content (e.g. cached Twitter/YouTube embeds in post meta),
     233            // which WordPress itself stores and imports as normal content.
     234            return true;
     235        }
     236
     237        /**
     238         * Whether a downloaded file contains a PHP opening tag.
     239         * Demo data never legitimately contains PHP code.
     240         * @since 1.0.6
     241         */
     242        private function contains_php_code($content) {
     243            return (bool) preg_match('/<\?php|<\?=/i', $content);
    132244        }
    133245
    … …  
    164276        function write_file_to_local($file_content, $file_name = 'content.xml')
    165277        {
     278            // Security: Validate and sanitize filename
     279            $file_name = $this->validate_and_sanitize_filename($file_name);
     280            if (!$file_name) {
     281                return false;
     282            }
     283
     284            // Security: Validate file content
     285            if (!$this->validate_file_content($file_content, $file_name)) {
     286                return false;
     287            }
    166288
    167289            global $wp_filesystem;
    … …  
    171293                WP_Filesystem();
    172294            }
     295           
    173296            $upload_dir = wp_upload_dir()['basedir'].DEMO_AWESOME_IMPORTER_FOLDER;
    174297            if (!is_dir($upload_dir)) {
    175                 mkdir($upload_dir, 0755);
    176             }
     298                // wp_mkdir_p() applies the correct, WordPress-managed directory permissions (FS_CHMOD_DIR).
     299                wp_mkdir_p($upload_dir);
     300            }
     301           
    177302            $file_path = $upload_dir.$file_name;
     303           
     304            // Security: Additional path validation
     305            $real_upload_dir = realpath($upload_dir);
     306            $real_file_path = realpath(dirname($file_path));
     307            if ($real_file_path === false || strpos($real_file_path, $real_upload_dir) !== 0) {
     308                return false;
     309            }
     310           
    178311            $result = $wp_filesystem->put_contents(
    179312                $file_path,
    … …  
    182315            );
    183316
    184             return $file_path;
     317            return $result ? $file_path : false;
     318        }
     319
     320        /**
     321         * Validate and sanitize filename to prevent path traversal and malicious files
     322         * @since 1.0.3
     323         */
     324        private function validate_and_sanitize_filename($filename) {
     325            // Remove any path components
     326            $filename = basename($filename);
     327           
     328            // Check for empty filename
     329            if (empty($filename)) {
     330                return false;
     331            }
     332           
     333            // Check for path traversal attempts
     334            if (strpos($filename, '..') !== false || strpos($filename, '/') !== false || strpos($filename, '\\') !== false) {
     335                return false;
     336            }
     337           
     338            // Check for null bytes
     339            if (strpos($filename, "\0") !== false) {
     340                return false;
     341            }
     342           
     343            // Sanitize filename
     344            $filename = sanitize_file_name($filename);
     345           
     346            // Validate file extension
     347            $allowed_extensions = array('xml', 'dat', 'wie', 'zip', 'txt', 'json');
     348            $file_extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
     349           
     350            if (!in_array($file_extension, $allowed_extensions)) {
     351                return false;
     352            }
     353           
     354            // Check filename length
     355            if (strlen($filename) > 255) {
     356                return false;
     357            }
     358           
     359            return $filename;
     360        }
     361
     362        /**
     363         * Validate file content to prevent malicious uploads
     364         * @since 1.0.3
     365         */
     366        private function validate_file_content($content, $filename) {
     367            // Check for empty content
     368            if (empty($content)) {
     369                return false;
     370            }
     371           
     372            // Check content length (prevent DoS)
     373            if (strlen($content) > 50 * 1024 * 1024) { // 50MB limit
     374                return false;
     375            }
     376           
     377            $file_extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
     378           
     379            // Content validation based on file type
     380            switch ($file_extension) {
     381                case 'xml':
     382                    return $this->validate_xml_content($content);
     383                case 'json':
     384                    return $this->validate_json_content($content);
     385                case 'dat':
     386                    return $this->validate_dat_content($content);
     387                case 'wie':
     388                    return $this->validate_wie_content($content);
     389                case 'zip':
     390                    return $this->validate_zip_content($content);
     391                case 'txt':
     392                    return $this->validate_txt_content($content);
     393                default:
     394                    return false;
     395            }
     396        }
     397
     398        /**
     399         * Validate XML content
     400         * @since 1.0.3
     401         */
     402        private function validate_xml_content($content) {
     403            // Check for PHP code injection
     404            if ($this->contains_php_code($content)) {
     405                return false;
     406            }
     407           
     408            // Basic XML structure validation.
     409            // Security: disable network access and external entity loading to
     410            // prevent XXE and entity-expansion (billion laughs) attacks. Never
     411            // use LIBXML_NOENT/LIBXML_DTDLOAD here, they enable the very attacks
     412            // this check is meant to guard against.
     413            if (PHP_VERSION_ID < 80000 && function_exists('libxml_disable_entity_loader')) {
     414                $previous_loader = libxml_disable_entity_loader(true);
     415            }
     416            $previous_errors = libxml_use_internal_errors(true);
     417
     418            $dom    = new DOMDocument();
     419            $loaded = $dom->loadXML($content, LIBXML_NONET);
     420
     421            libxml_clear_errors();
     422            libxml_use_internal_errors($previous_errors);
     423            if (PHP_VERSION_ID < 80000 && function_exists('libxml_disable_entity_loader') && isset($previous_loader)) {
     424                libxml_disable_entity_loader($previous_loader);
     425            }
     426
     427            return $loaded !== false;
     428        }
     429
     430        /**
     431         * Validate JSON content
     432         * @since 1.0.3
     433         */
     434        private function validate_json_content($content) {
     435            // Check for PHP code injection
     436            if ($this->contains_php_code($content)) {
     437                return false;
     438            }
     439           
     440            $decoded = json_decode($content, true);
     441            return json_last_error() === JSON_ERROR_NONE;
     442        }
     443
     444        /**
     445         * Validate DAT content (serialized data)
     446         * @since 1.0.3
     447         */
     448        private function validate_dat_content($content) {
     449            // Check for PHP code injection
     450            if ($this->contains_php_code($content)) {
     451                return false;
     452            }
     453           
     454            // Basic validation for serialized data. Disable object instantiation
     455            // so the validation step itself cannot trigger PHP object injection.
     456            if (!is_serialized($content)) {
     457                return false;
     458            }
     459            $unserialized = unserialize(trim($content), array('allowed_classes' => false));
     460            return $unserialized !== false;
     461        }
     462
     463        /**
     464         * Validate WIE content (widget import/export)
     465         * @since 1.0.3
     466         */
     467        private function validate_wie_content($content) {
     468            // Check for PHP code injection
     469            if ($this->contains_php_code($content)) {
     470                return false;
     471            }
     472           
     473            $decoded = json_decode($content, true);
     474            return json_last_error() === JSON_ERROR_NONE;
     475        }
     476
     477        /**
     478         * Validate ZIP content
     479         * @since 1.0.3
     480         */
     481        private function validate_zip_content($content) {
     482            // Check ZIP file signature
     483            if (substr($content, 0, 2) !== 'PK') {
     484                return false;
     485            }
     486           
     487            // Additional ZIP validation could be added here
     488            return true;
     489        }
     490
     491        /**
     492         * Validate TXT content
     493         * @since 1.0.3
     494         */
     495        private function validate_txt_content($content) {
     496            // Check for PHP code injection
     497            if ($this->contains_php_code($content)) {
     498                return false;
     499            }
     500           
     501            return true;
    185502        }
    186503
    … …  
    217534
    218535        /**
     536         * Enhanced validation and sanitization for demo data
     537         * @since 1.0.3
     538         */
     539        private function validate_and_sanitize_demo_data($data) {
     540            if (!is_array($data)) {
     541                return false;
     542            }
     543
     544            $allowed_keys = array(
     545                'folder_path', 'name', 'premium_demo', 'has_theme4press_slider_data',
     546                'has_slider_revolution_data', 'has_layerslider_data', 'plugins',
     547                'option_update', 'update_galleries', 'customizer_data_update',
     548                'widgets_data_update', 'require_ver_premium', 'require_ver_free'
     549            );
     550
     551            $sanitized_data = array();
     552           
     553            foreach ($data as $key => $value) {
     554                // Only allow whitelisted keys
     555                if (!in_array($key, $allowed_keys)) {
     556                    continue;
     557                }
     558
     559                if (is_array($value)) {
     560                    $sanitized_data[$key] = $this->sanitize_nested_array($value);
     561                } else {
     562                    $sanitized_data[$key] = sanitize_text_field($value);
     563                }
     564            }
     565
     566            return $sanitized_data;
     567        }
     568
     569        /**
     570         * Validate template name to prevent directory traversal
     571         * @since 1.0.3
     572         */
     573        private function validate_template_name($template_name) {
     574            if (empty($template_name)) {
     575                return false;
     576            }
     577
     578            // Check length
     579            if (strlen($template_name) > 100) {
     580                return false;
     581            }
     582
     583            // Demo folders are "<category>/<number>" (e.g. "business/1"), so one "/" between
     584            // two safe segments is allowed. The whitelist excludes "..", backslashes, null
     585            // bytes, leading/trailing slashes and anything else that could leave the demo folder.
     586            return (bool) preg_match('#^[a-zA-Z0-9_-]+(/[a-zA-Z0-9_-]+)?$#', $template_name);
     587        }
     588
     589        /**
     590         * Look up the demo the user picked in the demo list downloaded from the demo server.
     591         *
     592         * The browser only identifies the demo by its "index". Everything else (folder, required
     593         * plugins, options to update, slider flags) comes from the server-side list, never from
     594         * the request, so a forged request cannot change what gets downloaded or which options
     595         * get written.
     596         *
     597         * @since 1.0.6
     598         * @return array|false Normalized demo data, or false if the demo is not in the list.
     599         */
     600        private function get_requested_demo() {
     601            // Only called from AJAX handlers that verify the 'demo-awesome' nonce and the
     602            // manage_options capability before calling this method.
     603            // phpcs:disable WordPress.Security.NonceVerification.Missing
     604            $index = '';
     605            if (isset($_POST['demo_index'])) {
     606                $index = sanitize_text_field(wp_unslash($_POST['demo_index']));
     607            } elseif (isset($_POST['data_demo']['index'])) {
     608                // Older admin.js sends the whole demo object; only its index is used.
     609                $index = sanitize_text_field(wp_unslash($_POST['data_demo']['index']));
     610            }
     611            // phpcs:enable WordPress.Security.NonceVerification.Missing
     612            if ($index === '' || !preg_match('/^[0-9]+$/', $index)) {
     613                return false;
     614            }
     615
     616            $list = json_decode((string) $this->get_list_demos(), true);
     617            if (!is_array($list)) {
     618                return false;
     619            }
     620            foreach ($list as $category) {
     621                if (empty($category['items']) || !is_array($category['items'])) {
     622                    continue;
     623                }
     624                foreach ($category['items'] as $item) {
     625                    if (isset($item['index']) && (string) $item['index'] === $index) {
     626                        return $this->normalize_demo_data($item);
     627                    }
     628                }
     629            }
     630
     631            return false;
     632        }
     633
     634        /**
     635         * Fill in optional demo fields so later code can rely on them being set, and map the
     636         * demo list's "has_LayerSlider WP_data" key to the "has_layerslider_data" key used here.
     637         *
     638         * @since 1.0.6
     639         */
     640        private function normalize_demo_data($demo) {
     641            if (isset($demo['has_LayerSlider WP_data']) && !isset($demo['has_layerslider_data'])) {
     642                $demo['has_layerslider_data'] = $demo['has_LayerSlider WP_data'];
     643            }
     644            $defaults = array(
     645                'premium_demo' => false,
     646                'has_theme4press_slider_data' => false,
     647                'has_slider_revolution_data' => false,
     648                'has_layerslider_data' => false,
     649                'plugins' => array(),
     650                'option_update' => array(),
     651                'update_galleries' => array(),
     652                'customizer_data_update' => array(),
     653                'widgets_data_update' => array(),
     654            );
     655
     656            return $this->validate_and_sanitize_demo_data(array_merge($defaults, $demo));
     657        }
     658
     659        /**
     660         * Validate plugin name to prevent malicious plugin installation
     661         * @since 1.0.3
     662         */
     663        private function validate_plugin_name($plugin_name) {
     664            if (empty($plugin_name)) {
     665                return false;
     666            }
     667
     668            // Check for path traversal attempts
     669            if (strpos($plugin_name, '..') !== false ||
     670                strpos($plugin_name, '/') !== false ||
     671                strpos($plugin_name, '\\') !== false) {
     672                return false;
     673            }
     674
     675            // Check for null bytes
     676            if (strpos($plugin_name, "\0") !== false) {
     677                return false;
     678            }
     679
     680            // Check length
     681            if (strlen($plugin_name) > 100) {
     682                return false;
     683            }
     684
     685            // Only allow alphanumeric, hyphens, underscores, and spaces (covers both
     686            // plugin slugs and display names). The capability check
     687            // (install_plugins / activate_plugins) is the real authorization gate;
     688            // this only rejects path traversal, null bytes and regex-unsafe input.
     689            if (!preg_match('/^[a-zA-Z0-9_\- ]+$/', $plugin_name)) {
     690                return false;
     691            }
     692
     693            return true;
     694        }
     695
     696        /**
    219697         * @since    1.0.0
    220698         */
    221699        function call_import_function_from_ajax()
    222700        {
    223             if ( !wp_verify_nonce( $_POST['nonce'] ?? '', 'demo-awesome' ) ) {
    224                 wp_send_json_error( 'Invalid nonce' );
     701            // Security: Enhanced nonce verification
     702            if ( !wp_verify_nonce( isset($_POST['_nonce']) ? sanitize_text_field(wp_unslash($_POST['_nonce'])) : '', 'demo-awesome' ) ) {
     703                wp_send_json_error( array(
     704                    'message' => 'Security check failed. Please refresh the page and try again.',
     705                    'code' => 'invalid_nonce'
     706                ));
    225707                wp_die();
    226708            }
    227709
     710            // Security: Enhanced capability check
    228711            if ( !current_user_can('manage_options') ) {
    229                 wp_die('You do not have sufficient permissions to access this feature.');
    230             }       
    231             $data_demo_raw = isset($_REQUEST['data_demo']) ? $_REQUEST['data_demo'] : array();
    232             $data_demo = array();
    233 
    234             // Sanitize the data
    235             if (is_array($data_demo_raw)) {
    236                 $data_demo = $this->sanitize_nested_array($data_demo_raw);
    237             } else {
    238                 $data_demo = esc_attr($data_demo_raw);
     712                wp_send_json_error( array(
     713                    'message' => 'You do not have sufficient permissions to access this feature.',
     714                    'code' => 'insufficient_permissions'
     715                ));
     716                wp_die();
     717            }
     718
     719            // Security: the demo is looked up by index in the server-side demo list; no other
     720            // request data is used.
     721            $data_demo = $this->get_requested_demo();
     722            if ($data_demo === false) {
     723                wp_send_json_error( array(
     724                    'message' => esc_html__('The selected demo could not be found in the demo list. Please reload the page and try again. If it keeps happening, the demo server may be unreachable.', 'demo-awesome'),
     725                    'code' => 'demo_not_found'
     726                ));
     727                wp_die();
    239728            }
    240729
    241730            $template_name = isset($data_demo['folder_path']) ? $data_demo['folder_path'] : '';
    242731
    243             $this->remove_old_datas($data_demo, $template_name);
    244 
     732            // Security: Validate template name
     733            if (!$this->validate_template_name($template_name)) {
     734                wp_send_json_error( array(
     735                    'message' => esc_html__('Invalid demo folder.', 'demo-awesome'),
     736                    'code' => 'invalid_template'
     737                ));
     738                wp_die();
     739            }
     740
     741            // Check this before remove_old_datas(): refusing a premium demo must not
     742            // first wipe the site's theme settings, menus and widgets.
    245743            if (Demo_Awesome_Admin::is_premium_theme() == false && $data_demo['premium_demo']) {
    246                 wp_send_json_success(
     744                wp_send_json_error(
    247745                    array(
    248                         'success' => true,
    249                         'message' => sprintf(
    250                             '<span>%s</span>',
    251                             esc_html__('The premium demo requires the premium theme version', 'demo-awesome')
    252                         ),
     746                        'message' => esc_html__('The premium demo requires the premium theme version', 'demo-awesome'),
     747                        'code' => 'premium_required'
    253748                    )
    254749                );
    255750                wp_die();
    256751            }
     752
     753            // Download and validate the demo content before removing anything, so a failed
     754            // download leaves the site untouched. The file is cached, so the import step below
     755            // reuses it instead of downloading it again.
     756            if (!$this->get_import_file_path($template_name)) {
     757                wp_send_json_error( array(
     758                    'message' => esc_html__('The demo content could not be downloaded from the demo server, or it failed validation. Nothing on your site was changed. Please try again later.', 'demo-awesome'),
     759                    'code' => 'download_failed'
     760                ));
     761                wp_die();
     762            }
     763
     764            $this->remove_old_datas($data_demo, $template_name);
    257765            // Import content data
    258766            $this->import_content_theme($data_demo, $template_name);
    … …  
    343851        function required_plugins()
    344852        {
     853            // Security: Enhanced nonce verification
     854            if (!wp_verify_nonce(isset($_POST['_nonce']) ? sanitize_text_field(wp_unslash($_POST['_nonce'])) : '', 'demo-awesome')) {
     855                wp_die(esc_html__('Security check failed.', 'demo-awesome'));
     856            }
     857           
     858            // Security: Enhanced capability check
     859            if (!current_user_can('manage_options')) {
     860                wp_die(esc_html__('You do not have sufficient permissions.', 'demo-awesome'));
     861            }
     862
     863           
    345864            // Include the required plugins list
    346865            require dirname(__FILE__).'/required-plugins.php';
    347             $data_demo_raw = isset($_REQUEST['data_demo']) ? $_REQUEST['data_demo'] : array();
    348             $data_demo = array();
    349            
    350             //TODO (EvgenyViner): Look for a more elegant way to sanitize the data
    351 
    352             if (is_array($data_demo_raw)) {
    353                 foreach($data_demo_raw as $key => $item) {
    354                     if(is_array($data_demo_raw[$key])) {
    355                         foreach($data_demo_raw[$key] as $key2 => $item2) {
    356                             if(is_array($data_demo_raw[$key][$key2])) {
    357                                 foreach($data_demo_raw[$key][$key2] as $key3 => $item3) {
    358                                     $data_demo[$key][$key2][$key3] = esc_attr($item3);
    359                                 }
    360                             }
    361                             else $data_demo[$key][$key2] = esc_attr($item2);
    362                         }
    363                     }
    364                     else $data_demo[$key] = esc_attr($item);
    365                 }
    366             }
    367                 else {
    368                     $data_demo = htmlspecialchars((string)$data_demo_raw, ENT_QUOTES, 'UTF-8');
    369                 }
    370            
     866            // Security: the demo (and so its required-plugin list) comes from the server-side
     867            // demo list, looked up by index; no other request data is used.
     868            $data_demo = $this->get_requested_demo();
     869            if ($data_demo === false) {
     870                wp_die(esc_html__('The selected demo could not be found in the demo list. Please reload the page and try again.', 'demo-awesome'));
     871            }
     872
    371873            demo_awesome_required_plugins($data_demo);
    372874            wp_die(); // this is required to terminate immediately and return a proper response
    … …  
    375877        function evole_activate_plugin()
    376878        {
    377             $plugin = $_POST['plugin'];
     879            // Security: Enhanced nonce verification
     880            if (!wp_verify_nonce(isset($_POST['_nonce']) ? sanitize_text_field(wp_unslash($_POST['_nonce'])) : '', 'demo-awesome')) {
     881                wp_die(esc_html__('Security check failed.', 'demo-awesome'));
     882            }
     883   
     884            // Security: Enhanced capability check
     885            if (!current_user_can('activate_plugins')) {
     886                wp_die(esc_html__('Sorry, you are not allowed to activate plugins on this site.', 'demo-awesome'));
     887            }
     888
     889           
     890            // Security: Validate and sanitize plugin name
     891            $plugin = isset($_POST['plugin']) ? sanitize_text_field(wp_unslash($_POST['plugin'])) : '';
     892            if (!$this->validate_plugin_name($plugin)) {
     893                wp_die(esc_html__('Invalid plugin name provided.', 'demo-awesome'));
     894            }
     895           
    378896            $activate = isset($_POST['activate']) ? true : false;
    379897
    380898            if ($activate == false) {
    381899                if ($plugin == 'LayerSlider WP') {
    382                     evolve_get_update_plugin('layerslider');
     900                    if (function_exists('evolve_get_update_plugin')) {
     901                        evolve_get_update_plugin('layerslider');
     902                    }
    383903                    $plugin = 'LayerSlider';
    384904                } elseif ($plugin == 'slider-revolution') {
    385905                    $plugin = 'revslider';
    386906                } else {
    387                     evolve_get_update_plugin($plugin);
    388 
    389                 }
    390 
    391             }
    392             $html = str_replace('Not installed', 'Not active', stripslashes($_POST['html']));
     907                    if (function_exists('evolve_get_update_plugin')) {
     908                        evolve_get_update_plugin($plugin);
     909                    }
     910                }
     911
     912            }
     913            $html_raw = isset($_POST['html']) ? wp_kses_post(wp_unslash($_POST['html'])) : '';
     914            $html = str_replace('Not installed', 'Not active', $html_raw);
     915            // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- 'all_plugins' is a WordPress core filter.
    393916            $all_plugins = apply_filters('all_plugins', get_plugins());
    394917            foreach ($all_plugins as $k => $item) {
    395918
    396                 if (preg_match('#'.$plugin.'#', $k)) {
     919                if (preg_match('#'.preg_quote($plugin, '#').'#', $k)) {
    397920                    activate_plugin($k);
    398921                }
    … …  
    406929
    407930        function install_plugin()
    408         {
    409             $plugin = $_POST['plugin'];
     931        {   
     932            // Security: Enhanced nonce verification
     933            if (!wp_verify_nonce(isset($_POST['_nonce']) ? sanitize_text_field(wp_unslash($_POST['_nonce'])) : '', 'demo-awesome')) {
     934                wp_die(esc_html__('Security check failed.', 'demo-awesome'));
     935            }
     936
     937            // Security: Enhanced capability check
     938            if (!current_user_can('install_plugins')) {
     939                wp_die(esc_html__('Sorry, you are not allowed to install plugins on this site.', 'demo-awesome'));
     940            }
     941
     942
     943            // Security: Validate and sanitize plugin name
     944            $plugin = isset($_POST['plugin']) ? sanitize_text_field(wp_unslash($_POST['plugin'])) : '';
     945            if (!$this->validate_plugin_name($plugin)) {
     946                wp_die(esc_html__('Invalid plugin name provided.', 'demo-awesome'));
     947            }
     948           
    410949            $activate = isset($_POST['activate']) ? true : false;
    411950
    412951            if ($activate == false) {
    413952                if ($plugin == 'LayerSlider WP') {
    414                     evolve_get_update_plugin('layerslider');
     953                    if (function_exists('evolve_get_update_plugin')) {
     954                        evolve_get_update_plugin('layerslider');
     955                    }
    415956                    $plugin = 'LayerSlider';
    416957                } elseif ($plugin == 'slider-revolution') {
    417958                    $plugin = 'revslider';
    418959                } else {
    419                     evolve_get_update_plugin($plugin);
    420 
    421                 }
    422 
    423             }
    424 
     960                    if (function_exists('evolve_get_update_plugin')) {
     961                        evolve_get_update_plugin($plugin);
     962                    }
     963                }
     964
     965            }
     966
     967            // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- 'all_plugins' is a WordPress core filter.
    425968            $all_plugins = apply_filters('all_plugins', get_plugins());
    426969
    427970            foreach ($all_plugins as $k => $item) {
    428971
    429                 if (preg_match('#'.$plugin.'#', $k)) {
     972                if (preg_match('#'.preg_quote($plugin, '#').'#', $k)) {
    430973                    activate_plugin($k);
    431974                }
    432975            }
    433             $html = str_replace('Not installed', 'Not active', stripslashes($_POST['html']));
     976            $html_raw = isset($_POST['html']) ? wp_kses_post(wp_unslash($_POST['html'])) : '';
     977            $html = str_replace('Not installed', 'Not active', $html_raw);
    434978
    435979            echo wp_kses_post($html);
    … …  
    452996
    453997        /**
     998         * Determine whether an option name is too sensitive to be written from
     999         * remote demo data (prevents privilege escalation / takeover if the demo
     1000         * source is ever compromised or spoofed).
     1001         *
     1002         * @since 1.0.5
     1003         */
     1004        private function is_protected_option($option_name)
     1005        {
     1006            $protected = array(
     1007                'users_can_register', 'default_role', 'siteurl', 'home',
     1008                'admin_email', 'new_admin_email', 'template', 'stylesheet',
     1009                'active_plugins', 'mailserver_url', 'mailserver_login',
     1010                'mailserver_pass', 'mailserver_port', 'cron', 'rewrite_rules',
     1011                'ftp_credentials', 'auth_key', 'auth_salt', 'secret',
     1012                'db_version', 'WPLANG', 'fileupload_url',
     1013            );
     1014
     1015            return in_array($option_name, $protected, true);
     1016        }
     1017
     1018        /**
     1019         * Deprecation-safe replacement for get_page_by_title() (removed/deprecated
     1020         * in modern WordPress). Returns the first matching post object or null.
     1021         *
     1022         * @since 1.0.5
     1023         */
     1024        private function get_page_by_title_compat($title, $post_type = 'page')
     1025        {
     1026            $args = array(
     1027                'post_type'              => $post_type,
     1028                'title'                  => $title,
     1029                'posts_per_page'         => 1,
     1030                'no_found_rows'          => true,
     1031                'ignore_sticky_posts'    => true,
     1032                'update_post_term_cache' => false,
     1033                'update_post_meta_cache' => false,
     1034                'orderby'                => 'post_date ID',
     1035                'order'                  => 'ASC',
     1036            );
     1037
     1038            if ('attachment' === $post_type) {
     1039                $args['post_status'] = 'inherit';
     1040            }
     1041
     1042            $query = new WP_Query($args);
     1043
     1044            return !empty($query->posts) ? $query->posts[0] : null;
     1045        }
     1046
     1047        /**
    4541048         * @since    1.0.0
    4551049         */
    … …  
    4601054                    if ($data_type == 'update_pages' && $data_value && is_array($data_value) && count($data_value)) {
    4611055                        foreach ($data_value as $option_name => $option_value) {
    462                             $page = get_page_by_title($option_value);
     1056                            // Security: never let demo data target a protected option.
     1057                            if ($this->is_protected_option($option_name)) {
     1058                                continue;
     1059                            }
     1060                            $page = $this->get_page_by_title_compat($option_value);
    4631061                            if (is_object($page) && $page->ID) {
    4641062                                update_option($option_name, $page->ID);
    … …  
    4661064                        }
    4671065                    } else {
     1066                        // Security: never let demo data target a protected option.
     1067                        if ($this->is_protected_option($data_type)) {
     1068                            continue;
     1069                        }
    4681070                        update_option($data_type, $data_value);
    4691071                    }
    … …  
    4801082                foreach ($data_demo['update_galleries']['pages'] as $data_value) {
    4811083                    if (!empty($data_value['title'])) {
    482                         $page = get_page_by_title($data_value['title']);
     1084                        $page = $this->get_page_by_title_compat($data_value['title']);
    4831085                        if (is_object($page) && $page->ID) {
    4841086                            foreach ($data_value['items'] as $shortcode_values) {
    … …  
    4871089                                $new_ids = array();
    4881090                                foreach ($ids as $id_key => $id) {
    489                                     $attach = get_page_by_title($names[$id_key], OBJECT, 'attachment');
     1091                                    $attach = $this->get_page_by_title_compat($names[$id_key], 'attachment');
    4901092                                    if (is_object($attach) && $attach->ID) {
    4911093                                        $new_ids[] = $attach->ID;
    … …  
    5341136
    5351137            // Include Class Demo Awesome Importer
    536             require dirname(__FILE__).'/importer/class-demo-awesome-importer.php';
     1138            require_once dirname(__FILE__).'/importer/class-demo-awesome-importer.php';
    5371139
    5381140            if (is_file($import_file)) {
    … …  
    7031305                        foreach ($menu_items as $menu_item) {
    7041306                            if (isset($menu_item->url) && isset($menu_item->db_id) && 'custom' == $menu_item->type) {
    705                                 $site_parts = parse_url(home_url('/'));
    706                                 $menu_parts = parse_url($menu_item->url);
     1307                                $site_parts = wp_parse_url(home_url('/'));
     1308                                $menu_parts = wp_parse_url($menu_item->url);
    7071309
    7081310                                // Update existing custom nav menu item URL.
    … …  
    7551357                            foreach ($data_value as $option_key => $option_value) {
    7561358                                if (!empty($data['mods'][$option_key])) {
    757                                     $page = get_page_by_title($option_value);
     1359                                    $page = $this->get_page_by_title_compat($option_value);
    7581360
    7591361                                    if (is_object($page) && $page->ID) {
    … …  
    8251427                                if (!empty($widget_data[$instance_id]) && $widget_id == $widget_type) {
    8261428                                    foreach ($widget_data[$instance_id] as $widget_key => $widget_value) {
    827                                         $page = get_page_by_title($widget_value);
     1429                                        $page = $this->get_page_by_title_compat($widget_value);
    8281430
    8291431                                        if (is_object($page) && $page->ID) {
    … …  
    8861488            }
    8871489
    888             wp_enqueue_style('demo-awesome-notice', plugin_dir_url(__FILE__).'css/notice.css'); ?>
     1490            wp_enqueue_style('demo-awesome-notice', plugin_dir_url(__FILE__).'css/notice.css', array(), $this->version); ?>
    8891491
    8901492            <div class="notice demo-awesome-notice is-dismissible">
    8911493                <p>
    892                     <img src="<?php echo esc_url(plugin_dir_url(__FILE__)); ?>images/logo.png"/><?php echo sprintf(
     1494                    <img src="<?php echo esc_url(plugin_dir_url(__FILE__)); ?>images/logo.png"/>
     1495                    <?php
     1496                    echo wp_kses_post( sprintf(
     1497                        /* translators: 1: opening <strong> tag, 2: closing </strong> tag. */
    8931498                        esc_html__(
    8941499                            'Thank you for installing %1$sDemo Awesome%2$s plugin by Theme4Press. To start importing a demo content please visit the importer page',
    895                             'evolve'
     1500                            'demo-awesome'
    8961501                        ),
    8971502                        '<strong>',
    8981503                        '</strong>'
    899                     ); ?>
     1504                    ) ); ?>
    9001505                    <a class="button"
    9011506                       href="<?php echo esc_url(
    … …  
    9261531            }
    9271532
    928             wp_enqueue_style('demo-awesome-notice', plugin_dir_url(__FILE__).'css/notice.css'); ?>
     1533            wp_enqueue_style('demo-awesome-notice', plugin_dir_url(__FILE__).'css/notice.css', array(), $this->version); ?>
    9291534
    9301535            <div class="notice demo-awesome-notice is-dismissible">
    9311536                <p><?php echo wp_kses_post( Demo_Awesome_Admin::is_theme4press_theme_message()); ?><a
    9321537                            href="<?php echo esc_url(
    933                                 add_query_arg('hide-notice', 'demo_awesome_no_theme4press_theme_notice')
     1538                                wp_nonce_url(
     1539                                    add_query_arg('hide-notice', 'demo_awesome_no_theme4press_theme_notice'),
     1540                                    'demo_awesome_hide_notice',
     1541                                    '_demo_awesome_notice'
     1542                                )
    9341543                            ); ?>"><?php esc_html_e('Dismiss', 'demo-awesome'); ?></a>
    9351544                </p>
    … …  
    9451554            $message = '';
    9461555            if (!Demo_Awesome_Admin::is_theme4press_theme()) {
    947                 $message = "<span><img src='".plugin_dir_url(__FILE__)."images/logo.png' />".sprintf(
     1556                $message = "<span><img src='".esc_url(plugin_dir_url(__FILE__))."images/logo.png' />".sprintf(
     1557                        /* translators: 1,3: opening <strong> tag, 2,4: closing </strong> tag. */
    9481558                        esc_html__(
    9491559                            'The %1$sDemo Awesome%2$s plugin is designed only for %3$sTheme4Press%4$s themes',
    … …  
    10151625
    10161626        /**
     1627         * Allowlist for escaping markup that may contain inline SVG icons (from
     1628         * get_svg()). wp_kses_post() strips <svg>/<use>, so callers pass this list
     1629         * to wp_kses() to permit the icon markup in addition to standard post tags.
     1630         *
     1631         * Usage: echo wp_kses( $html, Demo_Awesome_Admin::allowed_svg_tags() );
     1632         *
     1633         * @since 1.0.5
     1634         * @return array Allowed HTML/SVG tags for wp_kses().
     1635         */
     1636        public static function allowed_svg_tags()
     1637        {
     1638            $svg_tags = array(
     1639                'svg'   => array(
     1640                    'class'           => true,
     1641                    'aria-hidden'     => true,
     1642                    'aria-labelledby' => true,
     1643                    'role'            => true,
     1644                    'xmlns'           => true,
     1645                    'width'           => true,
     1646                    'height'          => true,
     1647                    'viewbox'         => true,
     1648                    'fill'            => true,
     1649                    'focusable'       => true,
     1650                ),
     1651                'g'     => array('fill' => true),
     1652                'title' => array('title' => true),
     1653                'path'  => array('d' => true, 'fill' => true),
     1654                'use'   => array('href' => true, 'xlink:href' => true),
     1655            );
     1656
     1657            return array_merge(wp_kses_allowed_html('post'), $svg_tags);
     1658        }
     1659
     1660        /**
    10171661         * @since    1.0.0
    10181662         */
    … …  
    11071751            }
    11081752
    1109             wp_enqueue_style('demo-awesome', plugin_dir_url(__FILE__).'css/admin.css');
     1753            wp_enqueue_style('demo-awesome', plugin_dir_url(__FILE__).'css/admin.css', array(), $this->version);
    11101754        }
    11111755
    … …  
    11201764            }
    11211765
    1122             wp_enqueue_script('demo-awesome', plugin_dir_url(__FILE__).'js/admin.js');
    1123 
     1766            wp_enqueue_script('demo-awesome', plugin_dir_url(__FILE__).'js/admin.js', array('jquery'), $this->version, true);
     1767         
     1768         
    11241769            $local_variables = array(
    11251770                'close_button' => esc_html__('Close', 'demo-awesome'),
    … …  
    11341779                'is_free_version' => Demo_Awesome_Admin::is_free_theme(),
    11351780                'is_theme4press_theme' => Demo_Awesome_Admin::is_theme4press_theme(),
    1136                 'nonce'    => wp_create_nonce('demo-awesome')
     1781                '_nonce'    => wp_create_nonce('demo-awesome')
    11371782            );
    11381783
  • demo-awesome/trunk/inc/admin/demo-browser.php

    r3081092 r3813524  
    99 */
    1010
     11// Exit if accessed directly.
     12if ( ! defined( 'ABSPATH' ) ) {
     13        exit;
     14}
     15
    1116if ( $demo_awesome_get_list_demos ) {
    1217        $demo_awesome_get_list_demos = json_decode( $demo_awesome_get_list_demos, true );
    … …  
    2631                                    data-filter="<?php echo esc_attr( $demo_awesome_item_key ); ?>"
    2732                                    href="#"
    28                                     aria-selected="false"><?php esc_html_e( $demo_awesome_item['name'] ); ?></a>
     33                                    aria-selected="false"><?php echo esc_html( $demo_awesome_item['name'] ); ?></a>
    2934            </li>
    3035                <?php }
    … …  
    5055                        }
    5156                        $demo_awesome_number_demos = count( $demo_awesome_list_demos );
    52                         for ( $i = 0; $i < $demo_awesome_number_demos; $i ++ ) {
    53                                 $demo_awesome_list_demos_sorted[] = $demo_awesome_list_demos[ $i ];
     57                        for ( $demo_awesome_i = 0; $demo_awesome_i < $demo_awesome_number_demos; $demo_awesome_i ++ ) {
     58                                $demo_awesome_list_demos_sorted[] = $demo_awesome_list_demos[ $demo_awesome_i ];
    5459                        }
    5560                }
    … …  
    8085                        <div class="demo-container">
    8186                            <h2 class="demo-name"
    82                                 id="demo-name"><?php esc_html_e( $demo_awesome_item_2['name'] ); ?></h2>
     87                                id="demo-name"><?php echo esc_html( $demo_awesome_item_2['name'] ); ?></h2>
    8388
    8489                            <div class="demo-actions"
    … …  
    127132                                                <?php esc_html_e( 'Minimum recommended theme version for this demo: ', 'demo-awesome' ); ?><span
    128133                                class="theme-required-version"></span><br/>
    129                         <h3><?php echo  esc_html( sprintf( esc_html__( 'Installed theme version: %s', 'demo-awesome' ), $demo_awesome_my_theme['Version'] )); ?></h3>
     134                        <h3><?php /* translators: %s: the installed theme version number. */ echo esc_html( sprintf( esc_html__( 'Installed theme version: %s', 'demo-awesome' ), $demo_awesome_my_theme->get('Version') )); ?></h3>
    130135
    131136                                                <?php if ( Demo_Awesome_Admin::is_theme4press_theme() ) {
    … …  
    139144                    <div class="wizard-step">
    140145                        <div class="alert" role="alert">
    141                             <span class="mr-1"><?php echo Demo_Awesome_Admin::get_svg( 'warning' ); ?></span><?php echo sprintf( ( '%1$s%2$s%3$s%4$s%5$s%6$s%7$s%8$s%9$s%10$s%11$s%12$s%13$s' ), esc_html__( 'The demo import may overwrite/remove many website options', 'demo-awesome' ), '<br /><br />- ', esc_html__( 'customizer settings', 'demo-awesome' ), '<br />- ', esc_html__( 'menus', 'demo-awesome' ), '<br />- ', esc_html__( 'widgets', 'demo-awesome' ), '<br />- ', esc_html__( 'posts/pages', 'demo-awesome' ), '<br />- ', esc_html__( 'set new front page', 'demo-awesome' ), '<br /><br />', esc_html__( 'Some demos can take few minutes to complete the import, depending on the complexity of the demo content.', 'demo-awesome' ) ); ?>
     146                            <span class="mr-1"><?php echo wp_kses( Demo_Awesome_Admin::get_svg( 'warning' ), Demo_Awesome_Admin::allowed_svg_tags() ); ?></span><?php echo sprintf( ( '%1$s%2$s%3$s%4$s%5$s%6$s%7$s%8$s%9$s%10$s%11$s%12$s%13$s' ), esc_html__( 'The demo import may overwrite/remove many website options', 'demo-awesome' ), '<br /><br />- ', esc_html__( 'customizer settings', 'demo-awesome' ), '<br />- ', esc_html__( 'menus', 'demo-awesome' ), '<br />- ', esc_html__( 'widgets', 'demo-awesome' ), '<br />- ', esc_html__( 'posts/pages', 'demo-awesome' ), '<br />- ', esc_html__( 'set new front page', 'demo-awesome' ), '<br /><br />', esc_html__( 'Some demos can take few minutes to complete the import, depending on the complexity of the demo content.', 'demo-awesome' ) ); ?>
    142147                        </div>
    143148
    … …  
    173178
    174179                    <div class="alert hide-content" role="alert">
    175                         <span class="mr-1"><?php echo Demo_Awesome_Admin::get_svg( 'warning' ); ?></span><?php esc_html_e( 'Please don\'t leave/refresh the page while importing. Some demos can take few minutes to complete the import, depending on the complexity of the demo content', 'demo-awesome' ); ?>
    176                     </div>
    177 
    178                     <h3 class="hide-content"><?php echo '<span class="svg-spin mr-1">' . Demo_Awesome_Admin::get_svg( 'loader' ) . '</span>';
     180                        <span class="mr-1"><?php echo wp_kses( Demo_Awesome_Admin::get_svg( 'warning' ), Demo_Awesome_Admin::allowed_svg_tags() ); ?></span><?php esc_html_e( 'Please don\'t leave/refresh the page while importing. Some demos can take few minutes to complete the import, depending on the complexity of the demo content', 'demo-awesome' ); ?>
     181                    </div>
     182
     183                    <h3 class="hide-content"><?php echo wp_kses( '<span class="svg-spin mr-1">' . Demo_Awesome_Admin::get_svg( 'loader' ) . '</span>', Demo_Awesome_Admin::allowed_svg_tags() );
    179184                                                esc_html_e( 'Importing the demo...', 'demo-awesome' ); ?>
    180185                    </h3>
    181186
    182187                    <div class="alert alert-success alert-message-from-importer hide show-content" role="alert">
    183                         <h3><?php echo '<span class="mr-1">' . Demo_Awesome_Admin::get_svg( 'check' ) . '</span>';
     188                        <h3><?php echo wp_kses( '<span class="mr-1">' . Demo_Awesome_Admin::get_svg( 'check' ) . '</span>', Demo_Awesome_Admin::allowed_svg_tags() );
    184189                                                        esc_html_e( 'Import finished', 'demo-awesome' ); ?>
    185190                        </h3>
    … …  
    191196                <div class="modal-footer hide show-content">
    192197                    <a type="button" class="button back" target="_blank"
    193                        href="<?php echo site_url(); ?>"><?php esc_html_e( 'View Website', 'demo-awesome' ); ?></a>
     198                       href="<?php echo esc_url( site_url() ); ?>"><?php esc_html_e( 'View Website', 'demo-awesome' ); ?></a>
    194199                    <a type="button" class="button back"
    195                        href="<?php echo admin_url( "customize.php" ); ?>"><?php esc_html_e( 'Customize', 'demo-awesome' ); ?></a>
     200                       href="<?php echo esc_url( admin_url( 'customize.php' ) ); ?>"><?php esc_html_e( 'Customize', 'demo-awesome' ); ?></a>
    196201                    <a role="button" class="button button-primary"
    197202                       data-dismiss="modal" href="#"
    … …  
    232237                                                                <?php esc_html_e( 'Minimum recommended theme version for this demo: ', 'demo-awesome' ); ?>
    233238                                <span class="theme-required-version"></span><br/>
    234                                 <h3><?php echo sprintf( esc_html__( 'Installed theme version: %s', 'demo-awesome' ), $demo_awesome_my_theme['Version'] ); ?></h3>
     239                                <h3><?php /* translators: %s: the installed theme version number. */ echo esc_html( sprintf( esc_html__( 'Installed theme version: %s', 'demo-awesome' ), $demo_awesome_my_theme->get('Version') ) ); ?></h3>
    235240                            </div>
    236241
    … …  
    240245                                                        if ( Demo_Awesome_Admin::is_free_theme() ) { ?>
    241246                                <p class="alert alert-info required-premium-text"><span
    242                                             class="mr-1"><?php echo Demo_Awesome_Admin::get_svg( 'info' ); ?></span><span><?php echo sprintf( esc_html__( 'This demo requires the %1$sPremium%2$s version of the theme', 'demo-awesome' ), '<strong>', '</strong>' ); ?></span>
     247                                            class="mr-1"><?php echo wp_kses( Demo_Awesome_Admin::get_svg( 'info' ), Demo_Awesome_Admin::allowed_svg_tags() ); ?></span><span><?php /* translators: 1: opening <strong> tag, 2: closing </strong> tag. */ echo wp_kses_post( sprintf( esc_html__( 'This demo requires the %1$sPremium%2$s version of the theme', 'demo-awesome' ), '<strong>', '</strong>' ) ); ?></span>
    243248                                    <a class="button button-primary demo-name-link-1"
    244249                                       target="_blank"
    … …  
    249254                                                        if ( ! Demo_Awesome_Admin::is_theme4press_theme() ) { ?>
    250255                                <p class="alert alert-info required-premium-text"><span
    251                                             class="mr-1"><?php echo Demo_Awesome_Admin::get_svg( 'info' ); ?></span><?php echo Demo_Awesome_Admin::is_theme4press_theme_message(); ?>
     256                                            class="mr-1"><?php echo wp_kses( Demo_Awesome_Admin::get_svg( 'info' ), Demo_Awesome_Admin::allowed_svg_tags() ); ?></span><?php echo wp_kses_post( Demo_Awesome_Admin::is_theme4press_theme_message() ); ?>
    252257                                </p>
    253258                                                        <?php } ?>
    … …  
    319324                                                                <?php esc_html_e( 'Minimum recommended theme version for this demo: ', 'demo-awesome' ); ?>
    320325                                <span class="theme-required-version"></span><br/>
    321                                 <h3><?php echo sprintf( esc_html__( 'Installed theme version: %s', 'demo-awesome' ), $demo_awesome_my_theme['Version'] ); ?></h3>
     326                                <h3><?php /* translators: %s: the installed theme version number. */ echo esc_html( sprintf( esc_html__( 'Installed theme version: %s', 'demo-awesome' ), $demo_awesome_my_theme->get('Version') ) ); ?></h3>
    322327                            </div>
    323328
    … …  
    327332                                                        if ( Demo_Awesome_Admin::is_free_theme() ) { ?>
    328333                                <p class="alert alert-info required-premium-text"><span
    329                                             class="mr-1"><?php echo Demo_Awesome_Admin::get_svg( 'info' ); ?></span><span><?php echo sprintf( esc_html__( 'This demo requires the %1$sPremium%2$s version of the theme', 'demo-awesome' ), '<strong>', '</strong>' ); ?></span>
     334                                            class="mr-1"><?php echo wp_kses( Demo_Awesome_Admin::get_svg( 'info' ), Demo_Awesome_Admin::allowed_svg_tags() ); ?></span><span><?php /* translators: 1: opening <strong> tag, 2: closing </strong> tag. */ echo wp_kses_post( sprintf( esc_html__( 'This demo requires the %1$sPremium%2$s version of the theme', 'demo-awesome' ), '<strong>', '</strong>' ) ); ?></span>
    330335                                    <a class="button button-primary demo-name-link-2"
    331336                                       target="_blank"
    … …  
    336341                                                        if ( ! Demo_Awesome_Admin::is_theme4press_theme() ) { ?>
    337342                                <p class="alert alert-info required-premium-text"><span
    338                                             class="mr-1"><?php echo wp_kses_post( Demo_Awesome_Admin::get_svg( 'info' )); ?></span>
     343                                            class="mr-1"><?php echo wp_kses( Demo_Awesome_Admin::get_svg( 'info' ), Demo_Awesome_Admin::allowed_svg_tags() ); ?></span>
    339344                                    <?php echo wp_kses_post(Demo_Awesome_Admin::is_theme4press_theme_message()); ?>
    340345                                </p>
  • demo-awesome/trunk/inc/admin/importer/class-demo-awesome-customizer-importer.php

    r2158733 r3813524  
    3232                        global $wp_customize;
    3333
    34                         $data = maybe_unserialize( file_get_contents( $import_file ) );
     34                        // Security: Validate file path and content
     35                        if (!self::validate_import_file($import_file)) {
     36                                return new WP_Error( 'demo_awesome_customizer_import_file_error', esc_html__( 'Invalid import file.', 'demo-awesome' ) );
     37                        }
     38
     39                        $file_content = file_get_contents( $import_file );
     40                        if ($file_content === false) {
     41                                return new WP_Error( 'demo_awesome_customizer_import_file_error', esc_html__( 'Could not read import file.', 'demo-awesome' ) );
     42                        }
     43
     44                        // Security: Validate file content
     45                        if (!self::validate_file_content($file_content)) {
     46                                return new WP_Error( 'demo_awesome_customizer_import_content_error', esc_html__( 'Invalid file content detected.', 'demo-awesome' ) );
     47                        }
     48
     49                        // Security: never instantiate arbitrary PHP objects from the import file.
     50                        // Customizer data is always a serialized array, so unserialize with
     51                        // object instantiation disabled to prevent PHP object injection.
     52                        if ( is_serialized( $file_content ) ) {
     53                                $data = unserialize( trim( $file_content ), array( 'allowed_classes' => false ) );
     54                        } else {
     55                                $data = $file_content;
     56                        }
    3557
    3658                        // Data checks.
    … …  
    4567
    4668                        // Modify settings array.
    47                         $data = apply_filters( 'customizer_demo_import_settings', $data, $data_demo );
     69                        $data = apply_filters( 'demo_awesome_customizer_import_settings', $data, $data_demo );
    4870
    4971                        // Import custom options.
    … …  
    157179                                $id = media_handle_sideload( $file_array, 0 );
    158180
    159                                 // If error storing permanently, unlink.
     181                                // If error storing permanently, delete the temp file.
    160182                                if ( is_wp_error( $id ) ) {
    161                                         @unlink( $file_array['tmp_name'] );
     183                                        wp_delete_file( $file_array['tmp_name'] );
    162184
    163185                                        return $id;
    … …  
    175197                        return $data;
    176198                }
     199
     200                /**
     201                 * Validate import file path and permissions
     202                 * @since 1.0.3
     203                 */
     204                private static function validate_import_file($file_path) {
     205                        // Check if file exists
     206                        if (!file_exists($file_path)) {
     207                                return false;
     208                        }
     209
     210                        // Check if file is readable
     211                        if (!is_readable($file_path)) {
     212                                return false;
     213                        }
     214
     215                        // Check file extension
     216                        $allowed_extensions = array('dat');
     217                        $file_extension = strtolower(pathinfo($file_path, PATHINFO_EXTENSION));
     218                        if (!in_array($file_extension, $allowed_extensions)) {
     219                                return false;
     220                        }
     221
     222                        // Check file size (prevent DoS)
     223                        if (filesize($file_path) > 10 * 1024 * 1024) { // 10MB limit
     224                                return false;
     225                        }
     226
     227                        return true;
     228                }
     229
     230                /**
     231                 * Validate file content for security
     232                 * @since 1.0.3
     233                 */
     234                private static function validate_file_content($content) {
     235                        // Check for empty content
     236                        if (empty($content)) {
     237                                return false;
     238                        }
     239
     240                        // Check content length
     241                        if (strlen($content) > 10 * 1024 * 1024) { // 10MB limit
     242                                return false;
     243                        }
     244
     245                        // Check for malicious content
     246                        if (preg_match('/<\?php|<\?=|<script[^>]*>|javascript:|data:/i', $content)) {
     247                                return false;
     248                        }
     249
     250                        return true;
     251                }
    177252        }
    178253}
  • demo-awesome/trunk/inc/admin/importer/class-demo-awesome-importer.php

    r3081092 r3813524  
    11<?php
    22/**
    3  * Demo Awesome importer based on WordPress importer core
     3 * Vendored copy of the official WordPress Importer (class-wp-import.php), version 0.8.3.
    44 *
    5  * @link       https://theme4press.com/demo-awesome-the-data-importer/
    6  * @since      1.0.0
    7  * @package    Demo Awesome
    8  * @author     Theme4Press
     5 * Upstream: https://wordpress.org/plugins/wordpress-importer/ (SVN tag 0.8.3)
     6 *
     7 * Local modifications (kept intentionally minimal):
     8 *  - Class names prefixed "Demo_Awesome_" to avoid collisions with the official plugin.
     9 *  - Text domain changed to "demo-awesome".
     10 *  - Direct-access guard added.
     11 *  - Backported the object-injection-safe maybe_unserialize() guard from importer 0.9.x
     12 *    and routed all WXR meta unserialization through it.
     13 *
     14 * This is third-party code maintained close to upstream; it is intentionally exempt
     15 * from this plugin's coding-standard checks (see phpcs:ignoreFile below).
     16 *
     17 * @package Demo Awesome
    918 */
    1019
    11 
     20// phpcs:ignoreFile
     21
     22// Exit if accessed directly.
     23if ( ! defined( 'ABSPATH' ) ) {
     24        exit;
     25}
     26
     27// The importer extends the WordPress core importer base class.
    1228if ( ! class_exists( 'WP_Importer' ) ) {
    1329        return;
    1430}
    1531
    16 // Display errors
    17 define( 'IMPORT_DEBUG', false );
    18 
    19 // Include WXR file parsers
    20 require dirname( __FILE__ ) . '/class-demo-awesome-parsers.php';
     32if ( ! defined( 'IMPORT_DEBUG' ) ) {
     33        define( 'IMPORT_DEBUG', false );
     34}
     35
     36// Load the WXR parsers (selector pulls in the SimpleXML/XML/Regex implementations).
     37require_once __DIR__ . '/parsers/class-demo-awesome-parser.php';
    2138
    2239/**
    23  * Demo Awesome importer class
     40 * WordPress Importer class for managing the import process of a WXR file
     41 *
     42 * @package WordPress
     43 * @subpackage Importer
    2444 */
    25 if ( ! class_exists( 'Demo_Awesome_Importer' ) ) {
    26         class Demo_Awesome_Importer extends WP_Importer {
    27                 var $max_wxr_version = 1.2; // max. supported WXR version
    28 
    29                 var $id; // WXR attachment ID
    30 
    31                 // information to import from WXR file
    32                 var $version;
    33                 var $authors = array();
    34                 var $posts = array();
    35                 var $terms = array();
    36                 var $categories = array();
    37                 var $tags = array();
    38                 var $base_url = '';
    39 
    40                 // mappings from old information to new
    41                 var $processed_authors = array();
    42                 var $author_mapping = array();
    43                 var $processed_terms = array();
    44                 var $processed_posts = array();
    45                 var $post_orphans = array();
    46                 var $processed_menu_items = array();
    47                 var $menu_item_orphans = array();
    48                 var $missing_menu_items = array();
    49 
    50                 var $fetch_attachments = false;
    51                 var $url_remap = array();
    52                 var $featured_images = array();
     45
     46/**
     47 * WordPress importer class.
     48 */
     49class Demo_Awesome_Importer extends WP_Importer {
     50        public $max_wxr_version = 1.2; // max. supported WXR version
     51
     52        public $id; // WXR attachment ID
     53
     54        // information to import from WXR file
     55        public $version;
     56        public $authors    = array();
     57        public $posts      = array();
     58        public $terms      = array();
     59        public $categories = array();
     60        public $tags       = array();
     61        public $base_url   = '';
     62
     63        // mappings from old information to new
     64        public $processed_authors    = array();
     65        public $author_mapping       = array();
     66        public $processed_terms      = array();
     67        public $processed_posts      = array();
     68        public $post_orphans         = array();
     69        public $processed_menu_items = array();
     70        public $menu_item_orphans    = array();
     71        public $missing_menu_items   = array();
     72
     73        public $fetch_attachments = false;
     74        public $url_remap         = array();
     75        public $featured_images   = array();
     76
     77        /**
     78         * Registered callback function for the WordPress Importer
     79         *
     80         * Manages the three separate stages of the WXR import process
     81         */
     82        public function dispatch() {
     83                $this->header();
     84
     85                $step = empty( $_GET['step'] ) ? 0 : (int) $_GET['step'];
     86                switch ( $step ) {
     87                        case 0:
     88                                $this->greet();
     89                                break;
     90                        case 1:
     91                                check_admin_referer( 'import-upload' );
     92                                if ( $this->handle_upload() ) {
     93                                        $this->import_options();
     94                                }
     95                                break;
     96                        case 2:
     97                                check_admin_referer( 'import-wordpress' );
     98                                $this->fetch_attachments = ( ! empty( $_POST['fetch_attachments'] ) && $this->allow_fetch_attachments() );
     99                                $this->id                = (int) $_POST['import_id'];
     100                                $file                    = get_attached_file( $this->id );
     101                                set_time_limit( 0 );
     102                                $this->import( $file );
     103                                break;
     104                }
     105
     106                $this->footer();
     107        }
     108
     109        /**
     110         * The main controller for the actual import stage.
     111         *
     112         * @param string $file Path to the WXR file for importing
     113         */
     114        public function import( $file ) {
     115                add_filter( 'import_post_meta_key', array( $this, 'is_valid_meta_key' ) );
     116                add_filter( 'http_request_timeout', array( &$this, 'bump_request_timeout' ) );
     117
     118                $this->import_start( $file );
     119
     120                $this->get_author_mapping();
     121
     122                wp_suspend_cache_invalidation( true );
     123                $this->process_categories();
     124                $this->process_tags();
     125                $this->process_terms();
     126                $this->process_posts();
     127                wp_suspend_cache_invalidation( false );
     128
     129                // update incorrect/missing information in the DB
     130                $this->backfill_parents();
     131                $this->backfill_attachment_urls();
     132                $this->remap_featured_images();
     133
     134                $this->import_end();
     135        }
     136
     137        /**
     138         * Parses the WXR file and prepares us for the task of processing parsed data
     139         *
     140         * @param string $file Path to the WXR file for importing
     141         */
     142        public function import_start( $file ) {
     143                if ( ! is_file( $file ) ) {
     144                        echo '<p><strong>' . __( 'Sorry, there has been an error.', 'demo-awesome' ) . '</strong><br />';
     145                        echo __( 'The file does not exist, please try again.', 'demo-awesome' ) . '</p>';
     146                        $this->footer();
     147                        die();
     148                }
     149
     150                $import_data = $this->parse( $file );
     151
     152                if ( is_wp_error( $import_data ) ) {
     153                        echo '<p><strong>' . __( 'Sorry, there has been an error.', 'demo-awesome' ) . '</strong><br />';
     154                        echo esc_html( $import_data->get_error_message() ) . '</p>';
     155                        $this->footer();
     156                        die();
     157                }
     158
     159                $this->version = $import_data['version'];
     160                $this->get_authors_from_import( $import_data );
     161                $this->posts      = $import_data['posts'];
     162                $this->terms      = $import_data['terms'];
     163                $this->categories = $import_data['categories'];
     164                $this->tags       = $import_data['tags'];
     165                $this->base_url   = esc_url( $import_data['base_url'] );
     166
     167                wp_defer_term_counting( true );
     168                wp_defer_comment_counting( true );
     169
     170                do_action( 'import_start' );
     171        }
     172
     173        /**
     174         * Performs post-import cleanup of files and the cache
     175         */
     176        public function import_end() {
     177                wp_import_cleanup( $this->id );
     178
     179                wp_cache_flush();
     180                foreach ( get_taxonomies() as $tax ) {
     181                        delete_option( "{$tax}_children" );
     182                        _get_term_hierarchy( $tax );
     183                }
     184
     185                wp_defer_term_counting( false );
     186                wp_defer_comment_counting( false );
     187
     188                echo '<p>' . __( 'All done.', 'demo-awesome' ) . ' <a href="' . admin_url() . '">' . __( 'Have fun!', 'demo-awesome' ) . '</a>' . '</p>';
     189                echo '<p>' . __( 'Remember to update the passwords and roles of imported users.', 'demo-awesome' ) . '</p>';
     190
     191                do_action( 'import_end' );
     192        }
     193
     194        /**
     195         * Handles the WXR upload and initial parsing of the file to prepare for
     196         * displaying author import options
     197         *
     198         * @return bool False if error uploading or invalid file, true otherwise
     199         */
     200        public function handle_upload() {
     201                $file = wp_import_handle_upload();
     202
     203                if ( isset( $file['error'] ) ) {
     204                        echo '<p><strong>' . __( 'Sorry, there has been an error.', 'demo-awesome' ) . '</strong><br />';
     205                        echo esc_html( $file['error'] ) . '</p>';
     206                        return false;
     207                } elseif ( ! file_exists( $file['file'] ) ) {
     208                        echo '<p><strong>' . __( 'Sorry, there has been an error.', 'demo-awesome' ) . '</strong><br />';
     209                        printf( __( 'The export file could not be found at <code>%s</code>. It is likely that this was caused by a permissions problem.', 'demo-awesome' ), esc_html( $file['file'] ) );
     210                        echo '</p>';
     211                        return false;
     212                }
     213
     214                $this->id    = (int) $file['id'];
     215                $import_data = $this->parse( $file['file'] );
     216                if ( is_wp_error( $import_data ) ) {
     217                        echo '<p><strong>' . __( 'Sorry, there has been an error.', 'demo-awesome' ) . '</strong><br />';
     218                        echo esc_html( $import_data->get_error_message() ) . '</p>';
     219                        return false;
     220                }
     221
     222                $this->version = $import_data['version'];
     223                if ( $this->version > $this->max_wxr_version ) {
     224                        echo '<div class="error"><p><strong>';
     225                        printf( __( 'This WXR file (version %s) may not be supported by this version of the importer. Please consider updating.', 'demo-awesome' ), esc_html( $import_data['version'] ) );
     226                        echo '</strong></p></div>';
     227                }
     228
     229                $this->get_authors_from_import( $import_data );
     230
     231                return true;
     232        }
     233
     234        /**
     235         * Retrieve authors from parsed WXR data
     236         *
     237         * Uses the provided author information from WXR 1.1 files
     238         * or extracts info from each post for WXR 1.0 files
     239         *
     240         * @param array $import_data Data returned by a WXR parser
     241         */
     242        public function get_authors_from_import( $import_data ) {
     243                if ( ! empty( $import_data['authors'] ) ) {
     244                        $this->authors = $import_data['authors'];
     245                        // no author information, grab it from the posts
     246                } else {
     247                        foreach ( $import_data['posts'] as $post ) {
     248                                $login = sanitize_user( $post['post_author'], true );
     249                                if ( empty( $login ) ) {
     250                                        printf( __( 'Failed to import author %s. Their posts will be attributed to the current user.', 'demo-awesome' ), esc_html( $post['post_author'] ) );
     251                                        echo '<br />';
     252                                        continue;
     253                                }
     254
     255                                if ( ! isset( $this->authors[ $login ] ) ) {
     256                                        $this->authors[ $login ] = array(
     257                                                'author_login'        => $login,
     258                                                'author_display_name' => $post['post_author'],
     259                                        );
     260                                }
     261                        }
     262                }
     263        }
     264
     265        /**
     266         * Display pre-import options, author importing/mapping and option to
     267         * fetch attachments
     268         */
     269        public function import_options() {
     270                $j = 0;
     271                // phpcs:disable Generic.WhiteSpace.ScopeIndent.Incorrect
     272                ?>
     273<form action="<?php echo admin_url( 'admin.php?import=wordpress&amp;step=2' ); ?>" method="post">
     274        <?php wp_nonce_field( 'import-wordpress' ); ?>
     275        <input type="hidden" name="import_id" value="<?php echo $this->id; ?>" />
     276
     277<?php if ( ! empty( $this->authors ) ) : ?>
     278        <h3><?php _e( 'Assign Authors', 'demo-awesome' ); ?></h3>
     279        <p><?php _e( 'To make it simpler for you to edit and save the imported content, you may want to reassign the author of the imported item to an existing user of this site, such as your primary administrator account.', 'demo-awesome' ); ?></p>
     280<?php if ( $this->allow_create_users() ) : ?>
     281        <p><?php printf( __( 'If a new user is created by WordPress, a new password will be randomly generated and the new user&#8217;s role will be set as %s. Manually changing the new user&#8217;s details will be necessary.', 'demo-awesome' ), esc_html( get_option( 'default_role' ) ) ); ?></p>
     282<?php endif; ?>
     283        <ol id="authors">
     284<?php foreach ( $this->authors as $author ) : ?>
     285                <li><?php $this->author_select( $j++, $author ); ?></li>
     286<?php endforeach; ?>
     287        </ol>
     288<?php endif; ?>
     289
     290<?php if ( $this->allow_fetch_attachments() ) : ?>
     291        <h3><?php _e( 'Import Attachments', 'demo-awesome' ); ?></h3>
     292        <p>
     293                <input type="checkbox" value="1" name="fetch_attachments" id="import-attachments" />
     294                <label for="import-attachments"><?php _e( 'Download and import file attachments', 'demo-awesome' ); ?></label>
     295        </p>
     296<?php endif; ?>
     297
     298        <p class="submit"><input type="submit" class="button" value="<?php esc_attr_e( 'Submit', 'demo-awesome' ); ?>" /></p>
     299</form>
     300                <?php
     301                // phpcs:enable Generic.WhiteSpace.ScopeIndent.Incorrect
     302        }
     303
     304        /**
     305         * Display import options for an individual author. That is, either create
     306         * a new user based on import info or map to an existing user
     307         *
     308         * @param int $n Index for each author in the form
     309         * @param array $author Author information, e.g. login, display name, email
     310         */
     311        public function author_select( $n, $author ) {
     312                _e( 'Import author:', 'demo-awesome' );
     313                echo ' <strong>' . esc_html( $author['author_display_name'] );
     314                if ( '1.0' != $this->version ) {
     315                        echo ' (' . esc_html( $author['author_login'] ) . ')';
     316                }
     317                echo '</strong><br />';
     318
     319                if ( '1.0' != $this->version ) {
     320                        echo '<div style="margin-left:18px">';
     321                }
     322
     323                $create_users = $this->allow_create_users();
     324                if ( $create_users ) {
     325                        echo '<label for="user_new_' . $n . '">';
     326                        if ( '1.0' != $this->version ) {
     327                                _e( 'or create new user with login name:', 'demo-awesome' );
     328                                $value = '';
     329                        } else {
     330                                _e( 'as a new user:', 'demo-awesome' );
     331                                $value = esc_attr( sanitize_user( $author['author_login'], true ) );
     332                        }
     333                        echo '</label>';
     334
     335                        echo ' <input type="text" id="user_new_' . $n . '" name="user_new[' . $n . ']" value="' . $value . '" /><br />';
     336                }
     337
     338                echo '<label for="imported_authors_' . $n . '">';
     339                if ( ! $create_users && '1.0' == $this->version ) {
     340                        _e( 'assign posts to an existing user:', 'demo-awesome' );
     341                } else {
     342                        _e( 'or assign posts to an existing user:', 'demo-awesome' );
     343                }
     344                echo '</label>';
     345
     346                echo ' ' . wp_dropdown_users(
     347                        array(
     348                                'name'            => "user_map[$n]",
     349                                'id'              => 'imported_authors_' . $n,
     350                                'multi'           => true,
     351                                'show_option_all' => __( '- Select -', 'demo-awesome' ),
     352                                'show'            => 'display_name_with_login',
     353                                'echo'            => 0,
     354                        )
     355                );
     356
     357                echo '<input type="hidden" name="imported_authors[' . $n . ']" value="' . esc_attr( $author['author_login'] ) . '" />';
     358
     359                if ( '1.0' != $this->version ) {
     360                        echo '</div>';
     361                }
     362        }
     363
     364        /**
     365         * Map old author logins to local user IDs based on decisions made
     366         * in import options form. Can map to an existing user, create a new user
     367         * or falls back to the current user in case of error with either of the previous
     368         */
     369        public function get_author_mapping() {
     370                if ( ! isset( $_POST['imported_authors'] ) ) {
     371                        return;
     372                }
     373
     374                $create_users = $this->allow_create_users();
     375
     376                foreach ( (array) $_POST['imported_authors'] as $i => $old_login ) {
     377                        // Multisite adds strtolower to sanitize_user. Need to sanitize here to stop breakage in process_posts.
     378                        $santized_old_login = sanitize_user( $old_login, true );
     379                        $old_id             = isset( $this->authors[ $old_login ]['author_id'] ) ? intval( $this->authors[ $old_login ]['author_id'] ) : false;
     380
     381                        if ( ! empty( $_POST['user_map'][ $i ] ) ) {
     382                                $user = get_userdata( intval( $_POST['user_map'][ $i ] ) );
     383                                if ( isset( $user->ID ) ) {
     384                                        if ( $old_id ) {
     385                                                $this->processed_authors[ $old_id ] = $user->ID;
     386                                        }
     387                                        $this->author_mapping[ $santized_old_login ] = $user->ID;
     388                                }
     389                        } elseif ( $create_users ) {
     390                                if ( ! empty( $_POST['user_new'][ $i ] ) ) {
     391                                        $user_id = wp_create_user( $_POST['user_new'][ $i ], wp_generate_password() );
     392                                } elseif ( '1.0' != $this->version ) {
     393                                        $user_data = array(
     394                                                'user_login'   => $old_login,
     395                                                'user_pass'    => wp_generate_password(),
     396                                                'user_email'   => isset( $this->authors[ $old_login ]['author_email'] ) ? $this->authors[ $old_login ]['author_email'] : '',
     397                                                'display_name' => $this->authors[ $old_login ]['author_display_name'],
     398                                                'first_name'   => isset( $this->authors[ $old_login ]['author_first_name'] ) ? $this->authors[ $old_login ]['author_first_name'] : '',
     399                                                'last_name'    => isset( $this->authors[ $old_login ]['author_last_name'] ) ? $this->authors[ $old_login ]['author_last_name'] : '',
     400                                        );
     401                                        $user_id   = wp_insert_user( $user_data );
     402                                }
     403
     404                                if ( ! is_wp_error( $user_id ) ) {
     405                                        if ( $old_id ) {
     406                                                $this->processed_authors[ $old_id ] = $user_id;
     407                                        }
     408                                        $this->author_mapping[ $santized_old_login ] = $user_id;
     409                                } else {
     410                                        printf( __( 'Failed to create new user for %s. Their posts will be attributed to the current user.', 'demo-awesome' ), esc_html( $this->authors[ $old_login ]['author_display_name'] ) );
     411                                        if ( defined( 'IMPORT_DEBUG' ) && IMPORT_DEBUG ) {
     412                                                echo ' ' . $user_id->get_error_message();
     413                                        }
     414                                        echo '<br />';
     415                                }
     416                        }
     417
     418                        // failsafe: if the user_id was invalid, default to the current user
     419                        if ( ! isset( $this->author_mapping[ $santized_old_login ] ) ) {
     420                                if ( $old_id ) {
     421                                        $this->processed_authors[ $old_id ] = (int) get_current_user_id();
     422                                }
     423                                $this->author_mapping[ $santized_old_login ] = (int) get_current_user_id();
     424                        }
     425                }
     426        }
     427
     428        /**
     429         * Create new categories based on import information
     430         *
     431         * Doesn't create a new category if its slug already exists
     432         */
     433        public function process_categories() {
     434                $this->categories = apply_filters( 'wp_import_categories', $this->categories );
     435
     436                if ( empty( $this->categories ) ) {
     437                        return;
     438                }
     439
     440                foreach ( $this->categories as $cat ) {
     441                        // if the category already exists leave it alone
     442                        $term_id = term_exists( $cat['category_nicename'], 'category' );
     443                        if ( $term_id ) {
     444                                if ( is_array( $term_id ) ) {
     445                                        $term_id = $term_id['term_id'];
     446                                }
     447                                if ( isset( $cat['term_id'] ) ) {
     448                                        $this->processed_terms[ intval( $cat['term_id'] ) ] = (int) $term_id;
     449                                }
     450                                continue;
     451                        }
     452
     453                        $parent      = empty( $cat['category_parent'] ) ? 0 : category_exists( $cat['category_parent'] );
     454                        $description = isset( $cat['category_description'] ) ? $cat['category_description'] : '';
     455
     456                        $data = array(
     457                                'category_nicename'    => $cat['category_nicename'],
     458                                'category_parent'      => $parent,
     459                                'cat_name'             => wp_slash( $cat['cat_name'] ),
     460                                'category_description' => wp_slash( $description ),
     461                        );
     462
     463                        $id = wp_insert_category( $data, true );
     464                        if ( ! is_wp_error( $id ) && $id > 0 ) {
     465                                if ( isset( $cat['term_id'] ) ) {
     466                                        $this->processed_terms[ intval( $cat['term_id'] ) ] = $id;
     467                                }
     468                        } else {
     469                                printf( __( 'Failed to import category %s', 'demo-awesome' ), esc_html( $cat['category_nicename'] ) );
     470                                if ( defined( 'IMPORT_DEBUG' ) && IMPORT_DEBUG ) {
     471                                        echo ': ' . $id->get_error_message();
     472                                }
     473                                echo '<br />';
     474                                continue;
     475                        }
     476
     477                        $this->process_termmeta( $cat, $id );
     478                }
     479
     480                unset( $this->categories );
     481        }
     482
     483        /**
     484         * Create new post tags based on import information
     485         *
     486         * Doesn't create a tag if its slug already exists
     487         */
     488        public function process_tags() {
     489                $this->tags = apply_filters( 'wp_import_tags', $this->tags );
     490
     491                if ( empty( $this->tags ) ) {
     492                        return;
     493                }
     494
     495                foreach ( $this->tags as $tag ) {
     496                        // if the tag already exists leave it alone
     497                        $term_id = term_exists( $tag['tag_slug'], 'post_tag' );
     498                        if ( $term_id ) {
     499                                if ( is_array( $term_id ) ) {
     500                                        $term_id = $term_id['term_id'];
     501                                }
     502                                if ( isset( $tag['term_id'] ) ) {
     503                                        $this->processed_terms[ intval( $tag['term_id'] ) ] = (int) $term_id;
     504                                }
     505                                continue;
     506                        }
     507
     508                        $description = isset( $tag['tag_description'] ) ? $tag['tag_description'] : '';
     509                        $args        = array(
     510                                'slug'        => $tag['tag_slug'],
     511                                'description' => wp_slash( $description ),
     512                        );
     513
     514                        $id = wp_insert_term( wp_slash( $tag['tag_name'] ), 'post_tag', $args );
     515                        if ( ! is_wp_error( $id ) ) {
     516                                if ( isset( $tag['term_id'] ) ) {
     517                                        $this->processed_terms[ intval( $tag['term_id'] ) ] = $id['term_id'];
     518                                }
     519                        } else {
     520                                printf( __( 'Failed to import post tag %s', 'demo-awesome' ), esc_html( $tag['tag_name'] ) );
     521                                if ( defined( 'IMPORT_DEBUG' ) && IMPORT_DEBUG ) {
     522                                        echo ': ' . $id->get_error_message();
     523                                }
     524                                echo '<br />';
     525                                continue;
     526                        }
     527
     528                        $this->process_termmeta( $tag, $id['term_id'] );
     529                }
     530
     531                unset( $this->tags );
     532        }
     533
     534        /**
     535         * Create new terms based on import information
     536         *
     537         * Doesn't create a term its slug already exists
     538         */
     539        public function process_terms() {
     540                $this->terms = apply_filters( 'wp_import_terms', $this->terms );
     541
     542                if ( empty( $this->terms ) ) {
     543                        return;
     544                }
     545
     546                foreach ( $this->terms as $term ) {
     547                        // if the term already exists in the correct taxonomy leave it alone
     548                        $term_id = term_exists( $term['slug'], $term['term_taxonomy'] );
     549                        if ( $term_id ) {
     550                                if ( is_array( $term_id ) ) {
     551                                        $term_id = $term_id['term_id'];
     552                                }
     553                                if ( isset( $term['term_id'] ) ) {
     554                                        $this->processed_terms[ intval( $term['term_id'] ) ] = (int) $term_id;
     555                                }
     556                                continue;
     557                        }
     558
     559                        if ( empty( $term['term_parent'] ) ) {
     560                                $parent = 0;
     561                        } else {
     562                                $parent = term_exists( $term['term_parent'], $term['term_taxonomy'] );
     563                                if ( is_array( $parent ) ) {
     564                                        $parent = $parent['term_id'];
     565                                }
     566                        }
     567
     568                        $description = isset( $term['term_description'] ) ? $term['term_description'] : '';
     569                        $args        = array(
     570                                'slug'        => $term['slug'],
     571                                'description' => wp_slash( $description ),
     572                                'parent'      => (int) $parent,
     573                        );
     574
     575                        $id = wp_insert_term( wp_slash( $term['term_name'] ), $term['term_taxonomy'], $args );
     576                        if ( ! is_wp_error( $id ) ) {
     577                                if ( isset( $term['term_id'] ) ) {
     578                                        $this->processed_terms[ intval( $term['term_id'] ) ] = $id['term_id'];
     579                                }
     580                        } else {
     581                                printf( __( 'Failed to import %1$s %2$s', 'demo-awesome' ), esc_html( $term['term_taxonomy'] ), esc_html( $term['term_name'] ) );
     582                                if ( defined( 'IMPORT_DEBUG' ) && IMPORT_DEBUG ) {
     583                                        echo ': ' . $id->get_error_message();
     584                                }
     585                                echo '<br />';
     586                                continue;
     587                        }
     588
     589                        $this->process_termmeta( $term, $id['term_id'] );
     590                }
     591
     592                unset( $this->terms );
     593        }
     594
     595        /**
     596         * Add metadata to imported term.
     597         *
     598         * @since 0.6.2
     599         *
     600         * @param array $term    Term data from WXR import.
     601         * @param int   $term_id ID of the newly created term.
     602         */
     603        protected function process_termmeta( $term, $term_id ) {
     604                if ( ! isset( $term['termmeta'] ) ) {
     605                        $term['termmeta'] = array();
     606                }
    53607
    54608                /**
    55                  * Registered callback function for the WordPress Importer
     609                 * Filters the metadata attached to an imported term.
    56610                 *
    57                  * Manages the three separate stages of the WXR import process
     611                 * @since 0.6.2
     612                 *
     613                 * @param array $termmeta Array of term meta.
     614                 * @param int   $term_id  ID of the newly created term.
     615                 * @param array $term     Term data from the WXR import.
    58616                 */
    59                 function dispatch() {
    60                         $this->header();
    61 
    62                         $step = empty( $_GET['step'] ) ? 0 : (int) $_GET['step'];
    63                         switch ( $step ) {
    64                                 case 0:
    65                                         $this->greet();
    66                                         break;
    67                                 case 1:
    68                                         check_admin_referer( 'import-upload' );
    69                                         if ( $this->handle_upload() ) {
    70                                                 $this->import_options();
     617                $term['termmeta'] = apply_filters( 'wp_import_term_meta', $term['termmeta'], $term_id, $term );
     618
     619                if ( empty( $term['termmeta'] ) ) {
     620                        return;
     621                }
     622
     623                foreach ( $term['termmeta'] as $meta ) {
     624                        /**
     625                         * Filters the meta key for an imported piece of term meta.
     626                         *
     627                         * @since 0.6.2
     628                         *
     629                         * @param string $meta_key Meta key.
     630                         * @param int    $term_id  ID of the newly created term.
     631                         * @param array  $term     Term data from the WXR import.
     632                         */
     633                        $key = apply_filters( 'import_term_meta_key', $meta['key'], $term_id, $term );
     634                        if ( ! $key ) {
     635                                continue;
     636                        }
     637
     638                        // Export gets meta straight from the DB so could have a serialized string
     639                        $value = $this->maybe_unserialize( $meta['value'] );
     640
     641                        add_term_meta( $term_id, wp_slash( $key ), wp_slash_strings_only( $value ) );
     642
     643                        /**
     644                         * Fires after term meta is imported.
     645                         *
     646                         * @since 0.6.2
     647                         *
     648                         * @param int    $term_id ID of the newly created term.
     649                         * @param string $key     Meta key.
     650                         * @param mixed  $value   Meta value.
     651                         */
     652                        do_action( 'import_term_meta', $term_id, $key, $value );
     653                }
     654        }
     655
     656        /**
     657         * Create new posts based on import information
     658         *
     659         * Posts marked as having a parent which doesn't exist will become top level items.
     660         * Doesn't create a new post if: the post type doesn't exist, the given post ID
     661         * is already noted as imported or a post with the same title and date already exists.
     662         * Note that new/updated terms, comments and meta are imported for the last of the above.
     663         */
     664        public function process_posts() {
     665                $this->posts = apply_filters( 'wp_import_posts', $this->posts );
     666
     667                foreach ( $this->posts as $post ) {
     668                        $post = apply_filters( 'wp_import_post_data_raw', $post );
     669
     670                        if ( ! post_type_exists( $post['post_type'] ) ) {
     671                                printf(
     672                                        __( 'Failed to import &#8220;%1$s&#8221;: Invalid post type %2$s', 'demo-awesome' ),
     673                                        esc_html( $post['post_title'] ),
     674                                        esc_html( $post['post_type'] )
     675                                );
     676                                echo '<br />';
     677                                do_action( 'wp_import_post_exists', $post );
     678                                continue;
     679                        }
     680
     681                        if ( isset( $this->processed_posts[ $post['post_id'] ] ) && ! empty( $post['post_id'] ) ) {
     682                                continue;
     683                        }
     684
     685                        if ( 'auto-draft' == $post['status'] ) {
     686                                continue;
     687                        }
     688
     689                        if ( 'nav_menu_item' == $post['post_type'] ) {
     690                                $this->process_menu_item( $post );
     691                                continue;
     692                        }
     693
     694                        $post_type_object = get_post_type_object( $post['post_type'] );
     695
     696                        $post_exists = post_exists( $post['post_title'], '', $post['post_date'], $post['post_type'] );
     697
     698                        /**
     699                        * Filter ID of the existing post corresponding to post currently importing.
     700                        *
     701                        * Return 0 to force the post to be imported. Filter the ID to be something else
     702                        * to override which existing post is mapped to the imported post.
     703                        *
     704                        * @see post_exists()
     705                        * @since 0.6.2
     706                        *
     707                        * @param int   $post_exists  Post ID, or 0 if post did not exist.
     708                        * @param array $post         The post array to be inserted.
     709                        */
     710                        $post_exists = apply_filters( 'wp_import_existing_post', $post_exists, $post );
     711
     712                        if ( $post_exists && get_post_type( $post_exists ) == $post['post_type'] ) {
     713                                printf( __( '%1$s &#8220;%2$s&#8221; already exists.', 'demo-awesome' ), $post_type_object->labels->singular_name, esc_html( $post['post_title'] ) );
     714                                echo '<br />';
     715                                $comment_post_id = $post_exists;
     716                                $post_id         = $post_exists;
     717                                $this->processed_posts[ intval( $post['post_id'] ) ] = intval( $post_exists );
     718                        } else {
     719                                $post_parent = (int) $post['post_parent'];
     720                                if ( $post_parent ) {
     721                                        // if we already know the parent, map it to the new local ID
     722                                        if ( isset( $this->processed_posts[ $post_parent ] ) ) {
     723                                                $post_parent = $this->processed_posts[ $post_parent ];
     724                                                // otherwise record the parent for later
     725                                        } else {
     726                                                $this->post_orphans[ intval( $post['post_id'] ) ] = $post_parent;
     727                                                $post_parent                                      = 0;
    71728                                        }
    72                                         break;
    73                                 case 2:
    74                                         check_admin_referer( 'import-wordpress' );
    75                                         $this->fetch_attachments = ( ! empty( $_POST['fetch_attachments'] ) && $this->allow_fetch_attachments() );
    76                                         $this->id                = (int) $_POST['import_id'];
    77                                         $file                    = get_attached_file( $this->id );
    78                                         set_time_limit( 0 );
    79                                         $this->import( $file );
    80                                         break;
    81                         }
    82 
    83                         $this->footer();
    84                 }
    85 
    86                 /**
    87                  * The main controller for the actual import stage.
    88                  *
    89                  * @param string $file Path to the WXR file for importing
    90                  */
    91                 function import( $file ) {
    92                         require dirname( __FILE__ ) . '/class-demo-awesome-parsers.php';
    93 
    94                         add_filter( 'import_post_meta_key', array( $this, 'is_valid_meta_key' ) );
    95                         add_filter( 'http_request_timeout', array( &$this, 'bump_request_timeout' ) );
    96 
    97                         $this->import_start( $file );
    98 
    99                         $this->get_author_mapping();
    100 
    101                         wp_suspend_cache_invalidation( true );
    102                         $this->process_categories();
    103                         $this->process_tags();
    104                         $this->process_terms();
    105                         $this->process_posts();
    106                         wp_suspend_cache_invalidation( false );
    107 
    108                         // update incorrect/missing information in the DB
    109                         $this->backfill_parents();
    110                         $this->backfill_attachment_urls();
    111                         $this->remap_featured_images();
    112 
    113                         $this->import_end();
    114                 }
    115 
    116                 /**
    117                  * Parses the WXR file and prepares us for the task of processing parsed data
    118                  *
    119                  * @param string $file Path to the WXR file for importing
    120                  */
    121                 function import_start( $file ) {
    122                         if ( ! is_file( $file ) ) {
    123                                 echo '<p><strong>' . esc_html__( 'Sorry, there has been an error.', 'demo-awesome' ) . '</strong><br />';
    124                                 echo esc_html__( 'The file does not exist, please try again.', 'demo-awesome' ) . '</p>';
    125                                 $this->footer();
    126                                 die();
    127                         }
    128 
    129                         $import_data = $this->parse( $file );
    130 
    131                         if ( is_wp_error( $import_data ) ) {
    132                                 echo '<p><strong>' . esc_html__( 'Sorry, there has been an error.', 'demo-awesome' ) . '</strong><br />';
    133                                 echo esc_html( $import_data->get_error_message() ) . '</p>';
    134                                 $this->footer();
    135                                 die();
    136                         }
    137 
    138                         $this->version = $import_data['version'];
    139                         $this->get_authors_from_import( $import_data );
    140                         $this->posts      = $import_data['posts'];
    141                         $this->terms      = $import_data['terms'];
    142                         $this->categories = $import_data['categories'];
    143                         $this->tags       = $import_data['tags'];
    144                         $this->base_url   = esc_url( $import_data['base_url'] );
    145 
    146                         wp_defer_term_counting( true );
    147                         wp_defer_comment_counting( true );
    148                         do_action( 'import_start' );
    149                 }
    150 
    151                 /**
    152                  * Performs post-import cleanup of files and the cache
    153                  */
    154                 function import_end() {
    155                         wp_import_cleanup( $this->id );
    156 
    157                         wp_cache_flush();
    158                         foreach ( get_taxonomies() as $tax ) {
    159                                 delete_option( "{$tax}_children" );
    160                                 _get_term_hierarchy( $tax );
    161                         }
    162 
    163                         wp_defer_term_counting( false );
    164                         wp_defer_comment_counting( false );
    165 
    166                         echo '<p>' . esc_html__( 'All done.', 'demo-awesome' ) . ' <a href="' . admin_url() . '">' . esc_html__( 'Have fun!', 'demo-awesome' ) . '</a>' . '</p>';
    167                         echo '<p>' . esc_html__( 'Remember to update the passwords and roles of imported users.', 'demo-awesome' ) . '</p>';
    168 
    169                         do_action( 'import_end' );
    170                 }
    171 
    172                 /**
    173                  * Handles the WXR upload and initial parsing of the file to prepare for
    174                  * displaying author import options
    175                  *
    176                  * @return bool False if error uploading or invalid file, true otherwise
    177                  */
    178                 function handle_upload() {
    179                         $file = wp_import_handle_upload();
    180 
    181                         if ( isset( $file['error'] ) ) {
    182                                 echo '<p><strong>' . esc_html__( 'Sorry, there has been an error.', 'demo-awesome' ) . '</strong><br />';
    183                                 echo esc_html( $file['error'] ) . '</p>';
    184 
    185                                 return false;
    186                         } else if ( ! file_exists( $file['file'] ) ) {
    187                                 echo '<p><strong>' . esc_html__( 'Sorry, there has been an error.', 'demo-awesome' ) . '</strong><br />';
    188                                 printf( esc_html__( 'The export file could not be found at <code>%s</code>. It is likely that this was caused by a permissions problem.', 'demo-awesome' ), esc_html( $file['file'] ) );
    189                                 echo '</p>';
    190 
    191                                 return false;
    192                         }
    193 
    194                         $this->id    = (int) $file['id'];
    195                         $import_data = $this->parse( $file['file'] );
    196                         if ( is_wp_error( $import_data ) ) {
    197                                 echo '<p><strong>' . esc_html__( 'Sorry, there has been an error.', 'demo-awesome' ) . '</strong><br />';
    198                                 echo esc_html( $import_data->get_error_message() ) . '</p>';
    199 
    200                                 return false;
    201                         }
    202 
    203                         $this->version = $import_data['version'];
    204                         if ( $this->version > $this->max_wxr_version ) {
    205                                 echo '<div class="error"><p><strong>';
    206                                 printf( esc_html__( 'This WXR file (version %s) may not be supported by this version of the importer. Please consider updating.', 'demo-awesome' ), esc_html( $import_data['version'] ) );
    207                                 echo '</strong></p></div>';
    208                         }
    209 
    210                         $this->get_authors_from_import( $import_data );
    211 
    212                         return true;
    213                 }
    214 
    215                 /**
    216                  * Retrieve authors from parsed WXR data
    217                  *
    218                  * Uses the provided author information from WXR 1.1 files
    219                  * or extracts info from each post for WXR 1.0 files
    220                  *
    221                  * @param array $import_data Data returned by a WXR parser
    222                  */
    223                 function get_authors_from_import( $import_data ) {
    224                         if ( ! empty( $import_data['authors'] ) ) {
    225                                 $this->authors = $import_data['authors'];
    226                                 // no author information, grab it from the posts
    227                         } else {
    228                                 foreach ( $import_data['posts'] as $post ) {
    229                                         $login = sanitize_user( $post['post_author'], true );
    230                                         if ( empty( $login ) ) {
    231                                                 printf( esc_html__( 'Failed to import author %s. Their posts will be attributed to the current user.', 'demo-awesome' ), esc_html( $post['post_author'] ) );
    232                                                 echo '<br />';
    233                                                 continue;
     729                                }
     730
     731                                // map the post author
     732                                $author = sanitize_user( $post['post_author'], true );
     733                                if ( isset( $this->author_mapping[ $author ] ) ) {
     734                                        $author = $this->author_mapping[ $author ];
     735                                } else {
     736                                        $author = (int) get_current_user_id();
     737                                }
     738
     739                                $postdata = array(
     740                                        'import_id'      => $post['post_id'],
     741                                        'post_author'    => $author,
     742                                        'post_date'      => $post['post_date'],
     743                                        'post_date_gmt'  => $post['post_date_gmt'],
     744                                        'post_content'   => $post['post_content'],
     745                                        'post_excerpt'   => $post['post_excerpt'],
     746                                        'post_title'     => $post['post_title'],
     747                                        'post_status'    => $post['status'],
     748                                        'post_name'      => $post['post_name'],
     749                                        'comment_status' => $post['comment_status'],
     750                                        'ping_status'    => $post['ping_status'],
     751                                        'guid'           => $post['guid'],
     752                                        'post_parent'    => $post_parent,
     753                                        'menu_order'     => $post['menu_order'],
     754                                        'post_type'      => $post['post_type'],
     755                                        'post_password'  => $post['post_password'],
     756                                );
     757
     758                                $original_post_id = $post['post_id'];
     759                                $postdata         = apply_filters( 'wp_import_post_data_processed', $postdata, $post );
     760
     761                                $postdata = wp_slash( $postdata );
     762
     763                                if ( 'attachment' == $postdata['post_type'] ) {
     764                                        $remote_url = ! empty( $post['attachment_url'] ) ? $post['attachment_url'] : $post['guid'];
     765
     766                                        // try to use _wp_attached file for upload folder placement to ensure the same location as the export site
     767                                        // e.g. location is 2003/05/image.jpg but the attachment post_date is 2010/09, see media_handle_upload()
     768                                        $postdata['upload_date'] = $post['post_date'];
     769                                        if ( isset( $post['postmeta'] ) ) {
     770                                                foreach ( $post['postmeta'] as $meta ) {
     771                                                        if ( '_wp_attached_file' == $meta['key'] ) {
     772                                                                if ( preg_match( '%^[0-9]{4}/[0-9]{2}%', $meta['value'], $matches ) ) {
     773                                                                        $postdata['upload_date'] = $matches[0];
     774                                                                }
     775                                                                break;
     776                                                        }
     777                                                }
    234778                                        }
    235779
    236                                         if ( ! isset( $this->authors[ $login ] ) ) {
    237                                                 $this->authors[ $login ] = array(
    238                                                         'author_login'        => $login,
    239                                                         'author_display_name' => $post['post_author']
    240                                                 );
    241                                         }
    242                                 }
    243                         }
    244                 }
    245 
    246                 /**
    247                  * Display pre-import options, author importing/mapping and option to
    248                  * fetch attachments
    249                  */
    250                 function import_options() {
    251                         $j = 0;
    252                         ?>
    253             <form action="<?php echo esc_url(admin_url( 'admin.php?import=wordpress&amp;step=2' )); ?>" method="post">
    254                                 <?php wp_nonce_field( 'import-wordpress' ); ?>
    255                 <input type="hidden" name="import_id" value="<?php echo  esc_attr($this->id); ?>"/>
    256 
    257                                 <?php if ( ! empty( $this->authors ) ) : ?>
    258                     <h3><?php esc_html_e( 'Assign Authors', 'demo-awesome' ); ?></h3>
    259                     <p><?php esc_html_e( 'To make it easier for you to edit and save the imported content, you may want to reassign the author of the imported item to an existing user of this site. For example, you may want to import all the entries as <code>admin</code>s entries.', 'demo-awesome' ); ?></p>
    260                                         <?php if ( $this->allow_create_users() ) : ?>
    261                         <p><?php printf( esc_html__( 'If a new user is created by WordPress, a new password will be randomly generated and the new user&#8217;s role will be set as %s. Manually changing the new user&#8217;s details will be necessary.', 'demo-awesome' ), esc_html( get_option( 'default_role' ) ) ); ?></p>
    262                                         <?php endif; ?>
    263                     <ol id="authors">
    264                                                 <?php foreach ( $this->authors as $author ) : ?>
    265                             <li><?php $this->author_select( $j ++, $author ); ?></li>
    266                                                 <?php endforeach; ?>
    267                     </ol>
    268                                 <?php endif; ?>
    269 
    270                                 <?php if ( $this->allow_fetch_attachments() ) : ?>
    271                     <h3><?php esc_html_e( 'Import Attachments', 'demo-awesome' ); ?></h3>
    272                     <p>
    273                         <input type="checkbox" value="1" name="fetch_attachments" id="import-attachments"/>
    274                         <label for="import-attachments"><?php esc_html_e( 'Download and import file attachments', 'demo-awesome' ); ?></label>
    275                     </p>
    276                                 <?php endif; ?>
    277 
    278                 <p class="submit"><input type="submit" class="button"
    279                                          value="<?php esc_attr_e( 'Submit', 'demo-awesome' ); ?>"/></p>
    280             </form>
    281                         <?php
    282                 }
    283 
    284                 /**
    285                  * Display import options for an individual author. That is, either create
    286                  * a new user based on import info or map to an existing user
    287                  *
    288                  * @param int $n Index for each author in the form
    289                  * @param array $author Author information, e.g. login, display name, email
    290                  */
    291                 function author_select( $n, $author ) {
    292             esc_html_e( 'Import author:', 'demo-awesome' );
    293                         echo ' <strong>' . esc_html( $author['author_display_name'] );
    294                         if ( $this->version != '1.0' ) {
    295                                 echo ' (' . esc_html( $author['author_login'] ) . ')';
    296                         }
    297                         echo '</strong><br />';
    298 
    299                         if ( $this->version != '1.0' ) {
    300                                 echo '<div style="margin-left:18px">';
    301                         }
    302 
    303                         $create_users = $this->allow_create_users();
    304                         if ( $create_users ) {
    305                                 if ( $this->version != '1.0' ) {
    306                                         _e( 'or create new user with login name:', 'demo-awesome' );
    307                                         $value = '';
     780                                        $comment_post_id = $this->process_attachment( $postdata, $remote_url );
     781                                        $post_id         = $comment_post_id;
    308782                                } else {
    309                                         _e( 'as a new user:', 'demo-awesome' );
    310                                         $value = esc_attr( sanitize_user( $author['author_login'], true ) );
    311                                 }
    312 
    313                                 echo ' <input type="text" name="user_new[' . $n . ']" value="' . $value . '" /><br />';
    314                         }
    315 
    316                         if ( ! $create_users && $this->version == '1.0' ) {
    317                                 _e( 'assign posts to an existing user:', 'demo-awesome' );
    318                         } else {
    319                                 _e( 'or assign posts to an existing user:', 'demo-awesome' );
    320                         }
    321                         wp_dropdown_users( array(
    322                                 'name'            => "user_map[$n]",
    323                                 'multi'           => true,
    324                                 'show_option_all' => esc_html__( '- Select -', 'demo-awesome' )
    325                         ) );
    326                         echo '<input type="hidden" name="imported_authors[' . $n . ']" value="' . esc_attr( $author['author_login'] ) . '" />';
    327 
    328                         if ( $this->version != '1.0' ) {
    329                                 echo '</div>';
    330                         }
    331                 }
    332 
    333                 /**
    334                  * Map old author logins to local user IDs based on decisions made
    335                  * in import options form. Can map to an existing user, create a new user
    336                  * or falls back to the current user in case of error with either of the previous
    337                  */
    338                 function get_author_mapping() {
    339                         if ( ! isset( $_POST['imported_authors'] ) ) {
    340                                 return;
    341                         }
    342 
    343                         $create_users = $this->allow_create_users();
    344 
    345                         foreach ( (array) $_POST['imported_authors'] as $i => $old_login ) {
    346                                 // Multisite adds strtolower to sanitize_user. Need to sanitize here to stop breakage in process_posts.
    347                                 $santized_old_login = sanitize_user( $old_login, true );
    348                                 $old_id             = isset( $this->authors[ $old_login ]['author_id'] ) ? intval( $this->authors[ $old_login ]['author_id'] ) : false;
    349 
    350                                 if ( ! empty( $_POST['user_map'][ $i ] ) ) {
    351                                         $user = get_userdata( intval( $_POST['user_map'][ $i ] ) );
    352                                         if ( isset( $user->ID ) ) {
    353                                                 if ( $old_id ) {
    354                                                         $this->processed_authors[ $old_id ] = $user->ID;
    355                                                 }
    356                                                 $this->author_mapping[ $santized_old_login ] = $user->ID;
    357                                         }
    358                                 } else if ( $create_users ) {
    359                                         if ( ! empty( $_POST['user_new'][ $i ] ) ) {
    360                                                 $user_id = wp_create_user( $_POST['user_new'][ $i ], wp_generate_password() );
    361                                         } else if ( $this->version != '1.0' ) {
    362                                                 $user_data = array(
    363                                                         'user_login'   => $old_login,
    364                                                         'user_pass'    => wp_generate_password(),
    365                                                         'user_email'   => isset( $this->authors[ $old_login ]['author_email'] ) ? $this->authors[ $old_login ]['author_email'] : '',
    366                                                         'display_name' => $this->authors[ $old_login ]['author_display_name'],
    367                                                         'first_name'   => isset( $this->authors[ $old_login ]['author_first_name'] ) ? $this->authors[ $old_login ]['author_first_name'] : '',
    368                                                         'last_name'    => isset( $this->authors[ $old_login ]['author_last_name'] ) ? $this->authors[ $old_login ]['author_last_name'] : '',
    369                                                 );
    370                                                 $user_id   = wp_insert_user( $user_data );
    371                                         }
    372 
    373                                         if ( ! is_wp_error( $user_id ) ) {
    374                                                 if ( $old_id ) {
    375                                                         $this->processed_authors[ $old_id ] = $user_id;
    376                                                 }
    377                                                 $this->author_mapping[ $santized_old_login ] = $user_id;
    378                                         } else {
    379                                                 printf( esc_html__( 'Failed to create new user for %s. Their posts will be attributed to the current user.', 'demo-awesome' ), esc_html( $this->authors[ $old_login ]['author_display_name'] ) );
    380                                                 if ( defined( 'IMPORT_DEBUG' ) && IMPORT_DEBUG ) {
    381                                                         echo ' ' . esc_html($user_id->get_error_message());
    382                                                 }
    383                                                 echo '<br />';
    384                                         }
    385                                 }
    386 
    387                                 // failsafe: if the user_id was invalid, default to the current user
    388                                 if ( ! isset( $this->author_mapping[ $santized_old_login ] ) ) {
    389                                         if ( $old_id ) {
    390                                                 $this->processed_authors[ $old_id ] = (int) get_current_user_id();
    391                                         }
    392                                         $this->author_mapping[ $santized_old_login ] = (int) get_current_user_id();
    393                                 }
    394                         }
    395                 }
    396 
    397                 /**
    398                  * Create new categories based on import information
    399                  *
    400                  * Doesn't create a new category if its slug already exists
    401                  */
    402                 function process_categories() {
    403                         $this->categories = apply_filters( 'wp_import_categories', $this->categories );
    404 
    405                         if ( empty( $this->categories ) ) {
    406                                 return;
    407                         }
    408 
    409                         foreach ( $this->categories as $cat ) {
    410                                 // if the category already exists leave it alone
    411                                 $term_id = term_exists( $cat['category_nicename'], 'category' );
    412                                 if ( $term_id ) {
    413                                         if ( is_array( $term_id ) ) {
    414                                                 $term_id = $term_id['term_id'];
    415                                         }
    416                                         if ( isset( $cat['term_id'] ) ) {
    417                                                 $this->processed_terms[ intval( $cat['term_id'] ) ] = (int) $term_id;
    418                                         }
    419                                         continue;
    420                                 }
    421 
    422                                 $category_parent      = empty( $cat['category_parent'] ) ? 0 : category_exists( $cat['category_parent'] );
    423                                 $category_description = isset( $cat['category_description'] ) ? $cat['category_description'] : '';
    424                                 $catarr               = array(
    425                                         'category_nicename'    => $cat['category_nicename'],
    426                                         'category_parent'      => $category_parent,
    427                                         'cat_name'             => $cat['cat_name'],
    428                                         'category_description' => $category_description
    429                                 );
    430                                 $catarr               = wp_slash( $catarr );
    431 
    432                                 $id = wp_insert_category( $catarr );
    433                                 if ( ! is_wp_error( $id ) ) {
    434                                         if ( isset( $cat['term_id'] ) ) {
    435                                                 $this->processed_terms[ intval( $cat['term_id'] ) ] = $id;
    436                                         }
    437                                 } else {
    438                                         printf( esc_html__( 'Failed to import category %s', 'demo-awesome' ), esc_html( $cat['category_nicename'] ) );
     783                                        $comment_post_id = wp_insert_post( $postdata, true );
     784                                        $post_id         = $comment_post_id;
     785                                        do_action( 'wp_import_insert_post', $post_id, $original_post_id, $postdata, $post );
     786                                }
     787
     788                                if ( is_wp_error( $post_id ) ) {
     789                                        printf(
     790                                                __( 'Failed to import %1$s &#8220;%2$s&#8221;', 'demo-awesome' ),
     791                                                $post_type_object->labels->singular_name,
     792                                                esc_html( $post['post_title'] )
     793                                        );
    439794                                        if ( defined( 'IMPORT_DEBUG' ) && IMPORT_DEBUG ) {
    440                                                 echo ': ' .  esc_html($id->get_error_message());
     795                                                echo ': ' . $post_id->get_error_message();
    441796                                        }
    442797                                        echo '<br />';
    … …  
    444799                                }
    445800
    446                                 $this->process_termmeta( $cat, $id['term_id'] );
    447                         }
    448 
    449                         unset( $this->categories );
    450                 }
    451 
    452                 /**
    453                  * Create new post tags based on import information
    454                  *
    455                  * Doesn't create a tag if its slug already exists
    456                  */
    457                 function process_tags() {
    458                         $this->tags = apply_filters( 'wp_import_tags', $this->tags );
    459 
    460                         if ( empty( $this->tags ) ) {
    461                                 return;
    462                         }
    463 
    464                         foreach ( $this->tags as $tag ) {
    465                                 // if the tag already exists leave it alone
    466                                 $term_id = term_exists( $tag['tag_slug'], 'post_tag' );
    467                                 if ( $term_id ) {
    468                                         if ( is_array( $term_id ) ) {
    469                                                 $term_id = $term_id['term_id'];
    470                                         }
    471                                         if ( isset( $tag['term_id'] ) ) {
    472                                                 $this->processed_terms[ intval( $tag['term_id'] ) ] = (int) $term_id;
    473                                         }
    474                                         continue;
    475                                 }
    476 
    477                                 $tag      = wp_slash( $tag );
    478                                 $tag_desc = isset( $tag['tag_description'] ) ? $tag['tag_description'] : '';
    479                                 $tagarr   = array( 'slug' => $tag['tag_slug'], 'description' => $tag_desc );
    480 
    481                                 $id = wp_insert_term( $tag['tag_name'], 'post_tag', $tagarr );
    482                                 if ( ! is_wp_error( $id ) ) {
    483                                         if ( isset( $tag['term_id'] ) ) {
    484                                                 $this->processed_terms[ intval( $tag['term_id'] ) ] = $id['term_id'];
    485                                         }
    486                                 } else {
    487                                         printf( esc_html__( 'Failed to import post tag %s', 'demo-awesome' ), esc_html( $tag['tag_name'] ) );
    488                                         if ( defined( 'IMPORT_DEBUG' ) && IMPORT_DEBUG ) {
    489                                                 echo ': ' . esc_html($id->get_error_message());
    490                                         }
    491                                         echo '<br />';
    492                                         continue;
    493                                 }
    494 
    495                                 $this->process_termmeta( $tag, $id['term_id'] );
    496                         }
    497 
    498                         unset( $this->tags );
    499                 }
    500 
    501                 /**
    502                  * Create new terms based on import information
    503                  *
    504                  * Doesn't create a term its slug already exists
    505                  */
    506                 function process_terms() {
    507                         $this->terms = apply_filters( 'wp_import_terms', $this->terms );
    508 
    509                         if ( empty( $this->terms ) ) {
    510                                 return;
    511                         }
    512 
    513                         foreach ( $this->terms as $term ) {
    514                                 // if the term already exists in the correct taxonomy leave it alone
    515                                 $term_id = term_exists( $term['slug'], $term['term_taxonomy'] );
    516                                 if ( $term_id ) {
    517                                         if ( is_array( $term_id ) ) {
    518                                                 $term_id = $term_id['term_id'];
    519                                         }
    520                                         if ( isset( $term['term_id'] ) ) {
    521                                                 $this->processed_terms[ intval( $term['term_id'] ) ] = (int) $term_id;
    522                                         }
    523                                         continue;
    524                                 }
    525 
    526                                 if ( empty( $term['term_parent'] ) ) {
    527                                         $parent = 0;
    528                                 } else {
    529                                         $parent = term_exists( $term['term_parent'], $term['term_taxonomy'] );
    530                                         if ( is_array( $parent ) ) {
    531                                                 $parent = $parent['term_id'];
    532                                         }
    533                                 }
    534                                 $term        = wp_slash( $term );
    535                                 $description = isset( $term['term_description'] ) ? $term['term_description'] : '';
    536                                 $termarr     = array(
    537                                         'slug'        => $term['slug'],
    538                                         'description' => $description,
    539                                         'parent'      => intval( $parent )
    540                                 );
    541 
    542                                 $id = wp_insert_term( $term['term_name'], $term['term_taxonomy'], $termarr );
    543                                 if ( ! is_wp_error( $id ) ) {
    544                                         if ( isset( $term['term_id'] ) ) {
    545                                                 $this->processed_terms[ intval( $term['term_id'] ) ] = $id['term_id'];
    546                                         }
    547                                 } else {
    548                                         printf( esc_html__( 'Failed to import %s %s', 'demo-awesome' ), esc_html( $term['term_taxonomy'] ), esc_html( $term['term_name'] ) );
    549                                         if ( defined( 'IMPORT_DEBUG' ) && IMPORT_DEBUG ) {
    550                                                 echo ': ' . $id->get_error_message();
    551                                         }
    552                                         echo '<br />';
    553                                         continue;
    554                                 }
    555 
    556                                 $this->process_termmeta( $term, $id['term_id'] );
    557                         }
    558 
    559                         unset( $this->terms );
    560                 }
    561 
    562                 /**
    563                  * Add metadata to imported term.
    564                  *
    565                  * @since 0.6.2
    566                  *
    567                  * @param array $term Term data from WXR import.
    568                  * @param int $term_id ID of the newly created term.
    569                  */
    570                 protected function process_termmeta( $term, $term_id ) {
    571                         if ( ! isset( $term['termmeta'] ) ) {
    572                                 $term['termmeta'] = array();
    573                         }
    574 
    575                         /**
    576                          * Filters the metadata attached to an imported term.
    577                          *
    578                          * @since 0.6.2
    579                          *
    580                          * @param array $termmeta Array of term meta.
    581                          * @param int $term_id ID of the newly created term.
    582                          * @param array $term Term data from the WXR import.
    583                          */
    584                         $term['termmeta'] = apply_filters( 'wp_import_term_meta', $term['termmeta'], $term_id, $term );
    585 
    586                         if ( empty( $term['termmeta'] ) ) {
    587                                 return;
    588                         }
    589 
    590                         foreach ( $term['termmeta'] as $meta ) {
    591                                 /**
    592                                  * Filters the meta key for an imported piece of term meta.
    593                                  *
    594                                  * @since 0.6.2
    595                                  *
    596                                  * @param string $meta_key Meta key.
    597                                  * @param int $term_id ID of the newly created term.
    598                                  * @param array $term Term data from the WXR import.
    599                                  */
    600                                 $key = apply_filters( 'import_term_meta_key', $meta['key'], $term_id, $term );
    601                                 if ( ! $key ) {
    602                                         continue;
    603                                 }
    604 
    605                                 // Export gets meta straight from the DB so could have a serialized string
    606                                 $value = maybe_unserialize( $meta['value'] );
    607 
    608                                 add_term_meta( $term_id, $key, $value );
    609 
    610                                 /**
    611                                  * Fires after term meta is imported.
    612                                  *
    613                                  * @since 0.6.2
    614                                  *
    615                                  * @param int $term_id ID of the newly created term.
    616                                  * @param string $key Meta key.
    617                                  * @param mixed $value Meta value.
    618                                  */
    619                                 do_action( 'import_term_meta', $term_id, $key, $value );
    620                         }
    621                 }
    622 
    623                 /**
    624                  * Create new posts based on import information
    625                  *
    626                  * Posts marked as having a parent which doesn't exist will become top level items.
    627                  * Doesn't create a new post if: the post type doesn't exist, the given post ID
    628                  * is already noted as imported or a post with the same title and date already exists.
    629                  * Note that new/updated terms, comments and meta are imported for the last of the above.
    630                  */
    631                 function process_posts() {
    632                         $this->posts = apply_filters( 'wp_import_posts', $this->posts );
    633 
    634                         foreach ( $this->posts as $post ) {
    635                                 $post = apply_filters( 'wp_import_post_data_raw', $post );
    636 
    637                                 if ( ! post_type_exists( $post['post_type'] ) ) {
    638                                         printf( esc_html__( 'Failed to import &#8220;%s&#8221;: Invalid post type %s', 'demo-awesome' ),
    639                                                 esc_html( $post['post_title'] ), esc_html( $post['post_type'] ) );
    640                                         echo '<br />';
    641                                         do_action( 'wp_import_post_exists', $post );
    642                                         continue;
    643                                 }
    644 
    645                                 if ( isset( $this->processed_posts[ $post['post_id'] ] ) && ! empty( $post['post_id'] ) ) {
    646                                         continue;
    647                                 }
    648 
    649                                 if ( $post['status'] == 'auto-draft' ) {
    650                                         continue;
    651                                 }
    652 
    653                                 if ( 'nav_menu_item' == $post['post_type'] ) {
    654                                         $this->process_menu_item( $post );
    655                                         continue;
    656                                 }
    657 
    658                                 $post_type_object = get_post_type_object( $post['post_type'] );
    659 
    660                                 $post_exists = post_exists( $post['post_title'], '', $post['post_date'] );
    661 
    662                                 /**
    663                                  * Filter ID of the existing post corresponding to post currently importing.
    664                                  *
    665                                  * Return 0 to force the post to be imported. Filter the ID to be something else
    666                                  * to override which existing post is mapped to the imported post.
    667                                  *
    668                                  * @see post_exists()
    669                                  * @since 0.6.2
    670                                  *
    671                                  * @param int $post_exists Post ID, or 0 if post did not exist.
    672                                  * @param array $post The post array to be inserted.
    673                                  */
    674                                 $post_exists = apply_filters( 'wp_import_existing_post', $post_exists, $post );
    675 
    676                                 if ( $post_exists && get_post_type( $post_exists ) == $post['post_type'] ) {
    677                                         printf( esc_html__( '%s &#8220;%s&#8221; already exists.', 'demo-awesome' ), $post_type_object->labels->singular_name, esc_html( $post['post_title'] ) );
    678                                         echo '<br />';
    679                                         $comment_post_ID                                     = $post_id = $post_exists;
    680                                         $this->processed_posts[ intval( $post['post_id'] ) ] = intval( $post_exists );
    681                                 } else {
    682                                         $post_parent = (int) $post['post_parent'];
    683                                         if ( $post_parent ) {
    684                                                 // if we already know the parent, map it to the new local ID
    685                                                 if ( isset( $this->processed_posts[ $post_parent ] ) ) {
    686                                                         $post_parent = $this->processed_posts[ $post_parent ];
    687                                                         // otherwise record the parent for later
     801                                if ( 1 == $post['is_sticky'] ) {
     802                                        stick_post( $post_id );
     803                                }
     804                        }
     805
     806                        // map pre-import ID to local ID
     807                        $this->processed_posts[ intval( $post['post_id'] ) ] = (int) $post_id;
     808
     809                        if ( ! isset( $post['terms'] ) ) {
     810                                $post['terms'] = array();
     811                        }
     812
     813                        $post['terms'] = apply_filters( 'wp_import_post_terms', $post['terms'], $post_id, $post );
     814
     815                        // add categories, tags and other terms
     816                        if ( ! empty( $post['terms'] ) ) {
     817                                $terms_to_set = array();
     818                                foreach ( $post['terms'] as $term ) {
     819                                        // back compat with WXR 1.0 map 'tag' to 'post_tag'
     820                                        $taxonomy    = ( 'tag' == $term['domain'] ) ? 'post_tag' : $term['domain'];
     821                                        $term_exists = term_exists( $term['slug'], $taxonomy );
     822                                        $term_id     = is_array( $term_exists ) ? $term_exists['term_id'] : $term_exists;
     823                                        if ( ! $term_id ) {
     824                                                $t = wp_insert_term( $term['name'], $taxonomy, array( 'slug' => $term['slug'] ) );
     825                                                if ( ! is_wp_error( $t ) ) {
     826                                                        $term_id = $t['term_id'];
     827                                                        do_action( 'wp_import_insert_term', $t, $term, $post_id, $post );
    688828                                                } else {
    689                                                         $this->post_orphans[ intval( $post['post_id'] ) ] = $post_parent;
    690                                                         $post_parent                                      = 0;
     829                                                        printf( __( 'Failed to import %1$s %2$s', 'demo-awesome' ), esc_html( $taxonomy ), esc_html( $term['name'] ) );
     830                                                        if ( defined( 'IMPORT_DEBUG' ) && IMPORT_DEBUG ) {
     831                                                                echo ': ' . $t->get_error_message();
     832                                                        }
     833                                                        echo '<br />';
     834                                                        do_action( 'wp_import_insert_term_failed', $t, $term, $post_id, $post );
     835                                                        continue;
    691836                                                }
    692837                                        }
    693 
    694                                         // map the post author
    695                                         $author = sanitize_user( $post['post_author'], true );
    696                                         if ( isset( $this->author_mapping[ $author ] ) ) {
    697                                                 $author = $this->author_mapping[ $author ];
    698                                         } else {
    699                                                 $author = (int) get_current_user_id();
     838                                        $terms_to_set[ $taxonomy ][] = intval( $term_id );
     839                                }
     840
     841                                foreach ( $terms_to_set as $tax => $ids ) {
     842                                        $tt_ids = wp_set_post_terms( $post_id, $ids, $tax );
     843                                        do_action( 'wp_import_set_post_terms', $tt_ids, $ids, $tax, $post_id, $post );
     844                                }
     845                                unset( $post['terms'], $terms_to_set );
     846                        }
     847
     848                        if ( ! isset( $post['comments'] ) ) {
     849                                $post['comments'] = array();
     850                        }
     851
     852                        $post['comments'] = apply_filters( 'wp_import_post_comments', $post['comments'], $post_id, $post );
     853
     854                        // add/update comments
     855                        if ( ! empty( $post['comments'] ) ) {
     856                                $num_comments      = 0;
     857                                $inserted_comments = array();
     858                                foreach ( $post['comments'] as $comment ) {
     859                                        $comment_id                                    = $comment['comment_id'];
     860                                        $newcomments[ $comment_id ]['comment_post_ID'] = $comment_post_id;
     861                                        $newcomments[ $comment_id ]['comment_author']  = $comment['comment_author'];
     862                                        $newcomments[ $comment_id ]['comment_author_email'] = $comment['comment_author_email'];
     863                                        $newcomments[ $comment_id ]['comment_author_IP']    = $comment['comment_author_IP'];
     864                                        $newcomments[ $comment_id ]['comment_author_url']   = $comment['comment_author_url'];
     865                                        $newcomments[ $comment_id ]['comment_date']         = $comment['comment_date'];
     866                                        $newcomments[ $comment_id ]['comment_date_gmt']     = $comment['comment_date_gmt'];
     867                                        $newcomments[ $comment_id ]['comment_content']      = $comment['comment_content'];
     868                                        $newcomments[ $comment_id ]['comment_approved']     = $comment['comment_approved'];
     869                                        $newcomments[ $comment_id ]['comment_type']         = $comment['comment_type'];
     870                                        $newcomments[ $comment_id ]['comment_parent']       = $comment['comment_parent'];
     871                                        $newcomments[ $comment_id ]['commentmeta']          = isset( $comment['commentmeta'] ) ? $comment['commentmeta'] : array();
     872                                        if ( isset( $this->processed_authors[ $comment['comment_user_id'] ] ) ) {
     873                                                $newcomments[ $comment_id ]['user_id'] = $this->processed_authors[ $comment['comment_user_id'] ];
    700874                                        }
    701 
    702                                         $postdata = array(
    703                                                 'import_id'      => $post['post_id'],
    704                                                 'post_author'    => $author,
    705                                                 'post_date'      => $post['post_date'],
    706                                                 'post_date_gmt'  => $post['post_date_gmt'],
    707                                                 'post_content'   => $post['post_content'],
    708                                                 'post_excerpt'   => $post['post_excerpt'],
    709                                                 'post_title'     => $post['post_title'],
    710                                                 'post_status'    => $post['status'],
    711                                                 'post_name'      => $post['post_name'],
    712                                                 'comment_status' => $post['comment_status'],
    713                                                 'ping_status'    => $post['ping_status'],
    714                                                 'guid'           => $post['guid'],
    715                                                 'post_parent'    => $post_parent,
    716                                                 'menu_order'     => $post['menu_order'],
    717                                                 'post_type'      => $post['post_type'],
    718                                                 'post_password'  => $post['post_password']
    719                                         );
    720 
    721                                         $original_post_ID = $post['post_id'];
    722                                         $postdata         = apply_filters( 'wp_import_post_data_processed', $postdata, $post );
    723 
    724                                         $postdata = wp_slash( $postdata );
    725 
    726                                         if ( 'attachment' == $postdata['post_type'] ) {
    727                                                 $remote_url = ! empty( $post['attachment_url'] ) ? $post['attachment_url'] : $post['guid'];
    728 
    729                                                 // try to use _wp_attached file for upload folder placement to ensure the same location as the export site
    730                                                 // e.g. location is 2003/05/image.jpg but the attachment post_date is 2010/09, see media_handle_upload()
    731                                                 $postdata['upload_date'] = $post['post_date'];
    732                                                 if ( isset( $post['postmeta'] ) ) {
    733                                                         foreach ( $post['postmeta'] as $meta ) {
    734                                                                 if ( $meta['key'] == '_wp_attached_file' ) {
    735                                                                         if ( preg_match( '%^[0-9]{4}/[0-9]{2}%', $meta['value'], $matches ) ) {
    736                                                                                 $postdata['upload_date'] = $matches[0];
    737                                                                         }
    738                                                                         break;
    739                                                                 }
    740                                                         }
     875                                }
     876                                ksort( $newcomments );
     877
     878                                foreach ( $newcomments as $key => $comment ) {
     879                                        // if this is a new post we can skip the comment_exists() check
     880                                        if ( ! $post_exists || ! comment_exists( $comment['comment_author'], $comment['comment_date'] ) ) {
     881                                                if ( isset( $inserted_comments[ $comment['comment_parent'] ] ) ) {
     882                                                        $comment['comment_parent'] = $inserted_comments[ $comment['comment_parent'] ];
    741883                                                }
    742884
    743                                                 $comment_post_ID = $post_id = $this->process_attachment( $postdata, $remote_url );
    744                                         } else {
    745                                                 $comment_post_ID = $post_id = wp_insert_post( $postdata, true );
    746                                                 do_action( 'wp_import_insert_post', $post_id, $original_post_ID, $postdata, $post );
     885                                                $comment_data = wp_slash( $comment );
     886                                                unset( $comment_data['commentmeta'] ); // Handled separately, wp_insert_comment() also expects `comment_meta`.
     887                                                $comment_data = wp_filter_comment( $comment_data );
     888
     889                                                $inserted_comments[ $key ] = wp_insert_comment( $comment_data );
     890
     891                                                do_action( 'wp_import_insert_comment', $inserted_comments[ $key ], $comment, $comment_post_id, $post );
     892
     893                                                foreach ( $comment['commentmeta'] as $meta ) {
     894                                                        $value = $this->maybe_unserialize( $meta['value'] );
     895
     896                                                        add_comment_meta( $inserted_comments[ $key ], wp_slash( $meta['key'] ), wp_slash_strings_only( $value ) );
     897                                                }
     898
     899                                                ++$num_comments;
    747900                                        }
    748 
    749                                         if ( is_wp_error( $post_id ) ) {
    750                                                 printf( esc_html__( 'Failed to import %s &#8220;%s&#8221;', 'demo-awesome' ),
    751                                                         $post_type_object->labels->singular_name, esc_html( $post['post_title'] ) );
    752                                                 if ( defined( 'IMPORT_DEBUG' ) && IMPORT_DEBUG ) {
    753                                                         echo ': ' . esc_html( $post_id->get_error_message());
    754                                                 }
    755                                                 echo '<br />';
    756                                                 continue;
    757                                         }
    758 
    759                                         if ( $post['is_sticky'] == 1 ) {
    760                                                 stick_post( $post_id );
    761                                         }
    762                                 }
    763 
    764                                 // map pre-import ID to local ID
    765                                 $this->processed_posts[ intval( $post['post_id'] ) ] = (int) $post_id;
    766 
    767                                 if ( ! isset( $post['terms'] ) ) {
    768                                         $post['terms'] = array();
    769                                 }
    770 
    771                                 $post['terms'] = apply_filters( 'wp_import_post_terms', $post['terms'], $post_id, $post );
    772 
    773                                 // add categories, tags and other terms
    774                                 if ( ! empty( $post['terms'] ) ) {
    775                                         $terms_to_set = array();
    776                                         foreach ( $post['terms'] as $term ) {
    777                                                 // back compat with WXR 1.0 map 'tag' to 'post_tag'
    778                                                 $taxonomy    = ( 'tag' == $term['domain'] ) ? 'post_tag' : $term['domain'];
    779                                                 $term_exists = term_exists( $term['slug'], $taxonomy );
    780                                                 $term_id     = is_array( $term_exists ) ? $term_exists['term_id'] : $term_exists;
    781                                                 if ( ! $term_id ) {
    782                                                         $t = wp_insert_term( $term['name'], $taxonomy, array( 'slug' => $term['slug'] ) );
    783                                                         if ( ! is_wp_error( $t ) ) {
    784                                                                 $term_id = $t['term_id'];
    785                                                                 do_action( 'wp_import_insert_term', $t, $term, $post_id, $post );
    786                                                         } else {
    787                                                                 printf( esc_html__( 'Failed to import %s %s', 'demo-awesome' ), esc_html( $taxonomy ), esc_html( $term['name'] ) );
    788                                                                 if ( defined( 'IMPORT_DEBUG' ) && IMPORT_DEBUG ) {
    789                                                                         echo ': ' . $t->get_error_message();
    790                                                                 }
    791                                                                 echo '<br />';
    792                                                                 do_action( 'wp_import_insert_term_failed', $t, $term, $post_id, $post );
    793                                                                 continue;
    794                                                         }
    795                                                 }
    796                                                 $terms_to_set[ $taxonomy ][] = intval( $term_id );
    797                                         }
    798 
    799                                         foreach ( $terms_to_set as $tax => $ids ) {
    800                                                 $tt_ids = wp_set_post_terms( $post_id, $ids, $tax );
    801                                                 do_action( 'wp_import_set_post_terms', $tt_ids, $ids, $tax, $post_id, $post );
    802                                         }
    803                                         unset( $post['terms'], $terms_to_set );
    804                                 }
    805 
    806                                 if ( ! isset( $post['comments'] ) ) {
    807                                         $post['comments'] = array();
    808                                 }
    809 
    810                                 $post['comments'] = apply_filters( 'wp_import_post_comments', $post['comments'], $post_id, $post );
    811 
    812                                 // add/update comments
    813                                 if ( ! empty( $post['comments'] ) ) {
    814                                         $num_comments      = 0;
    815                                         $inserted_comments = array();
    816                                         foreach ( $post['comments'] as $comment ) {
    817                                                 $comment_id                                         = $comment['comment_id'];
    818                                                 $newcomments[ $comment_id ]['comment_post_ID']      = $comment_post_ID;
    819                                                 $newcomments[ $comment_id ]['comment_author']       = $comment['comment_author'];
    820                                                 $newcomments[ $comment_id ]['comment_author_email'] = $comment['comment_author_email'];
    821                                                 $newcomments[ $comment_id ]['comment_author_IP']    = $comment['comment_author_IP'];
    822                                                 $newcomments[ $comment_id ]['comment_author_url']   = $comment['comment_author_url'];
    823                                                 $newcomments[ $comment_id ]['comment_date']         = $comment['comment_date'];
    824                                                 $newcomments[ $comment_id ]['comment_date_gmt']     = $comment['comment_date_gmt'];
    825                                                 $newcomments[ $comment_id ]['comment_content']      = $comment['comment_content'];
    826                                                 $newcomments[ $comment_id ]['comment_approved']     = $comment['comment_approved'];
    827                                                 $newcomments[ $comment_id ]['comment_type']         = $comment['comment_type'];
    828                                                 $newcomments[ $comment_id ]['comment_parent']       = $comment['comment_parent'];
    829                                                 $newcomments[ $comment_id ]['commentmeta']          = isset( $comment['commentmeta'] ) ? $comment['commentmeta'] : array();
    830                                                 if ( isset( $this->processed_authors[ $comment['comment_user_id'] ] ) ) {
    831                                                         $newcomments[ $comment_id ]['user_id'] = $this->processed_authors[ $comment['comment_user_id'] ];
     901                                }
     902                                unset( $newcomments, $inserted_comments, $post['comments'] );
     903                        }
     904
     905                        if ( ! isset( $post['postmeta'] ) ) {
     906                                $post['postmeta'] = array();
     907                        }
     908
     909                        $post['postmeta'] = apply_filters( 'wp_import_post_meta', $post['postmeta'], $post_id, $post );
     910
     911                        // add/update post meta
     912                        if ( ! empty( $post['postmeta'] ) ) {
     913                                foreach ( $post['postmeta'] as $meta ) {
     914                                        $key   = apply_filters( 'import_post_meta_key', $meta['key'], $post_id, $post );
     915                                        $value = false;
     916
     917                                        if ( '_edit_last' == $key ) {
     918                                                if ( isset( $this->processed_authors[ intval( $meta['value'] ) ] ) ) {
     919                                                        $value = $this->processed_authors[ intval( $meta['value'] ) ];
     920                                                } else {
     921                                                        $key = false;
    832922                                                }
    833923                                        }
    834                                         ksort( $newcomments );
    835 
    836                                         foreach ( $newcomments as $key => $comment ) {
    837                                                 // if this is a new post we can skip the comment_exists() check
    838                                                 if ( ! $post_exists || ! comment_exists( $comment['comment_author'], $comment['comment_date'] ) ) {
    839                                                         if ( isset( $inserted_comments[ $comment['comment_parent'] ] ) ) {
    840                                                                 $comment['comment_parent'] = $inserted_comments[ $comment['comment_parent'] ];
    841                                                         }
    842                                                         $comment                   = wp_slash( $comment );
    843                                                         $comment                   = wp_filter_comment( $comment );
    844                                                         $inserted_comments[ $key ] = wp_insert_comment( $comment );
    845                                                         do_action( 'wp_import_insert_comment', $inserted_comments[ $key ], $comment, $comment_post_ID, $post );
    846 
    847                                                         foreach ( $comment['commentmeta'] as $meta ) {
    848                                                                 $value = maybe_unserialize( $meta['value'] );
    849                                                                 add_comment_meta( $inserted_comments[ $key ], $meta['key'], $value );
    850                                                         }
    851 
    852                                                         $num_comments ++;
     924
     925                                        if ( $key ) {
     926                                                // export gets meta straight from the DB so could have a serialized string
     927                                                if ( ! $value ) {
     928                                                        $value = $this->maybe_unserialize( $meta['value'] );
     929                                                }
     930
     931                                                add_post_meta( $post_id, wp_slash( $key ), wp_slash_strings_only( $value ) );
     932
     933                                                do_action( 'import_post_meta', $post_id, $key, $value );
     934
     935                                                // if the post has a featured image, take note of this in case of remap
     936                                                if ( '_thumbnail_id' == $key ) {
     937                                                        $this->featured_images[ $post_id ] = (int) $value;
    853938                                                }
    854939                                        }
    855                                         unset( $newcomments, $inserted_comments, $post['comments'] );
    856                                 }
    857 
    858                                 if ( ! isset( $post['postmeta'] ) ) {
    859                                         $post['postmeta'] = array();
    860                                 }
    861 
    862                                 $post['postmeta'] = apply_filters( 'wp_import_post_meta', $post['postmeta'], $post_id, $post );
    863 
    864                                 // add/update post meta
    865                                 if ( ! empty( $post['postmeta'] ) ) {
    866                                         foreach ( $post['postmeta'] as $meta ) {
    867                                                 $key   = apply_filters( 'import_post_meta_key', $meta['key'], $post_id, $post );
    868                                                 $value = false;
    869 
    870                                                 if ( '_edit_last' == $key ) {
    871                                                         if ( isset( $this->processed_authors[ intval( $meta['value'] ) ] ) ) {
    872                                                                 $value = $this->processed_authors[ intval( $meta['value'] ) ];
    873                                                         } else {
    874                                                                 $key = false;
    875                                                         }
    876                                                 }
    877 
    878                                                 if ( $key ) {
    879                                                         // export gets meta straight from the DB so could have a serialized string
    880                                                         if ( ! $value ) {
    881                                                                 $value = maybe_unserialize( $meta['value'] );
    882                                                         }
    883 
    884                                                         add_post_meta( $post_id, $key, $value );
    885                                                         do_action( 'import_post_meta', $post_id, $key, $value );
    886 
    887                                                         // if the post has a featured image, take note of this in case of remap
    888                                                         if ( '_thumbnail_id' == $key ) {
    889                                                                 $this->featured_images[ $post_id ] = (int) $value;
    890                                                         }
    891                                                 }
    892                                         }
    893                                 }
    894                         }
    895 
    896                         unset( $this->posts );
    897                 }
    898 
    899                 /**
    900                  * Attempt to create a new menu item from import data
    901                  *
    902                  * Fails for draft, orphaned menu items and those without an associated nav_menu
    903                  * or an invalid nav_menu term. If the post type or term object which the menu item
    904                  * represents doesn't exist then the menu item will not be imported (waits until the
    905                  * end of the import to retry again before discarding).
    906                  *
    907                  * @param array $item Menu item details from WXR file
    908                  */
    909                 function process_menu_item( $item ) {
    910                         // skip draft, orphaned menu items
    911                         if ( 'draft' == $item['status'] ) {
    912                                 return;
    913                         }
    914 
    915                         $menu_slug = false;
    916                         if ( isset( $item['terms'] ) ) {
    917                                 // loop through terms, assume first nav_menu term is correct menu
    918                                 foreach ( $item['terms'] as $term ) {
    919                                         if ( 'nav_menu' == $term['domain'] ) {
    920                                                 $menu_slug = $term['slug'];
    921                                                 break;
    922                                         }
    923                                 }
    924                         }
    925 
    926                         // no nav_menu term associated with this menu item
    927                         if ( ! $menu_slug ) {
    928                                 _e( 'Menu item skipped due to missing menu slug', 'demo-awesome' );
    929                                 echo '<br />';
    930 
    931                                 return;
    932                         }
    933 
    934                         $menu_id = term_exists( $menu_slug, 'nav_menu' );
    935                         if ( ! $menu_id ) {
    936                                 printf( esc_html__( 'Menu item skipped due to invalid menu slug: %s', 'demo-awesome' ), esc_html( $menu_slug ) );
    937                                 echo '<br />';
    938 
    939                                 return;
    940                         } else {
    941                                 $menu_id = is_array( $menu_id ) ? $menu_id['term_id'] : $menu_id;
    942                         }
    943                         foreach ( $item['postmeta'] as $meta ) {
    944                                 if ( version_compare( PHP_VERSION, '7.0.0' ) >= 0 ) {
    945                                         ${$meta['key']} = $meta['value'];
    946                                 } else {
    947                                         $$meta['key'] = $meta['value'];
    948                                 }
    949                         }
    950 
    951                         if ( 'taxonomy' == $_menu_item_type && isset( $this->processed_terms[ intval( $_menu_item_object_id ) ] ) ) {
    952                                 $_menu_item_object_id = $this->processed_terms[ intval( $_menu_item_object_id ) ];     
    953                         } else if ( 'post_type' == $_menu_item_type && isset( $this->processed_posts[ intval( $_menu_item_object_id ) ] ) ) {
    954                                 $_menu_item_object_id = $this->processed_posts[ intval( $_menu_item_object_id ) ];
    955                         } else if ( 'custom' != $_menu_item_type ) {
    956                                 // associated object is missing or not imported yet, we'll retry later
    957                                 $this->missing_menu_items[] = $item;
    958 
    959                                 return;
    960                         }
    961 
    962                         if ( isset( $this->processed_menu_items[ intval( $_menu_item_menu_item_parent ) ] ) ) {
    963                                 $_menu_item_menu_item_parent = $this->processed_menu_items[ intval( $_menu_item_menu_item_parent ) ];
    964                         } else if ( $_menu_item_menu_item_parent ) {
    965                                 $this->menu_item_orphans[ intval( $item['post_id'] ) ] = (int) $_menu_item_menu_item_parent;
    966                                 $_menu_item_menu_item_parent                           = 0;
    967                         }
    968 
    969                         // wp_update_nav_menu_item expects CSS classes as a space separated string
    970                         $_menu_item_classes = maybe_unserialize( $_menu_item_classes );
    971                         if ( is_array( $_menu_item_classes ) ) {
    972                                 $_menu_item_classes = implode( ' ', $_menu_item_classes );
    973                         }
    974 
    975                         $args = array(
    976                                 'menu-item-object-id'   => $_menu_item_object_id,
    977                                 'menu-item-object'      => $_menu_item_object,
    978                                 'menu-item-parent-id'   => $_menu_item_menu_item_parent,
    979                                 'menu-item-position'    => intval( $item['menu_order'] ),
    980                                 'menu-item-type'        => $_menu_item_type,
    981                                 'menu-item-title'       => $item['post_title'],
    982                                 'menu-item-url'         => $_menu_item_url,
    983                                 'menu-item-description' => $item['post_content'],
    984                                 'menu-item-attr-title'  => $item['post_excerpt'],
    985                                 'menu-item-target'      => $_menu_item_target,
    986                                 'menu-item-classes'     => $_menu_item_classes,
    987                                 'menu-item-xfn'         => $_menu_item_xfn,
    988                                 'menu-item-status'      => $item['status']
     940                                }
     941                        }
     942                }
     943
     944                unset( $this->posts );
     945        }
     946
     947        /**
     948         * Attempt to create a new menu item from import data
     949         *
     950         * Fails for draft, orphaned menu items and those without an associated nav_menu
     951         * or an invalid nav_menu term. If the post type or term object which the menu item
     952         * represents doesn't exist then the menu item will not be imported (waits until the
     953         * end of the import to retry again before discarding).
     954         *
     955         * @param array $item Menu item details from WXR file
     956         */
     957        public function process_menu_item( $item ) {
     958                // skip draft, orphaned menu items
     959                if ( 'draft' == $item['status'] ) {
     960                        return;
     961                }
     962
     963                $menu_slug = false;
     964                if ( isset( $item['terms'] ) ) {
     965                        // loop through terms, assume first nav_menu term is correct menu
     966                        foreach ( $item['terms'] as $term ) {
     967                                if ( 'nav_menu' == $term['domain'] ) {
     968                                        $menu_slug = $term['slug'];
     969                                        break;
     970                                }
     971                        }
     972                }
     973
     974                // no nav_menu term associated with this menu item
     975                if ( ! $menu_slug ) {
     976                        _e( 'Menu item skipped due to missing menu slug', 'demo-awesome' );
     977                        echo '<br />';
     978                        return;
     979                }
     980
     981                $menu_id = term_exists( $menu_slug, 'nav_menu' );
     982                if ( ! $menu_id ) {
     983                        printf( __( 'Menu item skipped due to invalid menu slug: %s', 'demo-awesome' ), esc_html( $menu_slug ) );
     984                        echo '<br />';
     985                        return;
     986                } else {
     987                        $menu_id = is_array( $menu_id ) ? $menu_id['term_id'] : $menu_id;
     988                }
     989
     990                foreach ( $item['postmeta'] as $meta ) {
     991                        ${$meta['key']} = $meta['value'];
     992                }
     993
     994                if ( 'taxonomy' == $_menu_item_type && isset( $this->processed_terms[ intval( $_menu_item_object_id ) ] ) ) {
     995                        $_menu_item_object_id = $this->processed_terms[ intval( $_menu_item_object_id ) ];
     996                } elseif ( 'post_type' == $_menu_item_type && isset( $this->processed_posts[ intval( $_menu_item_object_id ) ] ) ) {
     997                        $_menu_item_object_id = $this->processed_posts[ intval( $_menu_item_object_id ) ];
     998                } elseif ( 'custom' != $_menu_item_type ) {
     999                        // associated object is missing or not imported yet, we'll retry later
     1000                        $this->missing_menu_items[] = $item;
     1001                        return;
     1002                }
     1003
     1004                if ( isset( $this->processed_menu_items[ intval( $_menu_item_menu_item_parent ) ] ) ) {
     1005                        $_menu_item_menu_item_parent = $this->processed_menu_items[ intval( $_menu_item_menu_item_parent ) ];
     1006                } elseif ( $_menu_item_menu_item_parent ) {
     1007                        $this->menu_item_orphans[ intval( $item['post_id'] ) ] = (int) $_menu_item_menu_item_parent;
     1008                        $_menu_item_menu_item_parent                           = 0;
     1009                }
     1010
     1011                // wp_update_nav_menu_item expects CSS classes as a space separated string
     1012                $_menu_item_classes = $this->maybe_unserialize( $_menu_item_classes );
     1013                if ( is_array( $_menu_item_classes ) ) {
     1014                        $_menu_item_classes = implode( ' ', $_menu_item_classes );
     1015                }
     1016
     1017                $args = array(
     1018                        'menu-item-object-id'   => $_menu_item_object_id,
     1019                        'menu-item-object'      => $_menu_item_object,
     1020                        'menu-item-parent-id'   => $_menu_item_menu_item_parent,
     1021                        'menu-item-position'    => intval( $item['menu_order'] ),
     1022                        'menu-item-type'        => $_menu_item_type,
     1023                        'menu-item-title'       => $item['post_title'],
     1024                        'menu-item-url'         => $_menu_item_url,
     1025                        'menu-item-description' => $item['post_content'],
     1026                        'menu-item-attr-title'  => $item['post_excerpt'],
     1027                        'menu-item-target'      => $_menu_item_target,
     1028                        'menu-item-classes'     => $_menu_item_classes,
     1029                        'menu-item-xfn'         => $_menu_item_xfn,
     1030                        'menu-item-status'      => $item['status'],
     1031                );
     1032
     1033                $id = wp_update_nav_menu_item( $menu_id, 0, $args );
     1034                if ( $id && ! is_wp_error( $id ) ) {
     1035                        $this->processed_menu_items[ intval( $item['post_id'] ) ] = (int) $id;
     1036                }
     1037        }
     1038
     1039        /**
     1040         * If fetching attachments is enabled then attempt to create a new attachment
     1041         *
     1042         * @param array $post Attachment post details from WXR
     1043         * @param string $url URL to fetch attachment from
     1044         * @return int|WP_Error Post ID on success, WP_Error otherwise
     1045         */
     1046        public function process_attachment( $post, $url ) {
     1047                if ( ! $this->fetch_attachments ) {
     1048                        return new WP_Error(
     1049                                'attachment_processing_error',
     1050                                __( 'Fetching attachments is not enabled', 'demo-awesome' )
    9891051                        );
    990 
    991                         $id = wp_update_nav_menu_item( $menu_id, 0, $args );
    992                         if ( $id && ! is_wp_error( $id ) ) {
    993                                 //fix to update mega menu data
    994                                 foreach ( $item['postmeta'] as $meta ) {
    995                                         if (strpos($meta['key'],'evolve_mega') !== false) {
    996                                                 update_post_meta($id, $meta['key'], maybe_unserialize($meta['value']));
    997                                         }
    998                                 }
    999                                 $this->processed_menu_items[ intval( $item['post_id'] ) ] = (int) $id;
    1000                         }
    1001                 }
    1002 
    1003                 /**
    1004                  * If fetching attachments is enabled then attempt to create a new attachment
    1005                  *
    1006                  * @param array $post Attachment post details from WXR
    1007                  * @param string $url URL to fetch attachment from
    1008                  *
    1009                  * @return int|WP_Error Post ID on success, WP_Error otherwise
    1010                  */
    1011                 function process_attachment( $post, $url ) {
    1012                         if ( ! $this->fetch_attachments ) {
    1013                                 return new WP_Error( 'attachment_processing_error',
    1014                                         esc_html__( 'Fetching attachments is not enabled', 'demo-awesome' ) );
    1015                         }
    1016 
    1017                         // if the URL is absolute, but does not contain address, then upload it assuming base_site_url
    1018                         if ( preg_match( '|^/[\w\W]+$|', $url ) ) {
    1019                                 $url = rtrim( $this->base_url, '/' ) . $url;
    1020                         }
    1021 
    1022                         $upload = $this->fetch_remote_file( $url, $post );
    1023                         if ( is_wp_error( $upload ) ) {
    1024                                 return $upload;
    1025                         }
    1026 
    1027                         if ( $info = wp_check_filetype( $upload['file'] ) ) {
    1028                                 $post['post_mime_type'] = $info['type'];
    1029                         } else {
    1030                                 return new WP_Error( 'attachment_processing_error', esc_html__( 'Invalid file type', 'demo-awesome' ) );
    1031                         }
    1032 
    1033                         $post['guid'] = $upload['url'];
    1034 
    1035                         // as per wp-admin/includes/upload.php
    1036                         $post_id = wp_insert_attachment( $post, $upload['file'] );
    1037                         wp_update_attachment_metadata( $post_id, wp_generate_attachment_metadata( $post_id, $upload['file'] ) );
    1038 
    1039                         // remap resized image URLs, works by stripping the extension and remapping the URL stub.
    1040                         if ( preg_match( '!^image/!', $info['type'] ) ) {
    1041                                 $parts = pathinfo( $url );
    1042                                 $name  = basename( $parts['basename'], ".{$parts['extension']}" ); // PATHINFO_FILENAME in PHP 5.2
    1043 
    1044                                 $parts_new = pathinfo( $upload['url'] );
    1045                                 $name_new  = basename( $parts_new['basename'], ".{$parts_new['extension']}" );
    1046 
    1047                                 $this->url_remap[ $parts['dirname'] . '/' . $name ] = $parts_new['dirname'] . '/' . $name_new;
    1048                         }
    1049 
    1050                         return $post_id;
    1051                 }
    1052 
    1053                 /**
    1054                  * Attempt to download a remote file attachment
    1055                  *
    1056                  * @param string $url URL of item to fetch
    1057                  * @param array $post Attachment details
    1058                  *
    1059                  * @return array|WP_Error Local file location details on success, WP_Error otherwise
    1060                  */
    1061                 function fetch_remote_file( $url, $post ) {
    1062                         // extract the file name and extension from the url
    1063                         $file_name = basename( $url );
    1064 
    1065                         // get placeholder file in the upload dir with a unique, sanitized filename
    1066                         $upload = wp_upload_bits( $file_name, 0, '', $post['upload_date'] );
    1067                         if ( $upload['error'] ) {
    1068                                 return new WP_Error( 'upload_dir_error', $upload['error'] );
    1069                         }
    1070 
    1071                         // fetch the remote url and write it to the placeholder file
    1072                         $remote_response = wp_safe_remote_get( $url, array(
     1052                }
     1053
     1054                // if the URL is absolute, but does not contain address, then upload it assuming base_site_url
     1055                if ( preg_match( '|^/[\w\W]+$|', $url ) ) {
     1056                        $url = rtrim( $this->base_url, '/' ) . $url;
     1057                }
     1058
     1059                $upload = $this->fetch_remote_file( $url, $post );
     1060                if ( is_wp_error( $upload ) ) {
     1061                        return $upload;
     1062                }
     1063
     1064                $info = wp_check_filetype( $upload['file'] );
     1065                if ( $info ) {
     1066                        $post['post_mime_type'] = $info['type'];
     1067                } else {
     1068                        return new WP_Error( 'attachment_processing_error', __( 'Invalid file type', 'demo-awesome' ) );
     1069                }
     1070
     1071                $post['guid'] = $upload['url'];
     1072
     1073                // as per wp-admin/includes/upload.php
     1074                $post_id = wp_insert_attachment( $post, $upload['file'] );
     1075                wp_update_attachment_metadata( $post_id, wp_generate_attachment_metadata( $post_id, $upload['file'] ) );
     1076
     1077                // remap resized image URLs, works by stripping the extension and remapping the URL stub.
     1078                if ( preg_match( '!^image/!', $info['type'] ) ) {
     1079                        $parts = pathinfo( $url );
     1080                        $name  = basename( $parts['basename'], ".{$parts['extension']}" ); // PATHINFO_FILENAME in PHP 5.2
     1081
     1082                        $parts_new = pathinfo( $upload['url'] );
     1083                        $name_new  = basename( $parts_new['basename'], ".{$parts_new['extension']}" );
     1084
     1085                        $this->url_remap[ $parts['dirname'] . '/' . $name ] = $parts_new['dirname'] . '/' . $name_new;
     1086                }
     1087
     1088                return $post_id;
     1089        }
     1090
     1091        /**
     1092         * Attempt to download a remote file attachment
     1093         *
     1094         * @param string $url URL of item to fetch
     1095         * @param array $post Attachment details
     1096         * @return array|WP_Error Local file location details on success, WP_Error otherwise
     1097         */
     1098        public function fetch_remote_file( $url, $post ) {
     1099                // Extract the file name from the URL.
     1100                $path      = parse_url( $url, PHP_URL_PATH );
     1101                $file_name = '';
     1102                if ( is_string( $path ) ) {
     1103                        $file_name = basename( $path );
     1104                }
     1105
     1106                if ( ! $file_name ) {
     1107                        $file_name = md5( $url );
     1108                }
     1109
     1110                $tmp_file_name = wp_tempnam( $file_name );
     1111                if ( ! $tmp_file_name ) {
     1112                        return new WP_Error( 'import_no_file', __( 'Could not create temporary file.', 'demo-awesome' ) );
     1113                }
     1114
     1115                // Fetch the remote URL and write it to the placeholder file.
     1116                $remote_response = wp_safe_remote_get(
     1117                        $url,
     1118                        array(
    10731119                                'timeout'  => 300,
    10741120                                'stream'   => true,
    1075                                 'filename' => $upload['file'],
    1076                         ) );
    1077 
    1078                         $headers = wp_remote_retrieve_headers( $remote_response );
    1079 
    1080                         // request failed
    1081                         if ( ! $headers ) {
    1082                                 @unlink( $upload['file'] );
    1083 
    1084                                 return new WP_Error( 'import_file_error', esc_html__( 'Remote server did not respond', 'demo-awesome' ) );
    1085                         }
    1086 
    1087                         $remote_response_code = wp_remote_retrieve_response_code( $remote_response );
    1088 
    1089                         // make sure the fetch was successful
    1090                         if ( $remote_response_code != '200' ) {
    1091                                 @unlink( $upload['file'] );
    1092 
    1093                                 return new WP_Error( 'import_file_error', sprintf( esc_html__( 'Remote server returned error response %1$d %2$s', 'demo-awesome' ), esc_html( $remote_response_code ), get_status_header_desc( $remote_response_code ) ) );
    1094                         }
    1095 
    1096                         $filesize = filesize( $upload['file'] );
    1097 
    1098                         if ( isset( $headers['content-length'] ) && $filesize != $headers['content-length'] ) {
    1099                                 @unlink( $upload['file'] );
    1100 
    1101                                 return new WP_Error( 'import_file_error', esc_html__( 'Remote file is incorrect size', 'demo-awesome' ) );
    1102                         }
    1103 
    1104                         if ( 0 == $filesize ) {
    1105                                 @unlink( $upload['file'] );
    1106 
    1107                                 return new WP_Error( 'import_file_error', esc_html__( 'Zero size file downloaded', 'demo-awesome' ) );
    1108                         }
    1109 
    1110                         $max_size = (int) $this->max_attachment_size();
    1111                         if ( ! empty( $max_size ) && $filesize > $max_size ) {
    1112                                 @unlink( $upload['file'] );
    1113 
    1114                                 return new WP_Error( 'import_file_error', sprintf( esc_html__( 'Remote file is too large, limit is %s', 'demo-awesome' ), size_format( $max_size ) ) );
    1115                         }
    1116 
    1117                         // keep track of the old and new urls so we can substitute them later
    1118                         $this->url_remap[ $url ]          = $upload['url'];
    1119                         $this->url_remap[ $post['guid'] ] = $upload['url']; // r13735, really needed?
    1120                         // keep track of the destination if the remote url is redirected somewhere else
    1121                         if ( isset( $headers['x-final-location'] ) && $headers['x-final-location'] != $url ) {
    1122                                 $this->url_remap[ $headers['x-final-location'] ] = $upload['url'];
    1123                         }
    1124 
    1125                         return $upload;
    1126                 }
    1127 
    1128                 /**
    1129                  * Attempt to associate posts and menu items with previously missing parents
    1130                  *
    1131                  * An imported post's parent may not have been imported when it was first created
    1132                  * so try again. Similarly for child menu items and menu items which were missing
    1133                  * the object (e.g. post) they represent in the menu
    1134                  */
    1135                 function backfill_parents() {
    1136                         global $wpdb;
    1137 
    1138                         // find parents for post orphans
    1139                         foreach ( $this->post_orphans as $child_id => $parent_id ) {
    1140                                 $local_child_id = $local_parent_id = false;
    1141                                 if ( isset( $this->processed_posts[ $child_id ] ) ) {
    1142                                         $local_child_id = $this->processed_posts[ $child_id ];
    1143                                 }
    1144                                 if ( isset( $this->processed_posts[ $parent_id ] ) ) {
    1145                                         $local_parent_id = $this->processed_posts[ $parent_id ];
    1146                                 }
    1147 
    1148                                 if ( $local_child_id && $local_parent_id ) {
    1149                                         $wpdb->update( $wpdb->posts, array( 'post_parent' => $local_parent_id ), array( 'ID' => $local_child_id ), '%d', '%d' );
    1150                                         clean_post_cache( $local_child_id );
    1151                                 }
    1152                         }
    1153 
    1154                         // all other posts/terms are imported, retry menu items with missing associated object
    1155                         $missing_menu_items = $this->missing_menu_items;
    1156                         foreach ( $missing_menu_items as $item ) {
    1157                                 $this->process_menu_item( $item );
    1158                         }
    1159 
    1160                         // find parents for menu item orphans
    1161                         foreach ( $this->menu_item_orphans as $child_id => $parent_id ) {
    1162                                 $local_child_id = $local_parent_id = 0;
    1163                                 if ( isset( $this->processed_menu_items[ $child_id ] ) ) {
    1164                                         $local_child_id = $this->processed_menu_items[ $child_id ];
    1165                                 }
    1166                                 if ( isset( $this->processed_menu_items[ $parent_id ] ) ) {
    1167                                         $local_parent_id = $this->processed_menu_items[ $parent_id ];
    1168                                 }
    1169 
    1170                                 if ( $local_child_id && $local_parent_id ) {
    1171                                         update_post_meta( $local_child_id, '_menu_item_menu_item_parent', (int) $local_parent_id );
    1172                                 }
    1173                         }
    1174                 }
    1175 
    1176                 /**
    1177                  * Use stored mapping information to update old attachment URLs
    1178                  */
    1179                 function backfill_attachment_urls() {
    1180                         global $wpdb;
    1181                         // make sure we do the longest urls first, in case one is a substring of another
    1182                         uksort( $this->url_remap, array( &$this, 'cmpr_strlen' ) );
    1183 
    1184                         foreach ( $this->url_remap as $from_url => $to_url ) {
    1185                                 // remap urls in post_content
    1186                                 $wpdb->query( $wpdb->prepare( "UPDATE {$wpdb->posts} SET post_content = REPLACE(post_content, %s, %s)", $from_url, $to_url ) );
    1187                                 // remap enclosure urls
    1188                                 $result = $wpdb->query( $wpdb->prepare( "UPDATE {$wpdb->postmeta} SET meta_value = REPLACE(meta_value, %s, %s) WHERE meta_key='enclosure'", $from_url, $to_url ) );
    1189                         }
    1190                 }
    1191 
    1192                 /**
    1193                  * Update _thumbnail_id meta to new, imported attachment IDs
    1194                  */
    1195                 function remap_featured_images() {
    1196                         // cycle through posts that have a featured image
    1197                         foreach ( $this->featured_images as $post_id => $value ) {
    1198                                 if ( isset( $this->processed_posts[ $value ] ) ) {
    1199                                         $new_id = $this->processed_posts[ $value ];
    1200                                         // only update if there's a difference
    1201                                         if ( $new_id != $value ) {
    1202                                                 update_post_meta( $post_id, '_thumbnail_id', $new_id );
    1203                                         }
    1204                                 }
    1205                         }
    1206                 }
    1207 
    1208                 /**
    1209                  * Parse a WXR file
    1210                  *
    1211                  * @param string $file Path to WXR file for parsing
    1212                  *
    1213                  * @return array Information gathered from the WXR file
    1214                  */
    1215                 function parse( $file ) {
    1216                         $parser = new Demo_Awesome_Parser();
    1217 
    1218                         return $parser->parse( $file );
    1219                 }
    1220 
    1221                 // Display import page title
    1222                 function header() {
    1223                         echo '<div class="wrap">';
    1224                         echo '<h2>' . esc_html__( 'Import WordPress', 'demo-awesome' ) . '</h2>';
    1225 
    1226                         $updates  = get_plugin_updates();
    1227                         $basename = plugin_basename( __FILE__ );
    1228                         if ( isset( $updates[ $basename ] ) ) {
    1229                                 $update = $updates[ $basename ];
    1230                                 echo '<div class="error"><p><strong>';
    1231                                 printf( esc_html__( 'A new version of this importer is available. Please update to version %s to ensure compatibility with newer export files.', 'demo-awesome' ), $update->update->new_version );
    1232                                 echo '</strong></p></div>';
    1233                         }
    1234                 }
    1235 
    1236                 // Close div.wrap
    1237                 function footer() {
    1238                         echo '</div>';
    1239                 }
    1240 
    1241                 /**
    1242                  * Display introductory text and file upload form
    1243                  */
    1244                 function greet() {
    1245                         echo '<div class="narrow">';
    1246                         echo '<p>' . esc_html__( 'Howdy! Upload your WordPress eXtended RSS (WXR) file and we&#8217;ll import the posts, pages, comments, custom fields, categories, and tags into this site.', 'demo-awesome' ) . '</p>';
    1247                         echo '<p>' . esc_html__( 'Choose a WXR (.xml) file to upload, then click Upload file and import.', 'demo-awesome' ) . '</p>';
    1248                         wp_import_upload_form( 'admin.php?import=wordpress&amp;step=1' );
    1249                         echo '</div>';
    1250                 }
    1251 
    1252                 /**
    1253                  * Decide if the given meta key maps to information we will want to import
    1254                  *
    1255                  * @param string $key The meta key to check
    1256                  *
    1257                  * @return string|bool The key if we do want to import, false if not
    1258                  */
    1259                 function is_valid_meta_key( $key ) {
    1260                         // skip attachment metadata since we'll regenerate it from scratch
    1261                         // skip _edit_lock as not relevant for import
    1262                         if ( in_array( $key, array( '_wp_attached_file', '_wp_attachment_metadata', '_edit_lock' ) ) ) {
    1263                                 return false;
    1264                         }
    1265 
    1266                         return $key;
    1267                 }
    1268 
    1269                 /**
    1270                  * Decide whether or not the importer is allowed to create users.
    1271                  * Default is true, can be filtered via import_allow_create_users
    1272                  *
    1273                  * @return bool True if creating users is allowed
    1274                  */
    1275                 function allow_create_users() {
    1276                         return apply_filters( 'import_allow_create_users', true );
    1277                 }
    1278 
    1279                 /**
    1280                  * Decide whether or not the importer should attempt to download attachment files.
    1281                  * Default is true, can be filtered via import_allow_fetch_attachments. The choice
    1282                  * made at the import options screen must also be true, false here hides that checkbox.
    1283                  *
    1284                  * @return bool True if downloading attachments is allowed
    1285                  */
    1286                 function allow_fetch_attachments() {
    1287                         return apply_filters( 'import_allow_fetch_attachments', true );
    1288                 }
    1289 
    1290                 /**
    1291                  * Decide what the maximum file size for downloaded attachments is.
    1292                  * Default is 0 (unlimited), can be filtered via import_attachment_size_limit
    1293                  *
    1294                  * @return int Maximum attachment file size to import
    1295                  */
    1296                 function max_attachment_size() {
    1297                         return apply_filters( 'import_attachment_size_limit', 0 );
    1298                 }
    1299 
    1300                 /**
    1301                  * Added to http_request_timeout filter to force timeout at 60 seconds during import
    1302                  * @return int 60
    1303                  */
    1304                 function bump_request_timeout( $val ) {
    1305                         return 60;
    1306                 }
    1307 
    1308                 // return the difference in length between two strings
    1309                 function cmpr_strlen( $a, $b ) {
    1310                         return strlen( $b ) - strlen( $a );
    1311                 }
     1121                                'filename' => $tmp_file_name,
     1122                                'headers'  => array(
     1123                                        'Accept-Encoding' => 'identity',
     1124                                ),
     1125                        )
     1126                );
     1127
     1128                if ( is_wp_error( $remote_response ) ) {
     1129                        @unlink( $tmp_file_name );
     1130                        return new WP_Error(
     1131                                'import_file_error',
     1132                                sprintf(
     1133                                        /* translators: 1: The WordPress error message. 2: The WordPress error code. */
     1134                                        __( 'Request failed due to an error: %1$s (%2$s)', 'demo-awesome' ),
     1135                                        esc_html( $remote_response->get_error_message() ),
     1136                                        esc_html( $remote_response->get_error_code() )
     1137                                )
     1138                        );
     1139                }
     1140
     1141                $remote_response_code = (int) wp_remote_retrieve_response_code( $remote_response );
     1142
     1143                // Make sure the fetch was successful.
     1144                if ( 200 !== $remote_response_code ) {
     1145                        @unlink( $tmp_file_name );
     1146                        return new WP_Error(
     1147                                'import_file_error',
     1148                                sprintf(
     1149                                        /* translators: 1: The HTTP error message. 2: The HTTP error code. */
     1150                                        __( 'Remote server returned the following unexpected result: %1$s (%2$s)', 'demo-awesome' ),
     1151                                        get_status_header_desc( $remote_response_code ),
     1152                                        esc_html( $remote_response_code )
     1153                                )
     1154                        );
     1155                }
     1156
     1157                $headers = wp_remote_retrieve_headers( $remote_response );
     1158
     1159                // Request failed.
     1160                if ( ! $headers ) {
     1161                        @unlink( $tmp_file_name );
     1162                        return new WP_Error( 'import_file_error', __( 'Remote server did not respond', 'demo-awesome' ) );
     1163                }
     1164
     1165                $filesize = (int) filesize( $tmp_file_name );
     1166
     1167                if ( 0 === $filesize ) {
     1168                        @unlink( $tmp_file_name );
     1169                        return new WP_Error( 'import_file_error', __( 'Zero size file downloaded', 'demo-awesome' ) );
     1170                }
     1171
     1172                if ( ! isset( $headers['content-encoding'] ) && isset( $headers['content-length'] ) && $filesize !== (int) $headers['content-length'] ) {
     1173                        @unlink( $tmp_file_name );
     1174                        return new WP_Error( 'import_file_error', __( 'Downloaded file has incorrect size', 'demo-awesome' ) );
     1175                }
     1176
     1177                $max_size = (int) $this->max_attachment_size();
     1178                if ( ! empty( $max_size ) && $filesize > $max_size ) {
     1179                        @unlink( $tmp_file_name );
     1180                        return new WP_Error( 'import_file_error', sprintf( __( 'Remote file is too large, limit is %s', 'demo-awesome' ), size_format( $max_size ) ) );
     1181                }
     1182
     1183                // Override file name with Content-Disposition header value.
     1184                if ( ! empty( $headers['content-disposition'] ) ) {
     1185                        $file_name_from_disposition = self::get_filename_from_disposition( (array) $headers['content-disposition'] );
     1186                        if ( $file_name_from_disposition ) {
     1187                                $file_name = $file_name_from_disposition;
     1188                        }
     1189                }
     1190
     1191                // Set file extension if missing.
     1192                $file_ext = pathinfo( $file_name, PATHINFO_EXTENSION );
     1193                if ( ! $file_ext && ! empty( $headers['content-type'] ) ) {
     1194                        $extension = self::get_file_extension_by_mime_type( $headers['content-type'] );
     1195                        if ( $extension ) {
     1196                                $file_name = "{$file_name}.{$extension}";
     1197                        }
     1198                }
     1199
     1200                // Handle the upload like _wp_handle_upload() does.
     1201                $wp_filetype     = wp_check_filetype_and_ext( $tmp_file_name, $file_name );
     1202                $ext             = empty( $wp_filetype['ext'] ) ? '' : $wp_filetype['ext'];
     1203                $type            = empty( $wp_filetype['type'] ) ? '' : $wp_filetype['type'];
     1204                $proper_filename = empty( $wp_filetype['proper_filename'] ) ? '' : $wp_filetype['proper_filename'];
     1205
     1206                // Check to see if wp_check_filetype_and_ext() determined the filename was incorrect.
     1207                if ( $proper_filename ) {
     1208                        $file_name = $proper_filename;
     1209                }
     1210
     1211                if ( ( ! $type || ! $ext ) && ! current_user_can( 'unfiltered_upload' ) ) {
     1212                        return new WP_Error( 'import_file_error', __( 'Sorry, this file type is not permitted for security reasons.', 'demo-awesome' ) );
     1213                }
     1214
     1215                $uploads = wp_upload_dir( $post['upload_date'] );
     1216                if ( ! ( $uploads && false === $uploads['error'] ) ) {
     1217                        return new WP_Error( 'upload_dir_error', $uploads['error'] );
     1218                }
     1219
     1220                // Move the file to the uploads dir.
     1221                $file_name     = wp_unique_filename( $uploads['path'], $file_name );
     1222                $new_file      = $uploads['path'] . "/$file_name";
     1223                $move_new_file = copy( $tmp_file_name, $new_file );
     1224
     1225                if ( ! $move_new_file ) {
     1226                        @unlink( $tmp_file_name );
     1227                        return new WP_Error( 'import_file_error', __( 'The uploaded file could not be moved', 'demo-awesome' ) );
     1228                }
     1229
     1230                // Set correct file permissions.
     1231                $stat  = stat( dirname( $new_file ) );
     1232                $perms = $stat['mode'] & 0000666;
     1233                chmod( $new_file, $perms );
     1234
     1235                $upload = array(
     1236                        'file'  => $new_file,
     1237                        'url'   => $uploads['url'] . "/$file_name",
     1238                        'type'  => $wp_filetype['type'],
     1239                        'error' => false,
     1240                );
     1241
     1242                // keep track of the old and new urls so we can substitute them later
     1243                $this->url_remap[ $url ]          = $upload['url'];
     1244                $this->url_remap[ $post['guid'] ] = $upload['url']; // r13735, really needed?
     1245                // keep track of the destination if the remote url is redirected somewhere else
     1246                if ( isset( $headers['x-final-location'] ) && $headers['x-final-location'] != $url ) {
     1247                        $this->url_remap[ $headers['x-final-location'] ] = $upload['url'];
     1248                }
     1249
     1250                return $upload;
     1251        }
     1252
     1253        /**
     1254         * Attempt to associate posts and menu items with previously missing parents
     1255         *
     1256         * An imported post's parent may not have been imported when it was first created
     1257         * so try again. Similarly for child menu items and menu items which were missing
     1258         * the object (e.g. post) they represent in the menu
     1259         */
     1260        public function backfill_parents() {
     1261                global $wpdb;
     1262
     1263                // find parents for post orphans
     1264                foreach ( $this->post_orphans as $child_id => $parent_id ) {
     1265                        $local_child_id  = false;
     1266                        $local_parent_id = false;
     1267                        if ( isset( $this->processed_posts[ $child_id ] ) ) {
     1268                                $local_child_id = $this->processed_posts[ $child_id ];
     1269                        }
     1270                        if ( isset( $this->processed_posts[ $parent_id ] ) ) {
     1271                                $local_parent_id = $this->processed_posts[ $parent_id ];
     1272                        }
     1273
     1274                        if ( $local_child_id && $local_parent_id ) {
     1275                                $wpdb->update( $wpdb->posts, array( 'post_parent' => $local_parent_id ), array( 'ID' => $local_child_id ), '%d', '%d' );
     1276                                clean_post_cache( $local_child_id );
     1277                        }
     1278                }
     1279
     1280                // all other posts/terms are imported, retry menu items with missing associated object
     1281                $missing_menu_items = $this->missing_menu_items;
     1282                foreach ( $missing_menu_items as $item ) {
     1283                        $this->process_menu_item( $item );
     1284                }
     1285
     1286                // find parents for menu item orphans
     1287                foreach ( $this->menu_item_orphans as $child_id => $parent_id ) {
     1288                        $local_child_id  = 0;
     1289                        $local_parent_id = 0;
     1290                        if ( isset( $this->processed_menu_items[ $child_id ] ) ) {
     1291                                $local_child_id = $this->processed_menu_items[ $child_id ];
     1292                        }
     1293                        if ( isset( $this->processed_menu_items[ $parent_id ] ) ) {
     1294                                $local_parent_id = $this->processed_menu_items[ $parent_id ];
     1295                        }
     1296
     1297                        if ( $local_child_id && $local_parent_id ) {
     1298                                update_post_meta( $local_child_id, '_menu_item_menu_item_parent', (int) $local_parent_id );
     1299                        }
     1300                }
     1301        }
     1302
     1303        /**
     1304         * Use stored mapping information to update old attachment URLs
     1305         */
     1306        public function backfill_attachment_urls() {
     1307                global $wpdb;
     1308                // make sure we do the longest urls first, in case one is a substring of another
     1309                uksort( $this->url_remap, array( &$this, 'cmpr_strlen' ) );
     1310
     1311                foreach ( $this->url_remap as $from_url => $to_url ) {
     1312                        // remap urls in post_content
     1313                        $wpdb->query( $wpdb->prepare( "UPDATE {$wpdb->posts} SET post_content = REPLACE(post_content, %s, %s)", $from_url, $to_url ) );
     1314                        // remap enclosure urls
     1315                        $result = $wpdb->query( $wpdb->prepare( "UPDATE {$wpdb->postmeta} SET meta_value = REPLACE(meta_value, %s, %s) WHERE meta_key='enclosure'", $from_url, $to_url ) );
     1316                }
     1317        }
     1318
     1319        /**
     1320         * Update _thumbnail_id meta to new, imported attachment IDs
     1321         */
     1322        public function remap_featured_images() {
     1323                // cycle through posts that have a featured image
     1324                foreach ( $this->featured_images as $post_id => $value ) {
     1325                        if ( isset( $this->processed_posts[ $value ] ) ) {
     1326                                $new_id = $this->processed_posts[ $value ];
     1327                                // only update if there's a difference
     1328                                if ( $new_id != $value ) {
     1329                                        update_post_meta( $post_id, '_thumbnail_id', $new_id );
     1330                                }
     1331                        }
     1332                }
     1333        }
     1334
     1335        /**
     1336         * Unserialize WXR meta safely.
     1337         *
     1338         * Backported from WordPress Importer 0.9.x. Neutralizes any serialized PHP
     1339         * object in the data by rewriting it to a harmless stdClass before
     1340         * unserializing, preventing PHP object injection from a malicious WXR file.
     1341         *
     1342         * @param string $data Serialized (or plain) meta value from the WXR file.
     1343         * @return mixed The unserialized value, with objects coerced to stdClass.
     1344         */
     1345        protected function maybe_unserialize( $data ) {
     1346                if ( is_serialized( $data ) ) {
     1347                        // Transform any serialized objects into a stdClass object.
     1348                        $data = preg_replace( '/O:\d+:"[^"]+":/', 'O:8:"stdClass":', $data );
     1349
     1350                        return maybe_unserialize( $data );
     1351                }
     1352
     1353                return $data;
     1354        }
     1355
     1356        /**
     1357         * Parse a WXR file
     1358         *
     1359         * @param string $file Path to WXR file for parsing
     1360         * @return array Information gathered from the WXR file
     1361         */
     1362        public function parse( $file ) {
     1363                $parser = new Demo_Awesome_Parser();
     1364                return $parser->parse( $file );
     1365        }
     1366
     1367        // Display import page title
     1368        public function header() {
     1369                echo '<div class="wrap">';
     1370                echo '<h2>' . __( 'Import WordPress', 'demo-awesome' ) . '</h2>';
     1371
     1372                $updates  = get_plugin_updates();
     1373                $basename = plugin_basename( __FILE__ );
     1374                if ( isset( $updates[ $basename ] ) ) {
     1375                        $update = $updates[ $basename ];
     1376                        echo '<div class="error"><p><strong>';
     1377                        printf( __( 'A new version of this importer is available. Please update to version %s to ensure compatibility with newer export files.', 'demo-awesome' ), $update->update->new_version );
     1378                        echo '</strong></p></div>';
     1379                }
     1380        }
     1381
     1382        // Close div.wrap
     1383        public function footer() {
     1384                echo '</div>';
     1385        }
     1386
     1387        /**
     1388         * Display introductory text and file upload form
     1389         */
     1390        public function greet() {
     1391                echo '<div class="narrow">';
     1392                echo '<p>' . __( 'Howdy! Upload your WordPress eXtended RSS (WXR) file and we&#8217;ll import the posts, pages, comments, custom fields, categories, and tags into this site.', 'demo-awesome' ) . '</p>';
     1393                echo '<p>' . __( 'Choose a WXR (.xml) file to upload, then click Upload file and import.', 'demo-awesome' ) . '</p>';
     1394                wp_import_upload_form( 'admin.php?import=wordpress&amp;step=1' );
     1395                echo '</div>';
     1396        }
     1397
     1398        /**
     1399         * Decide if the given meta key maps to information we will want to import
     1400         *
     1401         * @param string $key The meta key to check
     1402         * @return string|bool The key if we do want to import, false if not
     1403         */
     1404        public function is_valid_meta_key( $key ) {
     1405                // skip attachment metadata since we'll regenerate it from scratch
     1406                // skip _edit_lock as not relevant for import
     1407                if ( in_array( $key, array( '_wp_attached_file', '_wp_attachment_metadata', '_edit_lock' ), true ) ) {
     1408                        return false;
     1409                }
     1410                return $key;
     1411        }
     1412
     1413        /**
     1414         * Decide whether or not the importer is allowed to create users.
     1415         * Default is true, can be filtered via import_allow_create_users
     1416         *
     1417         * @return bool True if creating users is allowed
     1418         */
     1419        public function allow_create_users() {
     1420                return apply_filters( 'import_allow_create_users', true );
     1421        }
     1422
     1423        /**
     1424         * Decide whether or not the importer should attempt to download attachment files.
     1425         * Default is true, can be filtered via import_allow_fetch_attachments. The choice
     1426         * made at the import options screen must also be true, false here hides that checkbox.
     1427         *
     1428         * @return bool True if downloading attachments is allowed
     1429         */
     1430        public function allow_fetch_attachments() {
     1431                return apply_filters( 'import_allow_fetch_attachments', true );
     1432        }
     1433
     1434        /**
     1435         * Decide what the maximum file size for downloaded attachments is.
     1436         * Default is 0 (unlimited), can be filtered via import_attachment_size_limit
     1437         *
     1438         * @return int Maximum attachment file size to import
     1439         */
     1440        public function max_attachment_size() {
     1441                return apply_filters( 'import_attachment_size_limit', 0 );
     1442        }
     1443
     1444        /**
     1445         * Added to http_request_timeout filter to force timeout at 60 seconds during import
     1446         * @return int 60
     1447         */
     1448        public function bump_request_timeout( $val ) {
     1449                return 60;
     1450        }
     1451
     1452        // return the difference in length between two strings
     1453        public function cmpr_strlen( $a, $b ) {
     1454                return strlen( $b ) - strlen( $a );
     1455        }
     1456
     1457        /**
     1458         * Parses filename from a Content-Disposition header value.
     1459         *
     1460         * As per RFC6266:
     1461         *
     1462         *     content-disposition = "Content-Disposition" ":"
     1463         *                            disposition-type *( ";" disposition-parm )
     1464         *
     1465         *     disposition-type    = "inline" | "attachment" | disp-ext-type
     1466         *                         ; case-insensitive
     1467         *     disp-ext-type       = token
     1468         *
     1469         *     disposition-parm    = filename-parm | disp-ext-parm
     1470         *
     1471         *     filename-parm       = "filename" "=" value
     1472         *                         | "filename*" "=" ext-value
     1473         *
     1474         *     disp-ext-parm       = token "=" value
     1475         *                         | ext-token "=" ext-value
     1476         *     ext-token           = <the characters in token, followed by "*">
     1477         *
     1478         * @since 0.7.0
     1479         *
     1480         * @see WP_REST_Attachments_Controller::get_filename_from_disposition()
     1481         *
     1482         * @link http://tools.ietf.org/html/rfc2388
     1483         * @link http://tools.ietf.org/html/rfc6266
     1484         *
     1485         * @param string[] $disposition_header List of Content-Disposition header values.
     1486         * @return string|null Filename if available, or null if not found.
     1487         */
     1488        protected static function get_filename_from_disposition( $disposition_header ) {
     1489                // Get the filename.
     1490                $filename = null;
     1491
     1492                foreach ( $disposition_header as $value ) {
     1493                        $value = trim( $value );
     1494
     1495                        if ( strpos( $value, ';' ) === false ) {
     1496                                continue;
     1497                        }
     1498
     1499                        list( $type, $attr_parts ) = explode( ';', $value, 2 );
     1500
     1501                        $attr_parts = explode( ';', $attr_parts );
     1502                        $attributes = array();
     1503
     1504                        foreach ( $attr_parts as $part ) {
     1505                                if ( strpos( $part, '=' ) === false ) {
     1506                                        continue;
     1507                                }
     1508
     1509                                list( $key, $value ) = explode( '=', $part, 2 );
     1510
     1511                                $attributes[ trim( $key ) ] = trim( $value );
     1512                        }
     1513
     1514                        if ( empty( $attributes['filename'] ) ) {
     1515                                continue;
     1516                        }
     1517
     1518                        $filename = trim( $attributes['filename'] );
     1519
     1520                        // Unquote quoted filename, but after trimming.
     1521                        if ( substr( $filename, 0, 1 ) === '"' && substr( $filename, -1, 1 ) === '"' ) {
     1522                                $filename = substr( $filename, 1, -1 );
     1523                        }
     1524                }
     1525
     1526                return $filename;
     1527        }
     1528
     1529        /**
     1530         * Retrieves file extension by mime type.
     1531         *
     1532         * @since 0.7.0
     1533         *
     1534         * @param string $mime_type Mime type to search extension for.
     1535         * @return string|null File extension if available, or null if not found.
     1536         */
     1537        protected static function get_file_extension_by_mime_type( $mime_type ) {
     1538                static $map = null;
     1539
     1540                if ( is_array( $map ) ) {
     1541                        return isset( $map[ $mime_type ] ) ? $map[ $mime_type ] : null;
     1542                }
     1543
     1544                $mime_types = wp_get_mime_types();
     1545                $map        = array_flip( $mime_types );
     1546
     1547                // Some types have multiple extensions, use only the first one.
     1548                foreach ( $map as $type => $extensions ) {
     1549                        $map[ $type ] = strtok( $extensions, '|' );
     1550                }
     1551
     1552                return isset( $map[ $mime_type ] ) ? $map[ $mime_type ] : null;
    13121553        }
    13131554}
  • demo-awesome/trunk/inc/admin/importer/class-demo-awesome-widget-importer.php

    r2158733 r3813524  
    3131                        global $wp_registered_sidebars;
    3232
    33                         $data = json_decode( file_get_contents( $import_file ) );
     33                        // Security: Validate file path and content
     34                        if (!self::validate_import_file($import_file)) {
     35                                return new WP_Error( 'demo_awesome_widget_import_file_error', esc_html__( 'Invalid import file.', 'demo-awesome' ) );
     36                        }
     37
     38                        $file_content = file_get_contents( $import_file );
     39                        if ($file_content === false) {
     40                                return new WP_Error( 'demo_awesome_widget_import_file_error', esc_html__( 'Could not read import file.', 'demo-awesome' ) );
     41                        }
     42
     43                        // Security: Validate file content
     44                        if (!self::validate_file_content($file_content)) {
     45                                return new WP_Error( 'demo_awesome_widget_import_content_error', esc_html__( 'Invalid file content detected.', 'demo-awesome' ) );
     46                        }
     47
     48                        $data = json_decode( $file_content );
    3449
    3550                        // Have valid data? If no data or could not decode.
    … …  
    112127                                         * Do before identical check because changes may make it identical to end result (such as URL replacements).
    113128                                         */
    114                                         $widget = apply_filters( 'widget_demo_import_settings', $widget, $id_base, $instance_id_number, $data_demo );
     129                                        $widget = apply_filters( 'demo_awesome_widget_import_settings', $widget, $id_base, $instance_id_number, $data_demo );
    115130
    116131                                        // Does widget with identical settings already exist in same sidebar?
    … …  
    167182
    168183                                                // Assign widget instance to sidebar.
    169                                                 $sidebars_widgets                      = get_option( 'sidebars_widgets' ); // Which sidebars have which widgets, get fresh every time.
     184                                                $sidebars_widgets                      = (array) get_option( 'sidebars_widgets', array() ); // Which sidebars have which widgets, get fresh every time.
    170185                                                $new_instance_id                       = $id_base . '-' . $new_instance_id_number; // Use ID number from new widget instance.
    171186                                                $sidebars_widgets[ $use_sidebar_id ][] = $new_instance_id; // Add new instance to sidebar.
    … …  
    233248                        return apply_filters( 'demo_awesome_widget_importer_available_widgets', $available_widgets );
    234249                }
     250
     251                /**
     252                 * Validate import file path and permissions
     253                 * @since 1.0.3
     254                 */
     255                private static function validate_import_file($file_path) {
     256                        // Check if file exists
     257                        if (!file_exists($file_path)) {
     258                                return false;
     259                        }
     260
     261                        // Check if file is readable
     262                        if (!is_readable($file_path)) {
     263                                return false;
     264                        }
     265
     266                        // Check file extension
     267                        $allowed_extensions = array('wie', 'json');
     268                        $file_extension = strtolower(pathinfo($file_path, PATHINFO_EXTENSION));
     269                        if (!in_array($file_extension, $allowed_extensions)) {
     270                                return false;
     271                        }
     272
     273                        // Check file size (prevent DoS)
     274                        if (filesize($file_path) > 5 * 1024 * 1024) { // 5MB limit
     275                                return false;
     276                        }
     277
     278                        return true;
     279                }
     280
     281                /**
     282                 * Validate file content for security
     283                 * @since 1.0.3
     284                 */
     285                private static function validate_file_content($content) {
     286                        // Check for empty content
     287                        if (empty($content)) {
     288                                return false;
     289                        }
     290
     291                        // Check content length
     292                        if (strlen($content) > 5 * 1024 * 1024) { // 5MB limit
     293                                return false;
     294                        }
     295
     296                        // Check for malicious content
     297                        if (preg_match('/<\?php|<\?=|<script[^>]*>|javascript:|data:/i', $content)) {
     298                                return false;
     299                        }
     300
     301                        // Validate JSON structure
     302                        $decoded = json_decode($content, true);
     303                        if (json_last_error() !== JSON_ERROR_NONE) {
     304                                return false;
     305                        }
     306
     307                        return true;
     308                }
    235309        }
    236310}
  • demo-awesome/trunk/inc/admin/importer/class-extends-customize-demo-importer-setting.php

    r2158733 r3813524  
    1010 * @author     Theme4Press
    1111 */
     12
     13// Exit if accessed directly.
     14if ( ! defined( 'ABSPATH' ) ) {
     15        exit;
     16}
    1217
    1318/**
  • demo-awesome/trunk/inc/admin/js/admin.js

    r3081092 r3813524  
    15831583        var data = {
    15841584            'action': 'call_import_function_from_ajax',
    1585             'data_demo': data_demo,
    1586             'nonce': demo_awesome_js_local_vars.nonce
     1585            'demo_index': data_demo.index,
     1586            '_nonce': demo_awesome_js_local_vars._nonce
     1587        };
     1588        var $alert = $('#finish-import-modal .alert-message-from-importer');
     1589        var showError = function (message) {
     1590            $(".hide-content").fadeOut(1500);
     1591            $alert.removeClass('alert-success').addClass('alert-danger').text(message);
     1592            $(".show-content").fadeIn(1500).css("display", "flex");
    15871593        };
    15881594        jQuery.post(ajaxurl, data, function (response) {
    1589             $(".hide-content").fadeOut(1500);
    15901595            if (response && response.success) {
    1591                 $('#finish-import-modal .alert-message-from-importer').removeClass('alert-danger').addClass('alert-success').text('').wrapInner(response.data.message);
     1596                $(".hide-content").fadeOut(1500);
     1597                $alert.removeClass('alert-danger').addClass('alert-success').text('').wrapInner(response.data.message);
     1598                $(".show-content").fadeIn(1500).css("display", "flex");
    15921599            }
    15931600            else {
    1594                 $('#finish-import-modal .alert-message-from-importer').removeClass('alert-success').addClass('alert-danger').text('').wrapInner(response);
     1601                var d = (response && response.data) || {};
     1602                showError(d.message || d.errorMessage || 'The import failed. Please check the PHP error log for details.');
    15951603            }
    1596             $(".show-content").fadeIn(1500).css("display", "flex");
    1597 
     1604        }).fail(function (xhr) {
     1605            showError('The import request failed (HTTP ' + xhr.status + '). The server may have run out of time or memory; please check the PHP error log.');
    15981606        });
    15991607    });
    … …  
    16741682            data: {
    16751683                action: 'required_plugins',
    1676                 data_demo: data_demo
     1684                demo_index: data_demo.index,
     1685                 '_nonce': demo_awesome_js_local_vars._nonce
    16771686            },
    16781687            success: function (data) {
    … …  
    16971706                plugin: plugin,
    16981707                html: html,
     1708                '_nonce': demo_awesome_js_local_vars._nonce
    16991709            },
    17001710            success: function (data) {
    … …  
    17071717                        plugin: plugin,
    17081718                        html: html,
     1719                        '_nonce': demo_awesome_js_local_vars._nonce
    17091720                    },
    17101721                    success: function (data) {
  • demo-awesome/trunk/inc/admin/required-plugins.php

    r3081092 r3813524  
    88 * @author     Theme4Press
    99 */
     10
     11// Exit if accessed directly.
     12if (!defined('ABSPATH')) {
     13    exit;
     14}
    1015
    1116if (!function_exists('demo_awesome_required_plugins')) {
    … …  
    2429        <div class="refresh-container-box">
    2530            <?php
    26             if (isset($_POST['action']) && $_POST['action'] == 'required_plugins') {
     31            // phpcs:ignore WordPress.Security.NonceVerification.Missing -- The calling AJAX handler (required_plugins()) verifies the nonce before this template is included.
     32            if (isset($_POST['action']) && 'required_plugins' === sanitize_text_field(wp_unslash($_POST['action']))) {
    2733                $requred_message = [];
    2834                if ($data_demo) {
    … …  
    4551
    4652
    47                         <span class="mr-1"><?php echo Demo_Awesome_Admin::get_svg('warning'); ?></span><?php esc_html_e(
     53                        <span class="mr-1"><?php echo wp_kses( Demo_Awesome_Admin::get_svg('warning'), Demo_Awesome_Admin::allowed_svg_tags() ); ?></span><?php esc_html_e(
    4854                            'This demo import requires additional plugins',
    4955                            'demo-awesome'
    … …  
    5258                        <button class="button button-primary refresh-required"><span
    5359                                    class="mr-1"
    54                                     name="refresh-required"><?php echo Demo_Awesome_Admin::get_svg('refresh'); ?></span>
     60                                    name="refresh-required"><?php echo wp_kses( Demo_Awesome_Admin::get_svg('refresh'), Demo_Awesome_Admin::allowed_svg_tags() ); ?></span>
    5561                            <?php esc_html_e('Refresh', 'demo-awesome'); ?>
    5662                        </button>
    … …  
    6672
    6773
    68                     <span class="mr-1"><?php echo Demo_Awesome_Admin::get_svg('warning'); ?></span><?php esc_html_e(
     74                    <span class="mr-1"><?php echo wp_kses( Demo_Awesome_Admin::get_svg('warning'), Demo_Awesome_Admin::allowed_svg_tags() ); ?></span><?php esc_html_e(
    6975                        'This demo import requires additional plugins',
    7076                        'demo-awesome'
    … …  
    7379                    <button class="button button-primary refresh-required"><span
    7480                                class="mr-1"
    75                                 name="refresh-required"><?php echo wp_kses_post( Demo_Awesome_Admin::get_svg(
     81                                name="refresh-required"><?php echo wp_kses( Demo_Awesome_Admin::get_svg(
    7682                                'refresh'
    77                             )); ?></span><?php esc_html_e('Refresh', 'demo-awesome'); ?>
     83                            ), Demo_Awesome_Admin::allowed_svg_tags() ); ?></span><?php esc_html_e('Refresh', 'demo-awesome'); ?>
    7884                    </button>
    7985
    … …  
    124130                                        $premium_plugin = sprintf(
    125131                                            '<div class="badge badge-premium">%s</div>',
    126                                             $plugin['disable_description']
     132                                           esc_html($plugin['disable_description'])
    127133                                        );
    128134                                     //   var_dump($plugin);
    129                                             $plugin['slug'] =  isset( $plugin['slug']{1} ) ? $plugin['slug'] : $plugin['keyword'];
    130                                         $premium_plugin = sprintf(
    131                                             '<a class="button evole-install-plugin button-proceed" target="_blank"
    132                                  data-plugin="'.$plugin['slug'].'" href="'.self_admin_url('#%s">%s</a>'),
    133                                             $plugin['keyword'],
    134                                             esc_html__('Install', 'demo-awesome')
    135                                         );
     135                                            $plugin['slug'] =  isset( $plugin['slug'][1] ) ? $plugin['slug'] : $plugin['keyword'];
     136
     137                                //         $premium_plugin = sprintf(
     138                                //             '<a class="button evole-install-plugin button-proceed" target="_blank"
     139                                //  data-plugin="'.$plugin['slug'].'" href="'.self_admin_url('#%s">%s</a>'),
     140                                //             $plugin['keyword'],
     141                                //             esc_html__('Install', 'demo-awesome')
     142                                //         );
     143                                $install_url = self_admin_url( sprintf( '#%s', rawurlencode( $plugin['keyword'] ) ) );
     144
     145                                $premium_plugin = sprintf(
     146                                    '<a class="button evole-install-plugin button-proceed" target="_blank" data-plugin="%1$s" href="%2$s">%3$s</a>',
     147                                    esc_attr( $plugin['slug'] ),
     148                                    esc_url( $install_url ),
     149                                    esc_html__( 'Install', 'demo-awesome' )
     150                                );
     151
     152
    136153                                    } else {
    137154                                        $premium_plugin = sprintf(
    … …  
    149166                                <li>
    150167                                    <strong><?php
    151                                         echo wp_kses_post($plugin['name'].'<br />'.$required_plugin); ?></strong>
     168                                        echo wp_kses($plugin['name'].'<br />'.$required_plugin, Demo_Awesome_Admin::allowed_svg_tags()); ?></strong>
    152169                                    <?php if (current_user_can(  'install_plugins' ) || current_user_can( 'update_plugins' )) {
    153                                         echo wp_kses_post($premium_plugin);
     170                                        echo wp_kses($premium_plugin, Demo_Awesome_Admin::allowed_svg_tags());
    154171                                    } ?>
    155172                                </li>
    … …  
    160177                    <?php if ($show_required_description) { ?>
    161178                        <p class="alert alert-info required-description-text"><span
    162                                     class="mr-1"><?php echo wp_kses_post( Demo_Awesome_Admin::get_svg('info')); ?></span><?php esc_html_e(
     179                                    class="mr-1"><?php echo wp_kses( Demo_Awesome_Admin::get_svg('info'), Demo_Awesome_Admin::allowed_svg_tags() ); ?></span><?php esc_html_e(
    163180                                'You can install/activate the required plugin(s) before import or import the demo content now. Importing content without enabled required plugin(s) may result in broken page layout or not importing the data supported by the plugin(s).',
    164181                                'demo-awesome'
  • demo-awesome/trunk/inc/class-demo-awesome-i18n.php

    r2003923 r3813524  
    99 */
    1010
     11// Exit if accessed directly.
     12if ( ! defined( 'ABSPATH' ) ) {
     13        exit;
     14}
     15
    1116if ( ! class_exists( 'Demo_Awesome_i18n' ) ) {
    1217        class Demo_Awesome_i18n {
    … …  
    1722                public function load_plugin_textdomain() {
    1823
     24                        // phpcs:ignore PluginCheck.CodeAnalysis.DiscouragedFunctions.load_plugin_textdomainFound -- Retained so bundled translations also load on non-wordpress.org installs.
    1925                        load_plugin_textdomain(
    2026                                'demo-awesome',
  • demo-awesome/trunk/inc/class-demo-awesome-loader.php

    r2003923 r3813524  
    88 * @author     Theme4Press
    99 */
     10
     11// Exit if accessed directly.
     12if ( ! defined( 'ABSPATH' ) ) {
     13        exit;
     14}
    1015
    1116if ( ! class_exists( 'Demo_Awesome_Loader' ) ) {
  • demo-awesome/trunk/inc/class-demo-awesome.php

    r2158733 r3813524  
    88 * @author     Theme4Press
    99 */
     10
     11// Exit if accessed directly.
     12if ( ! defined( 'ABSPATH' ) ) {
     13        exit;
     14}
    1015
    1116if ( ! class_exists( 'Demo_Awesome' ) ) {
Note: See TracChangeset for help on using the changeset viewer.