/**
 * 
 * Function sort out paramaters
 * This function creates folders needed when duplicating a template
 * @param number $folder_name_id - the id of this template
 * @param number $tutorial_id_from_post - the parent template name for the new tutorial
 * @version 1.0
 * @author Patrick Lockley
 */
function create_new_template($folder_name_id, $parent_template_name)
{
    global $dir_path, $new_path, $temp_dir_path, $temp_new_path, $xerte_toolkits_site;
    $row_framework = db_query_one("SELECT template_framework from {$xerte_toolkits_site->database_table_prefix}originaltemplatesdetails WHERE template_name = ?", array($parent_template_name));
    // I think this is wrong, currently looking like : /home/david/src/xerteonlinetoolkits/modules//templates/0 should presumably be home/david/src/xerteonlinetoolkits/modules/xerte/templates/Nottingham
    $dir_path = $xerte_toolkits_site->basic_template_path . $row_framework['template_framework'] . "/templates/" . $parent_template_name;
    /**
     * Get the id of the folder we are looking to copy into
     */
    _debug("Creating new template : {$folder_name_id}, {$parent_template_name}");
    $new_path = $xerte_toolkits_site->users_file_area_full . $folder_name_id . "-" . $_SESSION['toolkits_logon_username'] . "-" . $parent_template_name;
    $path = $xerte_toolkits_site->users_file_area_full . $folder_name_id . "-" . $_SESSION['toolkits_logon_username'] . "-" . $parent_template_name;
    if (is_dir($path)) {
        _debug("Trying to create new template at location - {$path} - it's already in use. Aborting");
        die("Template directory already exists; will not overwrite/re-create.");
    }
    if (mkdir($path)) {
        _debug("Created {$path} ok");
        if (@chmod($path, 0777)) {
            $ok = copy_r($dir_path, $path);
            _debug("Copy_r returned " . print_r($ok, true));
            return $ok;
        } else {
            _debug("Failed to set rights ");
            receive_message($_SESSION['toolkits_logon_username'], "FILE_SYSTEM", "MAJOR", "Failed to set rights on parent folder for template", "Failed to set rights on parent folder " . $path);
            return false;
        }
    } else {
        receive_message($_SESSION['toolkits_logon_username'], "FILE_SYSTEM", "CRITICAL", "Failed to create parent folder for template", "Failed to create parent folder " . $path);
        return false;
    }
}
function copy_r($path, $dest)
{
    if (is_dir($path)) {
        @mkdir($dest);
        $objects = scandir($path);
        if (sizeof($objects) > 0) {
            foreach ($objects as $file) {
                if ($file == "." || $file == "..") {
                    continue;
                }
                // go on
                if (is_dir($path . DS . $file)) {
                    copy_r($path . DS . $file, $dest . DS . $file);
                } else {
                    copy($path . DS . $file, $dest . DS . $file);
                }
            }
        }
        return true;
    } elseif (is_file($path)) {
        return copy($path, $dest);
    } else {
        return false;
    }
}
 /**
  *
  * アップデート
  * updateはアップデート時に実行されます。
  * 引数にはdtb_pluginのプラグイン情報が渡されます。
  * @param $arrPlugin
  */
 public function update($arrPlugin)
 {
     $objQuery =& SC_Query_Ex::getSingletonInstance();
     // 初期データ追加
     $sqlval_plugin = array();
     $sqlval_plugin['plugin_version'] = "0.4";
     $sqlval_plugin['update_date'] = 'CURRENT_TIMESTAMP';
     $where = "plugin_code = ?";
     // UPDATEの実行
     $objQuery->update('dtb_plugin', $sqlval_plugin, $where, array('BreadcrumbList'));
     // ファイルのコピー
     if (copy_r(DOWNLOADS_TEMP_PLUGIN_UPDATE_DIR, PLUGIN_UPLOAD_REALDIR . "BreadcrumbList/") === false) {
         die("失敗");
     }
 }
 /**
  * Initialize the phpfreechat configuration
  * this initialisation is done once at startup then it is stored into a session cache
  */
 function init()
 {
     $ok = true;
     // check the parameters types
     $array_params = $this->_params_type["array"];
     foreach ($array_params as $ap) {
         if (!is_array($this->{$ap})) {
             $this->errors[] = _pfc("'%s' parameter must be an array", $ap);
         }
     }
     $numerical_positive_params = $this->_params_type["positivenumeric"];
     foreach ($numerical_positive_params as $npp) {
         if (!is_int($this->{$npp}) || $this->{$npp} < 0) {
             $this->errors[] = _pfc("'%s' parameter must be a positive number", $npp);
         }
     }
     $boolean_params = $this->_params_type["bool"];
     foreach ($boolean_params as $bp) {
         if (!is_bool($this->{$bp})) {
             $this->errors[] = _pfc("'%s' parameter must be a boolean", $bp);
         }
     }
     $string_params = $this->_params_type["string"];
     foreach ($string_params as $sp) {
         if (!is_string($this->{$sp})) {
             $this->errors[] = _pfc("'%s' parameter must be a charatere string", $sp);
         }
     }
     if ($this->title == "") {
         $this->title = _pfc("My Chat");
     }
     // first of all, check the used functions
     $f_list["file_get_contents"] = _pfc("You need %s", "PHP 4 >= 4.3.0 or PHP 5");
     $err_session_x = "You need PHP 4 or PHP 5";
     $f_list["session_start"] = $err_session_x;
     $f_list["session_destroy"] = $err_session_x;
     $f_list["session_id"] = $err_session_x;
     $f_list["session_name"] = $err_session_x;
     $err_preg_x = _pfc("You need %s", "PHP 3 >= 3.0.9 or PHP 4 or PHP 5");
     $f_list["preg_match"] = $err_preg_x;
     $f_list["preg_replace"] = $err_preg_x;
     $f_list["preg_split"] = $err_preg_x;
     $err_ob_x = _pfc("You need %s", "PHP 4 or PHP 5");
     $f_list["ob_start"] = $err_ob_x;
     $f_list["ob_get_contents"] = $err_ob_x;
     $f_list["ob_end_clean"] = $err_ob_x;
     $f_list["get_object_vars"] = _pfc("You need %s", "PHP 4 or PHP 5");
     $this->errors = array_merge($this->errors, check_functions_exist($f_list));
     //    $this->errors = array_merge($this->errors, @test_writable_dir($this->data_public_path, "data_public_path"));
     $this->errors = array_merge($this->errors, @test_writable_dir($this->data_private_path, "data_private_path"));
     $this->errors = array_merge($this->errors, @test_writable_dir($this->data_private_path . "/cache", "data_private_path/cache"));
     // install the public directory content
     $dir = dirname(__FILE__) . "/../data/public/js";
     $dh = opendir($dir);
     while (false !== ($file = readdir($dh))) {
         $f_src = $dir . '/' . $file;
         $f_dst = $this->data_public_path . '/js/' . $file;
         if ($file == "." || $file == ".." || !is_file($f_src)) {
             continue;
         }
         // skip . and .. generic files
         // install js files only if the destination doesn't exists or if the destination timestamp is older than the source timestamp
         if (!file_exists($f_dst) || filemtime($f_dst) < filemtime($f_src)) {
             mkdir_r($this->data_public_path . '/js/');
             copy($f_src, $f_dst);
         }
         if (!file_exists($f_dst)) {
             $this->errors[] = _pfc("%s doesn't exist, data_public_path cannot be installed", $f_dst);
         }
     }
     closedir($dh);
     // ---
     // test client script
     // try to find the path into server configuration
     if ($this->client_script_path == '') {
         $this->client_script_path = pfc_GetScriptFilename();
     }
     if ($this->server_script_url == '' && $this->server_script_path == '') {
         $filetotest = $this->client_script_path;
         // do not take into account the url parameters
         if (preg_match("/(.*)\\?(.*)/", $filetotest, $res)) {
             $filetotest = $res[1];
         }
         if (!file_exists($filetotest)) {
             $this->errors[] = _pfc("%s doesn't exist", $filetotest);
         }
         $this->server_script_url = './' . basename($filetotest) . $this->_query_string;
     }
     // calculate datapublic url
     if ($this->data_public_url == "") {
         $this->data_public_url = pfc_RelativePath($this->client_script_path, $this->data_public_path);
     }
     if ($this->server_script_path == '') {
         $this->server_script_path = $this->client_script_path;
     }
     // ---
     // test server script
     if ($this->server_script_url == '') {
         $filetotest = $this->server_script_path;
         // do not take into account the url parameters
         if (preg_match("/(.*)\\?(.*)/", $this->server_script_path, $res)) {
             $filetotest = $res[1];
         }
         if (!file_exists($filetotest)) {
             $this->errors[] = _pfc("%s doesn't exist", $filetotest);
         }
         $this->server_script_url = pfc_RelativePath($this->client_script_path, $this->server_script_path) . '/' . basename($filetotest) . $this->_query_string;
     }
     // check if the theme_path parameter are correctly setup
     if ($this->theme_default_path == '' || !is_dir($this->theme_default_path)) {
         $this->theme_default_path = dirname(__FILE__) . '/../themes';
     }
     if ($this->theme_path == '' || !is_dir($this->theme_path)) {
         $this->theme_path = $this->theme_default_path;
     }
     // If the user didn't give any theme_default_url value,
     // copy the default theme resources in a public directory
     if ($this->theme_default_url == '') {
         mkdir_r($this->data_public_path . '/themes/default');
         if (!is_dir($this->data_public_path . '/themes/default')) {
             $this->errors[] = _pfc("cannot create %s", $this->data_public_path . '/themes/default');
         } else {
             $ret = copy_r(dirname(__FILE__) . '/../themes/default', $this->data_public_path . '/themes/default');
             if (!$ret) {
                 $this->errors[] = _pfc("cannot copy %s in %s", dirname(__FILE__) . '/../themes/default', $this->data_public_path . '/themes/default');
             }
         }
         $this->theme_default_url = $this->data_public_url . '/themes';
     }
     if ($this->theme_url == '') {
         mkdir_r($this->data_public_path . '/themes/' . $this->theme);
         if (!is_dir($this->data_public_path . '/themes/' . $this->theme)) {
             $this->errors[] = _pfc("cannot create %s", $this->data_public_path . '/themes/' . $this->theme);
         } else {
             $ret = copy_r($this->theme_path . '/' . $this->theme, $this->data_public_path . '/themes/' . $this->theme);
             if (!$ret) {
                 $this->errors[] = _pfc("cannot copy %s in %s", $this->theme_path . '/' . $this->theme, $this->data_public_path . '/themes/' . $this->theme);
             }
         }
         $this->theme_url = $this->theme_default_url;
     }
     // if the user do not have an existing prototype.js library, we use the embeded one
     if ($this->prototypejs_url == '') {
         $this->prototypejs_url = $this->data_public_url . '/js/prototype.js';
     }
     // ---
     // run specific container initialisation
     $ct =& pfcContainer::Instance();
     $ct_errors = $ct->init($this);
     $this->errors = array_merge($this->errors, $ct_errors);
     // check the language is known
     $lg_list = pfcI18N::GetAcceptedLanguage();
     if ($this->language != "" && !in_array($this->language, $lg_list)) {
         $this->errors[] = _pfc("'%s' parameter is not valid. Available values are : '%s'", "language", implode(", ", $lg_list));
     }
     // calculate the proxies chaine
     $this->proxies = array();
     foreach ($this->pre_proxies as $px) {
         if (!in_array($px, $this->skip_proxies) && !in_array($px, $this->proxies)) {
             $this->proxies[] = $px;
         }
     }
     foreach ($this->_sys_proxies as $px) {
         if (!in_array($px, $this->skip_proxies) && !in_array($px, $this->proxies)) {
             $this->proxies[] = $px;
         }
     }
     foreach ($this->post_proxies as $px) {
         if (!in_array($px, $this->skip_proxies) && !in_array($px, $this->proxies)) {
             $this->proxies[] = $px;
         }
     }
     // save the proxies path
     $this->proxies_path_default = dirname(__FILE__) . '/proxies';
     // check the customized proxies path
     if ($this->proxies_path != '' && !is_dir($this->proxies_path)) {
         $this->errors[] = _pfc("'%s' directory doesn't exist", $this->proxies_path);
     }
     if ($this->proxies_path == '') {
         $this->proxies_path = $this->proxies_path_default;
     }
     // save the commands path
     $this->cmd_path_default = dirname(__FILE__) . '/commands';
     if ($this->cmd_path == '') {
         $this->cmd_path = $this->cmd_path_default;
     }
     // load smileys from file
     $this->loadSmileyTheme();
     // load version number from file
     $this->version = trim(file_get_contents(dirname(__FILE__) . "/../version.txt"));
     $this->is_init = count($this->errors) == 0;
 }
示例#5
0
/**
 * My own 'cp -R' written in PHP.
 * Hopefully it will work for your situation. I'm using it in a web based file manager for my CMS.
 *
 * @param string $src
 * @param string $dest
 * @return boolean
 */
function copy_r($src, $dest)
{
    if (is_dir($src)) {
        if (!file_exists($dest)) {
            mkdir($dest, 0777, true);
        }
        $objects = scandir($src);
        if (sizeof($objects) > 0) {
            foreach ($objects as $file) {
                if ($file == "." || $file == "..") {
                    continue;
                }
                // go on
                if (is_dir($src . DS . $file)) {
                    copy_r($src . DS . $file, $dest);
                } else {
                    $dest = $dest . DS . $file;
                    //如果文件存在,重命名保存
                    if (file_exists($dest)) {
                        $dest = pathinfo($dest, PATHINFO_DIRNAME) . DS . pathinfo($dest, PATHINFO_FILENAME) . "-" . getUniqidName(4) . "." . pathinfo($dest, PATHINFO_EXTENSION);
                    }
                    copy($src . DS . $file, $dest);
                }
            }
        }
        return true;
    } elseif (is_file($src)) {
        $dest = $dest . DS . basename($src);
        //如果文件存在,重命名保存
        if (file_exists($dest)) {
            $dest = pathinfo($dest, PATHINFO_DIRNAME) . DS . pathinfo($dest, PATHINFO_FILENAME) . "-" . getUniqidName(4) . "." . pathinfo($dest, PATHINFO_EXTENSION);
        }
        return copy($src, $dest);
    } else {
        return false;
    }
}
示例#6
0
/**
 * Copy directory recursively or one file
 *
 * @param string Source path
 * @param string Destination path
 * @param string Name of folder name for the copied folder, Use NULL to get a folder name from source
 * @param array What directories should be excluded
 * @return boolean TRUE on success, FALSE when no permission
 */
function copy_r($source, $dest, $new_folder_name = NULL, $exclude_dirs = array())
{
    $result = true;
    if (is_dir($source)) {
        // Copy directory recusively
        if (in_array(basename($source), $exclude_dirs)) {
            // Don't copy this folder
            return true;
        }
        if (!($dir_handle = @opendir($source))) {
            // Unable to open dir
            return false;
        }
        $source_folder = is_null($new_folder_name) ? basename($source) : $new_folder_name;
        if (!mkdir_r($dest . '/' . $source_folder)) {
            // No rights to create a dir
            return false;
        }
        while ($file = readdir($dir_handle)) {
            if ($file != '.' && $file != '..') {
                if (is_dir($source . '/' . $file)) {
                    // Copy the files of subdirectory
                    $result = copy_r($source . '/' . $file, $dest . '/' . $source_folder, NULL, $exclude_dirs) && $result;
                } else {
                    // Copy one file of the directory
                    $result = @copy($source . '/' . $file, $dest . '/' . $source_folder . '/' . $file) && $result;
                }
            }
        }
        closedir($dir_handle);
    } else {
        // Copy a file and check destination folder for existing
        $dest_folder = preg_replace('#(.+)/[^/]+$#', '$1', $dest);
        if (!file_exists($dest_folder)) {
            // Create destination folder recursively if it doesn't exist
            if (!mkdir_r($dest_folder)) {
                // Unable to create a destination folder
                return false;
            }
        }
        // Copy a file
        $result = @copy($source, $dest);
    }
    return $result;
}
示例#7
0
function install_dir($src_dir, $dst_dir)
{
    $errors = array();
    if (!is_dir($src_dir)) {
        $errors[] = _pfc("%s is not a directory", $src_dir);
    }
    if (!is_readable($src_dir)) {
        $errors[] = _pfc("%s is not readable", $src_dir);
    }
    copy_r($src_dir, $dst_dir);
    return $errors;
}
 function update_cms()
 {
     $ok = true;
     $name = 'cms' . date('Y-m-d-') . time();
     $url = 'http://github.com/ramainen/doit-cms/zipball/master';
     $result = $_SERVER['DOCUMENT_ROOT'] . '/' . $this->tmp_folder . '/' . $name . '.zip';
     file_put_contents($result, file_get_contents($url));
     chmod($result, 0777);
     $zip = new ZipArchive();
     if ($zip->open($result) === TRUE) {
         $zip->extractTo($_SERVER['DOCUMENT_ROOT'] . '/' . $this->tmp_folder . '/' . $name);
         chmod($_SERVER['DOCUMENT_ROOT'] . '/' . $this->tmp_folder . '/' . $name, 0777);
         $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($_SERVER['DOCUMENT_ROOT'] . '/' . $this->tmp_folder . '/' . $name), RecursiveIteratorIterator::CHILD_FIRST);
         foreach ($iterator as $path) {
             chmod($path->__toString(), 0777);
         }
         $zip->close();
         $container = '';
         $dir_reader = opendir($_SERVER['DOCUMENT_ROOT'] . '/' . $this->tmp_folder . '/' . $name);
         while ($file = readdir($dir_reader)) {
             if ($file != '.' && $file != '..') {
                 $container = $file;
             }
         }
         if ($container == '') {
             print 'Обновление завершилось неудачей  - в архиве не найдена система';
             exit;
         }
         if ($ok == false) {
             return false;
         }
         $new_name = $_SERVER['DOCUMENT_ROOT'] . '/cms' . date('Y-m-d') . '-' . time();
         if (!rename($_SERVER['DOCUMENT_ROOT'] . '/cms', $new_name)) {
             print 'Обновление завершилось неудачей на этапе переименования папки cms в резервную копию';
             return false;
         }
         if ($ok == false) {
             return false;
         }
         //Эту папку можно сохранить при желании
         d()->renamed_cms = $new_name;
         $_SESSION['renamed_cms'] = $new_name;
         if (!copy_r($_SERVER['DOCUMENT_ROOT'] . '/' . $this->tmp_folder . '/' . $name . '/' . $container . '/cms', $_SERVER['DOCUMENT_ROOT'] . '/cms')) {
             $ok = false;
             print 'Обновление завершилось неудачей на этапе копирования папки cms в корень сайта';
             exit;
         }
         if ($ok == false) {
             return false;
         }
         $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($_SERVER['DOCUMENT_ROOT'] . '/' . $this->tmp_folder . '/' . $name), RecursiveIteratorIterator::CHILD_FIRST);
         foreach ($iterator as $path) {
             if ($path->isDir()) {
                 rmdir($path->__toString());
             } else {
                 unlink($path->__toString());
             }
         }
         rmdir($_SERVER['DOCUMENT_ROOT'] . '/' . $this->tmp_folder . '/' . $name);
         unlink($_SERVER['DOCUMENT_ROOT'] . '/' . $this->tmp_folder . '/' . $name . '.zip');
     } else {
         print 'Обновление завершилось неудачей на этапе распаковки архива';
         return false;
     }
     return $ok;
 }
示例#9
0
/**
 * recursively copy the contents of a directory to a new location akin to copy -r
 *
 * @param array $pSource source directory
 * @param array $pTarget target directory
 * @access public
 * @return void
 */
function copy_r($pSource, $pTarget)
{
    if (is_dir($pSource)) {
        @mkdir_p($pTarget);
        $d = dir($pSource);
        while (FALSE !== ($entry = $d->read())) {
            if ($entry == '.' || $entry == '..') {
                continue;
            }
            $source = $pSource . '/' . $entry;
            if (is_dir($source)) {
                copy_r($source, $pTarget . '/' . $entry);
                continue;
            }
            copy($source, $pTarget . '/' . $entry);
        }
        $d->close();
    } else {
        copy($pSource, $pTarget);
    }
}
示例#10
0
 /**
  * Check if the media directory or it's location was changed and perform the required data migration
  *
  * @param string the media directory path before update
  * @param string the media directory location before update
  * @return boolean true if the media directory was not changed or the change was successful, false otherwise
  */
 function check_media_dir_change($old_media_dir, $old_media_location = NULL)
 {
     global $Messages;
     $new_media_dir = $this->get_media_dir(false);
     if ($new_media_dir == $old_media_dir) {
         // The media dir was not changed, no need fo further updates
         return true;
     }
     $new_media_location = $this->get('media_location');
     if ($old_media_location == NULL) {
         // Media location was not changed
         $old_media_location = $new_media_location;
     }
     switch ($new_media_location) {
         case 'none':
             if (is_empty_directory($old_media_dir)) {
                 // Delete old media dir if it is empty
                 if (file_exists($old_media_dir) && !rmdir_r($old_media_dir)) {
                     $Messages->add(T_('The old media dir could not be removed, please remove it manually!'), 'warning');
                 }
             } else {
                 // The old media dir is not empty, but it must be cleared before it can be changed to none
                 $Messages->add(T_('Blog media folder is not empty, you cannot change it to "None".'), 'error');
                 return false;
             }
             break;
         case 'default':
         case 'subdir':
         case 'custom':
             global $media_path;
             if (file_exists($new_media_dir)) {
                 // Don't use the existing folder twice
                 $Messages->add(sprintf(T_('Folder %s already exists, it cannot be used for several media locations.'), '<b>' . $new_media_dir . '</b>'), 'error');
                 return false;
             }
             if (in_array(trim($new_media_dir, '/\\'), array($media_path . 'blogs', $media_path . 'import', $media_path . 'shared', $media_path . 'users'))) {
                 // Don't use the reserved paths
                 $Messages->add(sprintf(T_('Please use another folder name, because %s is reserved.'), '<b>' . $new_media_dir . '</b>'), 'error');
                 return false;
             }
             if ($new_media_location == 'custom') {
                 // Check for folder is not used by other blog, and it is not a sub-folder of other blog folder
                 $BlogCache =& get_BlogCache();
                 $BlogCache->clear(true);
                 $BlogCache->load_where('blog_ID != ' . $this->ID);
                 $other_blog_IDs = $BlogCache->get_ID_array();
                 foreach ($other_blog_IDs as $other_blog_ID) {
                     $other_Blog =& $BlogCache->get_by_ID($other_blog_ID, false, false);
                     $other_media_dir = $other_Blog->get_media_dir(false);
                     if (!empty($other_media_dir) && strpos($new_media_dir, $other_media_dir) === 0) {
                         $Messages->add(sprintf(T_('Please use another folder name, because %s is already used for another media location.'), '<b>' . $new_media_dir . '</b>'), 'error');
                         return false;
                     }
                 }
             }
             if ($old_media_location == 'none' || !file_exists($old_media_dir)) {
                 // The media folder was not used before, create the new media folder
                 return $this->get_media_dir(true);
             }
             if (copy_r($old_media_dir, $new_media_dir, '', array('_evocache', '.evocache'))) {
                 // The file have been copied to new folder successfully
                 if (!rmdir_r($old_media_dir)) {
                     // Display a warning if old folder could not be deleted
                     $Messages->add(sprintf(T_('Could not delete the old media folder "%s", please try to delete it manually.'), '<b>' . $old_media_dir . '</b>'), 'warning');
                 }
             } else {
                 // Display a message if some error on copying
                 $Messages->add(sprintf(T_('Could not move the media folder content from "%s" to the new "%s" location.'), '<b>' . $old_media_dir . '</b>', '<b>' . $new_media_dir . '</b>'), 'error');
                 return false;
             }
             break;
         default:
             debug_die('Invalid media location setting received!');
     }
     $Messages->add(T_('The media directory and all of its content were successfully moved to the new location.'), 'note');
     return true;
 }
示例#11
0
/**
 * Import WordPress data from XML file into b2evolution database
 */
function wpxml_import()
{
    global $DB, $tableprefix;
    // Load classes:
    load_class('regional/model/_country.class.php', 'Country');
    load_class('regional/model/_region.class.php', 'Region');
    load_class('regional/model/_subregion.class.php', 'Subregion');
    load_class('regional/model/_city.class.php', 'City');
    // Set Blog from request blog ID
    $wp_blog_ID = param('wp_blog_ID', 'integer', 0);
    $BlogCache =& get_BlogCache();
    $wp_Blog =& $BlogCache->get_by_ID($wp_blog_ID);
    // The import type ( replace | append )
    $import_type = param('import_type', 'string', 'replace');
    // Should we delete files on 'replace' mode?
    $delete_files = param('delete_files', 'integer', 0);
    $XML_file_path = get_param('wp_file');
    $XML_file_name = basename($XML_file_path);
    if (preg_match('/\\.(xml|txt)$/i', $XML_file_name)) {
        // XML format
        // Check WordPress XML file
        if (!wpxml_check_xml_file($XML_file_path)) {
            // Errors are in XML file
            return;
        }
        // Use this folder to upload files if they exist in subfolder "/b2evolution_export_files"
        $attached_files_path = dirname($XML_file_path);
    } else {
        if (preg_match('/\\.zip$/i', $XML_file_name)) {
            // ZIP format
            // Extract ZIP and check WordPress XML file
            global $media_path;
            $ZIP_folder_path = $media_path . 'import/temp-' . md5(rand());
            if (!unpack_archive($XML_file_path, $ZIP_folder_path, true, $XML_file_name)) {
                // Errors on unpack ZIP file
                return;
            }
            // Find valid XML file in ZIP package
            $ZIP_files_list = scandir($ZIP_folder_path);
            $xml_exists_in_zip = false;
            foreach ($ZIP_files_list as $ZIP_file) {
                if (preg_match('/\\.(xml|txt)$/i', $ZIP_file)) {
                    // XML file is found in ZIP package
                    if (wpxml_check_xml_file($ZIP_folder_path . '/' . $ZIP_file)) {
                        // XML file is valid
                        $XML_file_path = $ZIP_folder_path . '/' . $ZIP_file;
                        $xml_exists_in_zip = true;
                        break;
                    }
                }
            }
            if (!$xml_exists_in_zip) {
                // No XML is detected in ZIP package
                echo '<p style="color:red">' . T_('XML file is not detected in your ZIP package.') . '</p>';
                // Delete temporary folder that contains the files from extracted ZIP package
                rmdir_r($ZIP_folder_path);
                return;
            }
            // Use this folder to upload files, $ZIP_folder_path must be deleted after import
            $attached_files_path = $ZIP_folder_path;
        } else {
            // Unrecognized extension
            echo '<p style="color:red">' . sprintf(T_('%s has an unrecognized extension.'), '<b>' . $xml_file['name'] . '</b>') . '</p>';
            return;
        }
    }
    // Parse WordPress XML file into array
    $xml_data = wpxml_parser($XML_file_path);
    $DB->begin();
    if ($import_type == 'replace') {
        // Remove data from selected blog
        // Get existing categories
        $SQL = new SQL();
        $SQL->SELECT('cat_ID');
        $SQL->FROM('T_categories');
        $SQL->WHERE('cat_blog_ID = ' . $DB->quote($wp_blog_ID));
        $old_categories = $DB->get_col($SQL->get());
        if (!empty($old_categories)) {
            // Get existing posts
            $SQL = new SQL();
            $SQL->SELECT('post_ID');
            $SQL->FROM('T_items__item');
            $SQL->WHERE('post_main_cat_ID IN ( ' . implode(', ', $old_categories) . ' )');
            $old_posts = $DB->get_col($SQL->get());
        }
        echo T_('Removing the comments... ');
        evo_flush();
        if (!empty($old_posts)) {
            $SQL = new SQL();
            $SQL->SELECT('comment_ID');
            $SQL->FROM('T_comments');
            $SQL->WHERE('comment_item_ID IN ( ' . implode(', ', $old_posts) . ' )');
            $old_comments = $DB->get_col($SQL->get());
            $DB->query('DELETE FROM T_comments WHERE comment_item_ID IN ( ' . implode(', ', $old_posts) . ' )');
            if (!empty($old_comments)) {
                $DB->query('DELETE FROM T_comments__votes WHERE cmvt_cmt_ID IN ( ' . implode(', ', $old_comments) . ' )');
                $DB->query('DELETE FROM T_links WHERE link_cmt_ID IN ( ' . implode(', ', $old_comments) . ' )');
            }
        }
        echo T_('OK') . '<br />';
        echo T_('Removing the posts... ');
        evo_flush();
        if (!empty($old_categories)) {
            $DB->query('DELETE FROM T_items__item WHERE post_main_cat_ID IN ( ' . implode(', ', $old_categories) . ' )');
            if (!empty($old_posts)) {
                // Remove the post's data from related tables
                if ($delete_files) {
                    // Get the file IDs that should be deleted from hard drive
                    $SQL = new SQL();
                    $SQL->SELECT('DISTINCT link_file_ID');
                    $SQL->FROM('T_links');
                    $SQL->WHERE('link_itm_ID IN ( ' . implode(', ', $old_posts) . ' )');
                    $deleted_file_IDs = $DB->get_col($SQL->get());
                }
                $DB->query('DELETE FROM T_items__item_settings WHERE iset_item_ID IN ( ' . implode(', ', $old_posts) . ' )');
                $DB->query('DELETE FROM T_items__prerendering WHERE itpr_itm_ID IN ( ' . implode(', ', $old_posts) . ' )');
                $DB->query('DELETE FROM T_items__subscriptions WHERE isub_item_ID IN ( ' . implode(', ', $old_posts) . ' )');
                $DB->query('DELETE FROM T_items__version WHERE iver_itm_ID IN ( ' . implode(', ', $old_posts) . ' )');
                $DB->query('DELETE FROM T_postcats WHERE postcat_post_ID IN ( ' . implode(', ', $old_posts) . ' )');
                $DB->query('DELETE FROM T_slug WHERE slug_itm_ID IN ( ' . implode(', ', $old_posts) . ' )');
                $DB->query('DELETE l, lv FROM T_links AS l
											 LEFT JOIN T_links__vote AS lv ON lv.lvot_link_ID = l.link_ID
											WHERE l.link_itm_ID IN ( ' . implode(', ', $old_posts) . ' )');
                $DB->query('DELETE FROM T_users__postreadstatus WHERE uprs_post_ID IN ( ' . implode(', ', $old_posts) . ' )');
            }
        }
        echo T_('OK') . '<br />';
        echo T_('Removing the categories... ');
        evo_flush();
        $DB->query('DELETE FROM T_categories WHERE cat_blog_ID = ' . $DB->quote($wp_blog_ID));
        echo T_('OK') . '<br />';
        echo T_('Removing the tags that are no longer used... ');
        evo_flush();
        if (!empty($old_posts)) {
            // Remove the tags
            // Get tags from selected blog
            $SQL = new SQL();
            $SQL->SELECT('itag_tag_ID');
            $SQL->FROM('T_items__itemtag');
            $SQL->WHERE('itag_itm_ID IN ( ' . implode(', ', $old_posts) . ' )');
            $old_tags_this_blog = array_unique($DB->get_col($SQL->get()));
            if (!empty($old_tags_this_blog)) {
                // Get tags from other blogs
                $SQL = new SQL();
                $SQL->SELECT('itag_tag_ID');
                $SQL->FROM('T_items__itemtag');
                $SQL->WHERE('itag_itm_ID NOT IN ( ' . implode(', ', $old_posts) . ' )');
                $old_tags_other_blogs = array_unique($DB->get_col($SQL->get()));
                $old_tags_other_blogs_sql = !empty($old_tags_other_blogs) ? ' AND tag_ID NOT IN ( ' . implode(', ', $old_tags_other_blogs) . ' )' : '';
                // Remove the tags that are no longer used
                $DB->query('DELETE FROM T_items__tag
					WHERE tag_ID IN ( ' . implode(', ', $old_tags_this_blog) . ' )' . $old_tags_other_blogs_sql);
            }
            // Remove the links of tags with posts
            $DB->query('DELETE FROM T_items__itemtag WHERE itag_itm_ID IN ( ' . implode(', ', $old_posts) . ' )');
        }
        echo T_('OK') . '<br />';
        if ($delete_files) {
            // Delete the files
            echo T_('Removing the files... ');
            if (!empty($deleted_file_IDs)) {
                // Commit the DB changes before files deleting
                $DB->commit();
                // Get the deleted file IDs that are linked to other objects
                $SQL = new SQL();
                $SQL->SELECT('DISTINCT link_file_ID');
                $SQL->FROM('T_links');
                $SQL->WHERE('link_file_ID IN ( ' . implode(', ', $deleted_file_IDs) . ' )');
                $linked_file_IDs = $DB->get_col($SQL->get());
                // We can delete only the files that are NOT linked to other objects
                $deleted_file_IDs = array_diff($deleted_file_IDs, $linked_file_IDs);
                $FileCache =& get_FileCache();
                foreach ($deleted_file_IDs as $deleted_file_ID) {
                    if (!($deleted_File =& $FileCache->get_by_ID($deleted_file_ID, false, false))) {
                        // Incorrect file ID
                        echo '<p class="red">' . sprintf(T_('No file #%s found in DB. It cannot be deleted.'), $deleted_file_ID) . '</p>';
                    }
                    if (!$deleted_File->unlink()) {
                        // No permission to delete file
                        echo '<p class="red">' . sprintf(T_('Could not delete the file &laquo;%s&raquo;.'), $deleted_File->get_full_path()) . '</p>';
                    }
                    // Clear cache to save memory
                    $FileCache->clear();
                }
                // Start new transaction for the data inserting
                $DB->begin();
            }
            echo T_('OK') . '<br />';
        }
        echo '<br />';
    }
    /* Import authors */
    $authors = array();
    $authors_IDs = array();
    if (isset($xml_data['authors']) && count($xml_data['authors']) > 0) {
        global $Settings, $UserSettings;
        echo T_('Importing the users... ');
        evo_flush();
        // Get existing users
        $SQL = new SQL();
        $SQL->SELECT('user_login, user_ID');
        $SQL->FROM('T_users');
        $existing_users = $DB->get_assoc($SQL->get());
        $authors_count = 0;
        foreach ($xml_data['authors'] as $author) {
            if (empty($existing_users[(string) $author['author_login']])) {
                // Insert new user into DB if User doesn't exist with current login name
                $GroupCache =& get_GroupCache();
                if (!empty($author['author_group'])) {
                    // Set user group from xml data
                    if (($UserGroup =& $GroupCache->get_by_name($author['author_group'], false)) === false) {
                        // If user's group doesn't exist yet, we should create new
                        $UserGroup = new Group();
                        $UserGroup->set('name', $author['author_group']);
                        $UserGroup->dbinsert();
                    }
                } else {
                    // Set default user group is it is not defined in xml
                    if (($UserGroup =& $GroupCache->get_by_name('Normal Users', false)) === false) {
                        // Exit from import of users, because we cannot set default user group
                        break;
                    }
                }
                unset($author_created_from_country);
                if (!empty($author['author_created_from_country'])) {
                    // Get country ID from DB by code
                    $CountryCache =& get_CountryCache();
                    if (($Country =& $CountryCache->get_by_name($author['author_created_from_country'], false)) !== false) {
                        $author_created_from_country = $Country->ID;
                    }
                }
                // Get regional IDs by their names
                $author_regions = wp_get_regional_data($author['author_country'], $author['author_region'], $author['author_subregion'], $author['author_city']);
                $User = new User();
                $User->set('login', $author['author_login']);
                $User->set('email', $author['author_email']);
                $User->set('firstname', $author['author_first_name']);
                $User->set('lastname', $author['author_last_name']);
                $User->set('pass', $author['author_pass']);
                $User->set_Group($UserGroup);
                $User->set('status', !empty($author['author_status']) ? $author['author_status'] : 'autoactivated');
                $User->set('nickname', $author['author_nickname']);
                $User->set('url', $author['author_url']);
                $User->set('level', $author['author_level']);
                $User->set('locale', $author['author_locale']);
                $User->set('gender', $author['author_gender'] == 'female' ? 'F' : ($author['author_gender'] == 'male' ? 'M' : ''));
                if ($author['author_age_min'] > 0) {
                    $User->set('age_min', $author['author_age_min']);
                }
                if ($author['author_age_max'] > 0) {
                    $User->set('age_max', $author['author_age_max']);
                }
                if (isset($author_created_from_country)) {
                    // User was created from this country
                    $User->set('reg_ctry_ID', $author_created_from_country);
                }
                if (!empty($author_regions['country'])) {
                    // Country
                    $User->set('ctry_ID', $author_regions['country']);
                    if (!empty($author_regions['region'])) {
                        // Region
                        $User->set('rgn_ID', $author_regions['region']);
                        if (!empty($author_regions['subregion'])) {
                            // Subregion
                            $User->set('subrg_ID', $author_regions['subregion']);
                        }
                        if (!empty($author_regions['city'])) {
                            // City
                            $User->set('city_ID', $author_regions['city']);
                        }
                    }
                }
                $User->set('source', $author['author_source']);
                $User->set_datecreated(empty($author['author_created_ts']) ? mktime() : intval($author['author_created_ts']));
                $User->set('lastseen_ts', empty($author['author_lastseen_ts']) ? NULL : $author['author_lastseen_ts'], true);
                $User->set('profileupdate_date', empty($author['author_profileupdate_date']) ? date('Y-m-d', mktime()) : $author['author_profileupdate_date']);
                $User->dbinsert();
                $user_ID = $User->ID;
                if (!empty($user_ID) && !empty($author['author_created_fromIPv4'])) {
                    $UserSettings->set('created_fromIPv4', ip2int($author['author_created_fromIPv4']), $user_ID);
                }
                $authors_count++;
            } else {
                // Get ID of existing user
                $user_ID = $existing_users[(string) $author['author_login']];
            }
            // Save user ID of current author
            $authors[$author['author_login']] = (string) $user_ID;
            $authors_IDs[$author['author_id']] = (string) $user_ID;
        }
        $UserSettings->dbupdate();
        echo sprintf(T_('%d records'), $authors_count) . '<br />';
    }
    /* Import files, Copy them all to media folder */
    if (isset($xml_data['files']) && count($xml_data['files']) > 0) {
        echo T_('Importing the files... ');
        evo_flush();
        if (!file_exists($attached_files_path . '/b2evolution_export_files')) {
            // Display an error if files are attached but folder doesn't exist
            echo '<p class="red">' . sprintf(T_('No folder %s found. It must exists to import the attached files properly.'), '<b>' . $attached_files_path . '/b2evolution_export_files' . '</b>') . '</p>';
        } else {
            // The attached files are located in this subfolder
            $subfolder_path = '/b2evolution_export_files';
            $files_count = 0;
            $files = array();
            foreach ($xml_data['files'] as $file) {
                switch ($file['file_root_type']) {
                    case 'shared':
                        // Shared files
                        $file_root_ID = 0;
                        break;
                    case 'user':
                        // User's files
                        if (isset($authors_IDs[$file['file_root_ID']])) {
                            // If owner of this file exists in our DB
                            $file_root_ID = $authors_IDs[$file['file_root_ID']];
                            break;
                        }
                        // Otherwise we should upload this file into blog's folder:
                    // Otherwise we should upload this file into blog's folder:
                    default:
                        // 'collection', 'absolute', 'skins'
                        // The files from other blogs and from other places must be moved in the folder of the current blog
                        $file['file_root_type'] = 'collection';
                        $file_root_ID = $wp_blog_ID;
                        break;
                }
                // Get FileRoot by type and ID
                $FileRootCache =& get_FileRootCache();
                $FileRoot =& $FileRootCache->get_by_type_and_ID($file['file_root_type'], $file_root_ID);
                if (is_dir($attached_files_path . $subfolder_path . '/' . $file['zip_path'] . $file['file_path'])) {
                    // Folder
                    $file_destination_path = $FileRoot->ads_path;
                } else {
                    // File
                    $file_destination_path = $FileRoot->ads_path . $file['file_path'];
                }
                if (!file_exists($attached_files_path . $subfolder_path . '/' . $file['zip_path'] . $file['file_path'])) {
                    // File doesn't exist
                    echo '<p class="orange">' . sprintf(T_('Unable to copy file %s, because it does not exist.'), '<b>' . $file['zip_path'] . $file['file_path'] . '</b>') . '</p>';
                    // Skip it
                    continue;
                } else {
                    if (!copy_r($attached_files_path . $subfolder_path . '/' . $file['zip_path'] . $file['file_path'], $file_destination_path)) {
                        // No permission to copy to this folder
                        if (is_dir($attached_files_path . $subfolder_path . '/' . $file['zip_path'] . $file['file_path'])) {
                            // Folder
                            echo '<p class="orange">' . sprintf(T_('Unable to copy folder %s to %s. Please, check the permissions assigned to this folder.'), '<b>' . $file['zip_path'] . $file['file_path'] . '</b>', '<b>' . $file_destination_path . '</b>') . '</p>';
                        } else {
                            // File
                            echo '<p class="orange">' . sprintf(T_('Unable to copy file %s to %s. Please, check the permissions assigned to this folder.'), '<b>' . $file['zip_path'] . $file['file_path'] . '</b>', '<b>' . $file_destination_path . '</b>') . '</p>';
                        }
                        // Skip it
                        continue;
                    }
                }
                // Create new File object, It will be linked to the items below
                $File = new File($file['file_root_type'], $file_root_ID, $file['file_path']);
                $File->set('title', $file['file_title']);
                $File->set('alt', $file['file_alt']);
                $File->set('desc', $file['file_desc']);
                $files[$file['file_ID']] = $File;
                $files_count++;
            }
            echo sprintf(T_('%d records'), $files_count) . '<br />';
            if (isset($ZIP_folder_path) && file_exists($ZIP_folder_path)) {
                // This folder was created only to extract files from ZIP package, Remove it now
                rmdir_r($ZIP_folder_path);
            }
        }
    }
    /* Import categories */
    $category_default = 0;
    load_class('chapters/model/_chapter.class.php', 'Chapter');
    // Get existing categories
    $SQL = new SQL();
    $SQL->SELECT('cat_urlname, cat_ID');
    $SQL->FROM('T_categories');
    $SQL->WHERE('cat_blog_ID = ' . $DB->quote($wp_blog_ID));
    $categories = $DB->get_assoc($SQL->get());
    if (isset($xml_data['categories']) && count($xml_data['categories']) > 0) {
        echo T_('Importing the categories... ');
        evo_flush();
        load_funcs('locales/_charset.funcs.php');
        $categories_count = 0;
        foreach ($xml_data['categories'] as $cat) {
            if (empty($categories[(string) $cat['category_nicename']])) {
                $Chapter = new Chapter(NULL, $wp_blog_ID);
                $Chapter->set('name', $cat['cat_name']);
                $Chapter->set('urlname', $cat['category_nicename']);
                $Chapter->set('description', $cat['category_description']);
                if (!empty($cat['category_parent']) && isset($categories[(string) $cat['category_parent']])) {
                    // Set category parent ID
                    $Chapter->set('parent_ID', $categories[(string) $cat['category_parent']]);
                }
                $Chapter->dbinsert();
                // Save new category
                $categories[$cat['category_nicename']] = $Chapter->ID;
                if (empty($category_default)) {
                    // Set first category as default
                    $category_default = $Chapter->ID;
                }
                $categories_count++;
            }
        }
        echo sprintf(T_('%d records'), $categories_count) . '<br />';
    }
    if (empty($category_default)) {
        // No categories in XML file, Try to use first category(from DB) as default
        foreach ($categories as $category_name => $category_ID) {
            $category_default = $category_ID;
            break;
        }
    }
    if (empty($category_default)) {
        // If category is still not defined then we should create default, because blog must has at least one category
        $new_Chapter = new Chapter(NULL, $wp_blog_ID);
        $new_Chapter->set('name', T_('Uncategorized'));
        $new_Chapter->set('urlname', $wp_Blog->get('urlname') . '-main');
        $new_Chapter->dbinsert();
        $category_default = $new_Chapter->ID;
    }
    /* Import tags */
    $tags = array();
    if (isset($xml_data['tags']) && count($xml_data['tags']) > 0) {
        echo T_('Importing the tags... ');
        evo_flush();
        // Get existing tags
        $SQL = new SQL();
        $SQL->SELECT('tag_name, tag_ID');
        $SQL->FROM('T_items__tag');
        $tags = $DB->get_assoc($SQL->get());
        $tags_count = 0;
        foreach ($xml_data['tags'] as $tag) {
            if (empty($tags[(string) $tag['tag_name']])) {
                // Insert new tag into DB if tag doesn't exist with current name
                mysqli_query($DB->dbhandle, 'INSERT INTO ' . $tableprefix . 'items__tag ( tag_name )
					VALUES ( ' . $DB->quote($tag['tag_name']) . ' )');
                $tag_ID = mysqli_insert_id($DB->dbhandle);
                // Save new tag
                $tags[$tag['tag_name']] = (string) $tag_ID;
                $tags_count++;
            }
        }
        echo sprintf(T_('%d records'), $tags_count) . '<br />';
    }
    /* Import posts */
    $posts = array();
    $comments = array();
    if (isset($xml_data['posts']) && count($xml_data['posts']) > 0) {
        load_class('items/model/_item.class.php', 'Item');
        // Set status's links between WP and b2evo names
        $post_statuses = array('publish' => 'published', 'pending' => 'review', 'draft' => 'draft', 'trash' => 'deprecated', 'community' => 'community', 'deprecated' => 'deprecated', 'protected' => 'protected', 'private' => 'private', 'review' => 'review', 'redirected' => 'redirected');
        // Get post types
        $SQL = new SQL();
        $SQL->SELECT('LOWER( ityp_name ), ityp_ID');
        $SQL->FROM('T_items__type');
        $post_types = $DB->get_assoc($SQL->get());
        echo T_('Importing the posts... ');
        evo_flush();
        foreach ($xml_data['posts'] as $post) {
            $author_ID = isset($authors[(string) $post['post_author']]) ? $authors[(string) $post['post_author']] : 1;
            $last_edit_user_ID = isset($authors[(string) $post['post_lastedit_user']]) ? $authors[(string) $post['post_lastedit_user']] : $author_ID;
            $post_main_cat_ID = $category_default;
            $post_extra_cat_IDs = array();
            $post_tags = array();
            if (!empty($post['terms'])) {
                // Set categories and tags
                foreach ($post['terms'] as $term) {
                    switch ($term['domain']) {
                        case 'category':
                            if (isset($categories[(string) $term['slug']])) {
                                if ($post_main_cat_ID == $category_default) {
                                    // Set main category
                                    $post_main_cat_ID = $categories[(string) $term['slug']];
                                }
                                // Set extra categories
                                $post_extra_cat_IDs[] = $categories[(string) $term['slug']];
                            }
                            break;
                        case 'post_tag':
                            if (isset($tags[(string) $term['slug']])) {
                                // Set tag
                                $post_tags[] = $term['slug'];
                            }
                            break;
                    }
                }
            }
            // Set post type ID
            $post_type_ID = isset($post_types[strtolower($post['post_type'])]) ? $post_types[strtolower($post['post_type'])] : '1';
            // Get regional IDs by their names
            $item_regions = wp_get_regional_data($post['post_country'], $post['post_region'], $post['post_subregion'], $post['post_city']);
            $Item = new Item();
            $Item->set('main_cat_ID', $post_main_cat_ID);
            $Item->set('creator_user_ID', $author_ID);
            $Item->set('lastedit_user_ID', $last_edit_user_ID);
            $Item->set('title', $post['post_title']);
            $Item->set('content', $post['post_content']);
            $Item->set('excerpt', $post['post_excerpt']);
            $Item->set('datestart', $post['post_date']);
            $Item->set('datecreated', !empty($post['post_datecreated']) ? $post['post_datecreated'] : $post['post_date']);
            $Item->set('datemodified', !empty($post['post_datemodified']) ? $post['post_datemodified'] : $post['post_date']);
            $Item->set('urltitle', !empty($post['post_urltitle']) ? $post['post_urltitle'] : $post['post_title']);
            $Item->set('url', $post['post_url']);
            $Item->set('status', isset($post_statuses[(string) $post['status']]) ? $post_statuses[(string) $post['status']] : 'review');
            // If 'comment_status' has the unappropriate value set it to 'open'
            $Item->set('comment_status', in_array($post['comment_status'], array('open', 'closed', 'disabled')) ? $post['comment_status'] : 'open');
            $Item->set('ityp_ID', $post_type_ID);
            if (empty($post['post_excerpt']) && !empty($post['post_content'])) {
                // Generate excerpt
                $Item->set('excerpt', excerpt($post['post_content']));
                $Item->set('excerpt_autogenerated', '1');
            }
            $Item->set('extra_cat_IDs', $post_extra_cat_IDs);
            $Item->set('dateset', $post['post_date_mode'] == 'set' ? 1 : 0);
            if (isset($authors[(string) $post['post_assigned_user']])) {
                $Item->set('assigned_user', $authors[(string) $post['post_assigned_user']]);
            }
            $Item->set('datedeadline', $post['post_datedeadline']);
            $Item->set('locale', $post['post_locale']);
            $Item->set('excerpt_autogenerated', $post['post_excerpt_autogenerated']);
            $Item->set('titletag', $post['post_titletag']);
            $Item->set('notifications_status', empty($post['post_notifications_status']) ? 'noreq' : $post['post_notifications_status']);
            $Item->set('renderers', array($post['post_renderers']));
            $Item->set('priority', $post['post_priority']);
            $Item->set('featured', $post['post_featured']);
            $Item->set('order', $post['post_order']);
            if (!empty($item_regions['country'])) {
                // Country
                $Item->set('ctry_ID', $item_regions['country']);
                if (!empty($item_regions['region'])) {
                    // Region
                    $Item->set('rgn_ID', $item_regions['region']);
                    if (!empty($item_regions['subregion'])) {
                        // Subregion
                        $Item->set('subrg_ID', $item_regions['subregion']);
                    }
                    if (!empty($item_regions['city'])) {
                        // City
                        $Item->set('city_ID', $item_regions['city']);
                    }
                }
            }
            if (count($post_tags) > 0) {
                $Item->tags = $post_tags;
            }
            $Item->dbinsert();
            $posts[$post['post_id']] = $Item->ID;
            if (!empty($files) && !empty($post['links'])) {
                // Link the files to the Item if it has them
                foreach ($post['links'] as $link) {
                    if (isset($files[$link['link_file_ID']])) {
                        // Link a file to Item
                        $File = $files[$link['link_file_ID']];
                        $LinkOwner = new LinkItem($Item);
                        $File->link_to_Object($LinkOwner, $link['link_order'], $link['link_position']);
                    }
                }
            }
            if (!empty($post['comments'])) {
                // Set comments
                $comments[$Item->ID] = $post['comments'];
            }
        }
        foreach ($xml_data['posts'] as $post) {
            // Set post parents
            if (!empty($post['post_parent']) && isset($posts[(string) $post['post_parent']])) {
                mysqli_query($DB->dbhandle, 'UPDATE ' . $tableprefix . 'items__item
						  SET post_parent_ID = ' . $DB->quote($posts[(string) $post['post_parent']]) . '
						WHERE post_ID = ' . $DB->quote($posts[(string) $post['post_id']]));
            }
        }
        echo sprintf(T_('%d records'), count($xml_data['posts'])) . '<br />';
    }
    /* Import comments */
    if (!empty($comments)) {
        echo T_('Importing the comments... ');
        evo_flush();
        $comments_count = 0;
        $comments_IDs = array();
        foreach ($comments as $post_ID => $comments) {
            if (empty($comments)) {
                // Skip if no comments
                continue;
            }
            foreach ($comments as $comment) {
                $comment_author_user_ID = 0;
                if (!empty($comment['comment_user_id']) && isset($authors_IDs[(string) $comment['comment_user_id']])) {
                    // Author ID
                    $comment_author_user_ID = $authors_IDs[(string) $comment['comment_user_id']];
                }
                $comment_parent_ID = 0;
                if (!empty($comment['comment_parent']) && isset($comments_IDs[(string) $comment['comment_parent']])) {
                    // Parent comment ID
                    $comment_parent_ID = $comments_IDs[(string) $comment['comment_parent']];
                }
                unset($comment_IP_country);
                if (!empty($comment['comment_IP_country'])) {
                    // Get country ID by code
                    $CountryCache =& get_CountryCache();
                    if ($Country =& $CountryCache->get_by_name($comment['comment_IP_country'], false)) {
                        $comment_IP_country = $Country->ID;
                    }
                }
                $Comment = new Comment();
                $Comment->set('item_ID', $post_ID);
                if (!empty($comment_parent_ID)) {
                    $Comment->set('in_reply_to_cmt_ID', $comment_parent_ID);
                }
                $Comment->set('date', $comment['comment_date']);
                if (!empty($comment_author_user_ID)) {
                    $Comment->set('author_user_ID', $comment_author_user_ID);
                }
                $Comment->set('author', utf8_substr($comment['comment_author'], 0, 100));
                $Comment->set('author_IP', $comment['comment_author_IP']);
                $Comment->set('author_email', $comment['comment_author_email']);
                $Comment->set('content', $comment['comment_content']);
                if (empty($comment['comment_status'])) {
                    // If comment status is empty (the export of wordpress doesn't provide this field)
                    $Comment->set('status', $comment['comment_approved'] == '1' ? 'published' : 'draft');
                } else {
                    // Set status when we have predefined value
                    $Comment->set('status', $comment['comment_status']);
                }
                if (!empty($comment_IP_country)) {
                    // Country
                    $Comment->set('IP_ctry_ID', $comment_IP_country);
                }
                $Comment->set('rating', $comment['comment_rating']);
                $Comment->set('featured', $comment['comment_featured']);
                $Comment->set('nofollow', $comment['comment_nofollow']);
                $Comment->set('helpful_addvotes', $comment['comment_helpful_addvotes']);
                $Comment->set('helpful_countvotes', $comment['comment_helpful_countvotes']);
                $Comment->set('spam_addvotes', $comment['comment_spam_addvotes']);
                $Comment->set('spam_countvotes', $comment['comment_spam_countvotes']);
                $Comment->set('karma', $comment['comment_karma']);
                $Comment->set('spam_karma', $comment['comment_spam_karma']);
                $Comment->set('allow_msgform', $comment['comment_allow_msgform']);
                $Comment->set('notif_status', empty($comment['comment_notif_status']) ? 'noreq' : $comment['comment_notif_status']);
                $Comment->dbinsert();
                $comments_IDs[$comment['comment_id']] = $Comment->ID;
                $comments_count++;
            }
        }
        echo sprintf(T_('%d records'), $comments_count) . '<br />';
    }
    echo '<p>' . T_('Import complete.') . '</p>';
    $DB->commit();
}
示例#12
0
/**
 * Copies entire directories recursively,
 * overwriting existing files.
 *
 * Authors: SkyEye, AngelKiha, marajax, NanoTech.
 * Original from <http://php.net/copy>.
 */
function copy_r($srcdir, $dstdir, $ignore_dotfiles = true)
{
    if (!is_dir($srcdir)) {
        return copy($srcdir, $dstdir);
    }
    if (!is_dir($dstdir)) {
        mkdir($dstdir);
    }
    if ($curdir = opendir($srcdir)) {
        while ($file = readdir($curdir)) {
            if ($ignore_dotfiles && $file[0] == '.' || $file == '.' || $file == '..') {
                continue;
            }
            $srcfile = $srcdir . '/' . $file;
            $dstfile = $dstdir . '/' . $file;
            if (is_file($srcfile)) {
                if (!copy($srcfile, $dstfile)) {
                    echo "Error: File '{$srcfile}' could not be copied!\n";
                }
            } elseif (is_dir($srcfile)) {
                copy_r($srcfile, $dstfile, $ignore_dotfiles);
            }
        }
        closedir($curdir);
    }
    return true;
}