Exemplo n.º 1
0
    /**
     * Export style or style elements
     */
    function export($mode, $style_id)
    {
        global $db, $template, $user, $phpbb_root_path, $cache, $phpEx, $config;
        $update = isset($_POST['update']) ? true : false;
        $inc_template = request_var('inc_template', 0);
        $inc_theme = request_var('inc_theme', 0);
        $inc_imageset = request_var('inc_imageset', 0);
        $store = request_var('store', 0);
        $format = request_var('format', '');
        $error = array();
        $methods = array('tar');
        $available_methods = array('tar.gz' => 'zlib', 'tar.bz2' => 'bz2', 'zip' => 'zlib');
        foreach ($available_methods as $type => $module) {
            if (!@extension_loaded($module)) {
                continue;
            }
            $methods[] = $type;
        }
        if (!in_array($format, $methods)) {
            $format = 'tar';
        }
        switch ($mode) {
            case 'style':
                if ($update && $inc_template + $inc_theme + $inc_imageset < 1) {
                    $error[] = $user->lang['STYLE_ERR_MORE_ELEMENTS'];
                }
                $name = 'style_name';
                $sql_select = 's.style_id, s.style_name, s.style_copyright';
                $sql_select .= $inc_template ? ', t.*' : ', t.template_name';
                $sql_select .= $inc_theme ? ', c.*' : ', c.theme_name';
                $sql_select .= $inc_imageset ? ', i.*' : ', i.imageset_name';
                $sql_from = STYLES_TABLE . ' s, ' . STYLES_TEMPLATE_TABLE . ' t, ' . STYLES_THEME_TABLE . ' c, ' . STYLES_IMAGESET_TABLE . ' i';
                $sql_where = "s.style_id = {$style_id} AND t.template_id = s.template_id AND c.theme_id = s.theme_id AND i.imageset_id = s.imageset_id";
                $l_prefix = 'STYLE';
                break;
            case 'template':
                $name = 'template_name';
                $sql_select = '*';
                $sql_from = STYLES_TEMPLATE_TABLE;
                $sql_where = "template_id = {$style_id}";
                $l_prefix = 'TEMPLATE';
                break;
            case 'theme':
                $name = 'theme_name';
                $sql_select = '*';
                $sql_from = STYLES_THEME_TABLE;
                $sql_where = "theme_id = {$style_id}";
                $l_prefix = 'THEME';
                break;
            case 'imageset':
                $name = 'imageset_name';
                $sql_select = '*';
                $sql_from = STYLES_IMAGESET_TABLE;
                $sql_where = "imageset_id = {$style_id}";
                $l_prefix = 'IMAGESET';
                break;
        }
        if ($update && !sizeof($error)) {
            $sql = "SELECT {$sql_select}\n\t\t\t\tFROM {$sql_from}\n\t\t\t\tWHERE {$sql_where}";
            $result = $db->sql_query($sql);
            $style_row = $db->sql_fetchrow($result);
            $db->sql_freeresult($result);
            if (!$style_row) {
                trigger_error($user->lang['NO_' . $l_prefix] . adm_back_link($this->u_action), E_USER_WARNING);
            }
            $var_ary = array('style_id', 'style_name', 'style_copyright', 'template_id', 'template_name', 'template_path', 'template_copyright', 'template_storedb', 'template_inherits_id', 'bbcode_bitfield', 'theme_id', 'theme_name', 'theme_path', 'theme_copyright', 'theme_storedb', 'theme_mtime', 'theme_data', 'imageset_id', 'imageset_name', 'imageset_path', 'imageset_copyright');
            foreach ($var_ary as $var) {
                if (!isset($style_row[$var])) {
                    $style_row[$var] = '';
                }
            }
            $files = $data = array();
            if ($mode == 'style') {
                $style_cfg = str_replace(array('{MODE}', '{NAME}', '{COPYRIGHT}', '{VERSION}'), array($mode, $style_row['style_name'], $style_row['style_copyright'], $config['version']), $this->style_cfg);
                $style_cfg .= !$inc_template ? "\nrequired_template = {$style_row['template_name']}" : '';
                $style_cfg .= !$inc_theme ? "\nrequired_theme = {$style_row['theme_name']}" : '';
                $style_cfg .= !$inc_imageset ? "\nrequired_imageset = {$style_row['imageset_name']}" : '';
                $data[] = array('src' => $style_cfg, 'prefix' => 'style.cfg');
                unset($style_cfg);
            }
            // Export template core code
            if ($mode == 'template' || $inc_template) {
                $template_cfg = str_replace(array('{MODE}', '{NAME}', '{COPYRIGHT}', '{VERSION}'), array($mode, $style_row['template_name'], $style_row['template_copyright'], $config['version']), $this->template_cfg);
                $use_template_name = '';
                // Add the inherit from variable, depending on it's use...
                if ($style_row['template_inherits_id']) {
                    // Get the template name
                    $sql = 'SELECT template_name
						FROM ' . STYLES_TEMPLATE_TABLE . '
						WHERE template_id = ' . (int) $style_row['template_inherits_id'];
                    $result = $db->sql_query($sql);
                    $use_template_name = (string) $db->sql_fetchfield('template_name');
                    $db->sql_freeresult($result);
                }
                $template_cfg .= $use_template_name ? "\ninherit_from = {$use_template_name}" : "\n#inherit_from = ";
                $template_cfg .= "\n\nbbcode_bitfield = {$style_row['bbcode_bitfield']}";
                $data[] = array('src' => $template_cfg, 'prefix' => 'template/template.cfg');
                // This is potentially nasty memory-wise ...
                if (!$style_row['template_storedb']) {
                    $files[] = array('src' => "styles/{$style_row['template_path']}/template/", 'prefix-' => "styles/{$style_row['template_path']}/", 'prefix+' => false, 'exclude' => 'template.cfg');
                } else {
                    $sql = 'SELECT template_filename, template_data
						FROM ' . STYLES_TEMPLATE_DATA_TABLE . "\n\t\t\t\t\t\tWHERE template_id = {$style_row['template_id']}";
                    $result = $db->sql_query($sql);
                    while ($row = $db->sql_fetchrow($result)) {
                        $data[] = array('src' => $row['template_data'], 'prefix' => 'template/' . $row['template_filename']);
                    }
                    $db->sql_freeresult($result);
                }
                unset($template_cfg);
            }
            // Export theme core code
            if ($mode == 'theme' || $inc_theme) {
                $theme_cfg = str_replace(array('{MODE}', '{NAME}', '{COPYRIGHT}', '{VERSION}'), array($mode, $style_row['theme_name'], $style_row['theme_copyright'], $config['version']), $this->theme_cfg);
                // Read old cfg file
                $items = $cache->obtain_cfg_items($style_row);
                $items = $items['theme'];
                if (!isset($items['parse_css_file'])) {
                    $items['parse_css_file'] = 'off';
                }
                $theme_cfg = str_replace(array('{PARSE_CSS_FILE}'), array($items['parse_css_file']), $theme_cfg);
                $files[] = array('src' => "styles/{$style_row['theme_path']}/theme/", 'prefix-' => "styles/{$style_row['theme_path']}/", 'prefix+' => false, 'exclude' => $style_row['theme_storedb'] ? 'stylesheet.css,theme.cfg' : 'theme.cfg');
                $data[] = array('src' => $theme_cfg, 'prefix' => 'theme/theme.cfg');
                if ($style_row['theme_storedb']) {
                    $data[] = array('src' => $style_row['theme_data'], 'prefix' => 'theme/stylesheet.css');
                }
                unset($items, $theme_cfg);
            }
            // Export imageset core code
            if ($mode == 'imageset' || $inc_imageset) {
                $imageset_cfg = str_replace(array('{MODE}', '{NAME}', '{COPYRIGHT}', '{VERSION}'), array($mode, $style_row['imageset_name'], $style_row['imageset_copyright'], $config['version']), $this->imageset_cfg);
                $imageset_main = array();
                $sql = 'SELECT image_filename, image_name, image_height, image_width
					FROM ' . STYLES_IMAGESET_DATA_TABLE . "\n\t\t\t\t\tWHERE imageset_id = {$style_id}\n\t\t\t\t\t\tAND image_lang = ''";
                $result = $db->sql_query($sql);
                while ($row = $db->sql_fetchrow($result)) {
                    $imageset_main[$row['image_name']] = $row['image_filename'] . ($row['image_height'] ? '*' . $row['image_height'] : '') . ($row['image_width'] ? '*' . $row['image_width'] : '');
                }
                $db->sql_freeresult($result);
                foreach ($this->imageset_keys as $topic => $key_array) {
                    foreach ($key_array as $key) {
                        if (isset($imageset_main[$key])) {
                            $imageset_cfg .= "\nimg_" . $key . ' = ' . str_replace("styles/{$style_row['imageset_path']}/imageset/", '{PATH}', $imageset_main[$key]);
                        }
                    }
                }
                $files[] = array('src' => "styles/{$style_row['imageset_path']}/imageset/", 'prefix-' => "styles/{$style_row['imageset_path']}/", 'prefix+' => false, 'exclude' => 'imageset.cfg');
                $data[] = array('src' => trim($imageset_cfg), 'prefix' => 'imageset/imageset.cfg');
                end($data);
                $imageset_root = "{$phpbb_root_path}styles/{$style_row['imageset_path']}/imageset/";
                if ($dh = @opendir($imageset_root)) {
                    while (($fname = readdir($dh)) !== false) {
                        if ($fname[0] != '.' && $fname != 'CVS' && is_dir("{$imageset_root}{$fname}")) {
                            $files[key($files)]['exclude'] .= ',' . $fname . '/imageset.cfg';
                        }
                    }
                    closedir($dh);
                }
                $imageset_lang = array();
                $sql = 'SELECT image_filename, image_name, image_height, image_width, image_lang
					FROM ' . STYLES_IMAGESET_DATA_TABLE . "\n\t\t\t\t\tWHERE imageset_id = {$style_id}\n\t\t\t\t\t\tAND image_lang <> ''";
                $result = $db->sql_query($sql);
                while ($row = $db->sql_fetchrow($result)) {
                    $imageset_lang[$row['image_lang']][$row['image_name']] = $row['image_filename'] . ($row['image_height'] ? '*' . $row['image_height'] : '') . ($row['image_width'] ? '*' . $row['image_width'] : '');
                }
                $db->sql_freeresult($result);
                foreach ($imageset_lang as $lang => $imageset_localized) {
                    $imageset_cfg = str_replace(array('{MODE}', '{NAME}', '{COPYRIGHT}', '{VERSION}'), array($mode, $style_row['imageset_name'], $style_row['imageset_copyright'], $config['version']), $this->imageset_cfg);
                    foreach ($this->imageset_keys as $topic => $key_array) {
                        foreach ($key_array as $key) {
                            if (isset($imageset_localized[$key])) {
                                $imageset_cfg .= "\nimg_" . $key . ' = ' . str_replace("styles/{$style_row['imageset_path']}/imageset/", '{PATH}', $imageset_localized[$key]);
                            }
                        }
                    }
                    $data[] = array('src' => trim($imageset_cfg), 'prefix' => 'imageset/' . $lang . '/imageset.cfg');
                }
                unset($imageset_cfg);
            }
            switch ($format) {
                case 'tar':
                    $ext = '.tar';
                    $mimetype = 'x-tar';
                    $compress = 'compress_tar';
                    break;
                case 'zip':
                    $ext = '.zip';
                    $mimetype = 'zip';
                    break;
                case 'tar.gz':
                    $ext = '.tar.gz';
                    $mimetype = 'x-gzip';
                    break;
                case 'tar.bz2':
                    $ext = '.tar.bz2';
                    $mimetype = 'x-bzip2';
                    break;
                default:
                    $error[] = $user->lang[$l_prefix . '_ERR_ARCHIVE'];
            }
            if (!sizeof($error)) {
                include $phpbb_root_path . 'includes/functions_compress.' . $phpEx;
                if ($mode == 'style') {
                    $path = preg_replace('#[^\\w-]+#', '_', $style_row['style_name']);
                } else {
                    $path = $style_row[$mode . '_path'];
                }
                if ($format == 'zip') {
                    $compress = new compress_zip('w', $phpbb_root_path . "store/{$path}{$ext}");
                } else {
                    $compress = new compress_tar('w', $phpbb_root_path . "store/{$path}{$ext}", $ext);
                }
                if (sizeof($files)) {
                    foreach ($files as $file_ary) {
                        $compress->add_file($file_ary['src'], $file_ary['prefix-'], $file_ary['prefix+'], $file_ary['exclude']);
                    }
                }
                if (sizeof($data)) {
                    foreach ($data as $data_ary) {
                        $compress->add_data($data_ary['src'], $data_ary['prefix']);
                    }
                }
                $compress->close();
                add_log('admin', 'LOG_' . $l_prefix . '_EXPORT', $style_row[$mode . '_name']);
                if (!$store) {
                    $compress->download($path);
                    @unlink("{$phpbb_root_path}store/{$path}{$ext}");
                    exit;
                }
                trigger_error(sprintf($user->lang[$l_prefix . '_EXPORTED'], "store/{$path}{$ext}") . adm_back_link($this->u_action));
            }
        }
        $sql = "SELECT {$mode}_id, {$mode}_name\n\t\t\tFROM " . ($mode == 'style' ? STYLES_TABLE : $sql_from) . "\n\t\t\tWHERE {$mode}_id = {$style_id}";
        $result = $db->sql_query($sql);
        $style_row = $db->sql_fetchrow($result);
        $db->sql_freeresult($result);
        if (!$style_row) {
            trigger_error($user->lang['NO_' . $l_prefix] . adm_back_link($this->u_action), E_USER_WARNING);
        }
        $this->page_title = $l_prefix . '_EXPORT';
        $format_buttons = '';
        foreach ($methods as $method) {
            $format_buttons .= '<label><input type="radio"' . (!$format_buttons ? ' id="format"' : '') . ' class="radio" value="' . $method . '" name="format"' . ($method == $format ? ' checked="checked"' : '') . ' /> ' . $method . '</label>';
        }
        $template->assign_vars(array('S_EXPORT' => true, 'S_ERROR_MSG' => sizeof($error) ? true : false, 'S_STYLE' => $mode == 'style' ? true : false, 'L_TITLE' => $user->lang[$this->page_title], 'L_EXPLAIN' => $user->lang[$this->page_title . '_EXPLAIN'], 'L_NAME' => $user->lang[$l_prefix . '_NAME'], 'U_ACTION' => $this->u_action . '&amp;action=export&amp;id=' . $style_id, 'U_BACK' => $this->u_action, 'ERROR_MSG' => sizeof($error) ? implode('<br />', $error) : '', 'NAME' => $style_row[$mode . '_name'], 'FORMAT_BUTTONS' => $format_buttons));
    }
Exemplo n.º 2
0
    function main($mode, $sub)
    {
        global $lang, $template, $language, $phpbb_root_path, $phpEx, $config, $db, $table_prefix, $db, $auth, $cache, $user;
        $this->old_location = $phpbb_root_path . 'garage/install/install/old/';
        $this->new_location = $phpbb_root_path . 'garage/install/install/new/';
        // Special options for conflicts/modified files
        define('MERGE_NO_MERGE_NEW', 1);
        define('MERGE_NO_MERGE_MOD', 2);
        define('MERGE_NEW_FILE', 3);
        define('MERGE_MOD_FILE', 4);
        $this->install_info = $this->get_file('install_info');
        // Include renderer and engine
        $this->include_file('includes/diff/diff.' . $phpEx);
        $this->include_file('includes/diff/engine.' . $phpEx);
        $this->include_file('includes/diff/renderer.' . $phpEx);
        // Make sure we stay at the file check if checking the files again
        if (!empty($_POST['check_again'])) {
            $sub = $this->p_master->sub = 'file_check';
        }
        $this->tpl_name = 'garage_install_install';
        switch ($sub) {
            case 'intro':
                $this->page_title = $lang['SUB_INTRO'];
                $template->assign_vars(array('TITLE' => $lang['INSTALL_INTRO'], 'BODY' => $lang['INSTALL_INTRO_BODY'], 'L_SUBMIT' => $lang['NEXT_STEP'], 'U_ACTION' => $this->p_master->module_url . "?mode={$mode}&amp;sub=requirements&amp;language={$language}"));
                break;
            case 'requirements':
                $this->check_server_requirements($mode, $sub);
                break;
            case 'optional':
                $this->obtain_optional_settings($mode, $sub);
                break;
            case 'create_table':
                $this->load_schema($mode, $sub);
                break;
            case 'create_permissions':
                $this->add_permissions($mode, $sub);
                $this->update_group_permissions($mode, $sub);
                $this->update_role_permissions($mode, $sub);
                $submit = $lang['NEXT_STEP'];
                $url = $this->p_master->module_url . "?mode={$mode}&amp;sub=install_modules";
                $template->assign_vars(array('BODY' => $lang['STAGE_CREATE_PERMISSIONS_EXPLAIN'], 'L_SUBMIT' => $submit, 'U_ACTION' => $url));
                break;
            case 'install_modules':
                $this->add_modules($mode, $sub);
                $submit = $lang['NEXT_STEP'];
                $url = $this->p_master->module_url . "?mode={$mode}&amp;sub=file_check";
                $template->assign_vars(array('BODY' => $lang['STAGE_INSTALL_MODULES_EXPLAIN'], 'L_SUBMIT' => $submit, 'U_ACTION' => $url));
                break;
                // Last step is just a re-check of files...
            // Last step is just a re-check of files...
            case 'final':
            case 'file_check':
                $this->tpl_name = 'garage_install_update';
                $this->page_title = 'STAGE_FILE_CHECK';
                // Now make sure our install list is correct if the admin refreshes
                $action = request_var('action', '');
                // We are directly within an update. To make sure our install list is correct we check its status.
                $install_list = !empty($_POST['check_again']) ? false : $cache->get('_install_list');
                $modified = $install_list !== false ? @filemtime($cache->cache_dir . 'data_install_list.' . $phpEx) : 0;
                // Make sure the list is up-to-date
                if ($install_list !== false) {
                    $get_new_list = false;
                    foreach ($this->install_info['files'] as $file) {
                        if (file_exists($phpbb_root_path . $file) && filemtime($phpbb_root_path . $file) > $modified) {
                            $get_new_list = true;
                            break;
                        }
                    }
                } else {
                    $get_new_list = true;
                }
                if ($get_new_list) {
                    $install_list = $this->get_install_structure();
                    $cache->put('_install_list', $install_list);
                }
                if ($action == 'diff') {
                    $this->show_diff($install_list);
                    return;
                }
                // Now assign the list to the template
                foreach ($install_list as $status => $filelist) {
                    if ($status == 'no_update' || !sizeof($filelist)) {
                        continue;
                    }
                    $template->assign_block_vars('files', array('S_STATUS' => true, 'STATUS' => $status, 'L_STATUS' => $user->lang['STATUS_' . strtoupper($status)], 'TITLE' => $user->lang['FILES_' . strtoupper($status)], 'EXPLAIN' => $user->lang['FILES_' . strtoupper($status) . '_EXPLAIN']));
                    foreach ($filelist as $file_struct) {
                        $filename = htmlspecialchars($file_struct['filename']);
                        if (strrpos($filename, '/') !== false) {
                            $dir_part = substr($filename, 0, strrpos($filename, '/') + 1);
                            $file_part = substr($filename, strrpos($filename, '/') + 1);
                        } else {
                            $dir_part = '';
                            $file_part = $filename;
                        }
                        $diff_url = append_sid($this->p_master->module_url, "mode={$mode}&amp;sub=file_check&amp;action=diff&amp;status={$status}&amp;file=" . urlencode($file_struct['filename']));
                        $template->assign_block_vars('files', array('STATUS' => $status, 'FILENAME' => $filename, 'DIR_PART' => $dir_part, 'FILE_PART' => $file_part, 'NUM_CONFLICTS' => isset($file_struct['conflicts']) ? $file_struct['conflicts'] : 0, 'S_CUSTOM' => $file_struct['custom'] ? true : false, 'CUSTOM_ORIGINAL' => $file_struct['custom'] ? $file_struct['original'] : '', 'U_SHOW_DIFF' => $diff_url, 'L_SHOW_DIFF' => $status != 'up_to_date' ? $user->lang['SHOW_DIFF_' . strtoupper($status)] : '', 'U_VIEW_MOD_FILE' => $diff_url . '&amp;op=' . MERGE_MOD_FILE, 'U_VIEW_NEW_FILE' => $diff_url . '&amp;op=' . MERGE_NEW_FILE, 'U_VIEW_NO_MERGE_MOD' => $diff_url . '&amp;op=' . MERGE_NO_MERGE_MOD, 'U_VIEW_NO_MERGE_NEW' => $diff_url . '&amp;op=' . MERGE_NO_MERGE_NEW));
                    }
                }
                $all_up_to_date = true;
                foreach ($install_list as $status => $filelist) {
                    if ($status != 'up_to_date' && $status != 'custom' && sizeof($filelist)) {
                        $all_up_to_date = false;
                        break;
                    }
                }
                $template->assign_vars(array('S_FILE_CHECK' => true, 'S_ALL_UP_TO_DATE' => $all_up_to_date, 'U_ACTION' => append_sid($this->p_master->module_url, "mode={$mode}&amp;sub=file_check"), 'U_UPDATE_ACTION' => append_sid($this->p_master->module_url, "mode={$mode}&amp;sub=update_files")));
                if ($all_up_to_date and $sub == 'final') {
                    // Remove the lock file
                    @unlink($phpbb_root_path . 'cache/install_lock');
                }
                // Make sure we stay at the final if we checked_again and all is now up to date
                if (!empty($_POST['check_again']) && $all_up_to_date) {
                    $sub = $this->p_master->sub = 'final';
                }
                if ($all_up_to_date) {
                    // Refresh any style css data we updated - this may cause some unhappy users, but
                    $sql = 'SELECT *
						FROM ' . STYLES_THEME_TABLE;
                    $result = $db->sql_query($sql);
                    while ($theme = $db->sql_fetchrow($result)) {
                        //Check For Themes Updated By Installer
                        if (file_exists($phpbb_root_path . "garage/install/install/styles/{$theme['theme_name']}/theme/index." . $phpEx)) {
                            $recache = empty($theme['theme_data']) ? true : false;
                            $update_time = time();
                            // We test for stylesheet.css because it is faster and most likely the only file changed on common themes
                            if (!$recache && $theme['theme_mtime'] < @filemtime("{$phpbb_root_path}styles/" . $theme['theme_path'] . '/theme/stylesheet.css')) {
                                $recache = true;
                                $update_time = @filemtime("{$phpbb_root_path}styles/" . $theme['theme_path'] . '/theme/stylesheet.css');
                            } else {
                                if (!$recache) {
                                    $last_change = $theme['theme_mtime'];
                                    $dir = @opendir("{$phpbb_root_path}styles/{$theme['theme_path']}/theme");
                                    if ($dir) {
                                        while (($entry = readdir($dir)) !== false) {
                                            if (substr(strrchr($entry, '.'), 1) == 'css' && $last_change < @filemtime("{$phpbb_root_path}styles/{$theme['theme_path']}/theme/{$entry}")) {
                                                $recache = true;
                                                break;
                                            }
                                        }
                                        closedir($dir);
                                    }
                                }
                            }
                            if ($recache) {
                                include_once $phpbb_root_path . 'includes/acp/acp_styles.' . $phpEx;
                                $theme['theme_data'] = acp_styles::db_theme_data($theme);
                                $theme['theme_mtime'] = $update_time;
                                // Save CSS contents
                                $sql_ary = array('theme_mtime' => $theme['theme_mtime'], 'theme_data' => $theme['theme_data']);
                                $sql = 'UPDATE ' . STYLES_THEME_TABLE . ' SET ' . $db->sql_build_array('UPDATE', $sql_ary) . '
									WHERE theme_id = ' . $theme['theme_id'];
                                $db->sql_query($sql);
                                $cache->destroy('sql', STYLES_THEME_TABLE);
                            }
                        }
                    }
                    $db->sql_freeresult($result);
                    // Refresh any imageset data we updated - but only for garage images
                    $sql = 'SELECT *
						FROM ' . STYLES_IMAGESET_TABLE;
                    $result = $db->sql_query($sql);
                    while ($imageset = $db->sql_fetchrow($result)) {
                        $sql_ary = array();
                        $db->sql_transaction('begin');
                        if (!class_exists('garage_template')) {
                            include $phpbb_root_path . 'includes/mods/class_garage_template.' . $phpEx;
                            $garage_template = new garage_template();
                        }
                        //We need to build the imageset_keys now only for garage keys
                        $imageset_keys = array();
                        $imageset_keys['buttons'] = array();
                        $imageset_keys = $garage_template->update_imageset_keys($imageset_keys);
                        $imageset_definitions = array();
                        foreach ($imageset_keys as $topic => $key_array) {
                            $imageset_definitions = array_merge($imageset_definitions, $key_array);
                        }
                        //Check For Imageset Updated By Installer
                        if (file_exists($phpbb_root_path . "garage/install/install/new/styles/{$imageset['imageset_path']}/imageset/imageset.cfg")) {
                            $cfg_data_imageset = parse_cfg_file("{$phpbb_root_path}styles/{$imageset['imageset_path']}/imageset/imageset.cfg");
                            $sql = 'DELETE FROM ' . STYLES_IMAGESET_DATA_TABLE . '
								WHERE imageset_id = ' . $imageset['imageset_id'] . '
									AND ' . $db->sql_in_set('image_name', $imageset_keys['garage']);
                            $db->sql_query($sql);
                            foreach ($cfg_data_imageset as $image_name => $value) {
                                //Lets cut to the chase and make sure we only work with garage images
                                $image_wanted = substr($image_name, 4);
                                if (!in_array($image_wanted, $imageset_keys['garage'])) {
                                    continue;
                                }
                                if (strpos($value, '*') !== false) {
                                    if (substr($value, -1, 1) === '*') {
                                        list($image_filename, $image_height) = explode('*', $value);
                                        $image_width = 0;
                                    } else {
                                        list($image_filename, $image_height, $image_width) = explode('*', $value);
                                    }
                                } else {
                                    $image_filename = $value;
                                    $image_height = $image_width = 0;
                                }
                                if (strpos($image_name, 'img_') === 0 && $image_filename) {
                                    $image_name = substr($image_name, 4);
                                    if (in_array($image_name, $imageset_definitions)) {
                                        $sql_ary[] = array('image_name' => (string) $image_name, 'image_filename' => (string) $image_filename, 'image_height' => (int) $image_height, 'image_width' => (int) $image_width, 'imageset_id' => (int) $imageset['imageset_id'], 'image_lang' => '');
                                    }
                                }
                            }
                        }
                        $sql2 = 'SELECT lang_dir
							FROM ' . LANG_TABLE;
                        $result2 = $db->sql_query($sql2);
                        while ($language = $db->sql_fetchrow($result2)) {
                            //Check For Language Imageset Updated By Installer
                            if (file_exists($phpbb_root_path . "garage/install/install/new/styles/{$imageset['imageset_path']}/imageset/{$language['lang_dir']}/imageset.cfg")) {
                                $cfg_data_imageset_data = parse_cfg_file("{$phpbb_root_path}styles/{$imageset['imageset_path']}/imageset/{$language['lang_dir']}/imageset.cfg");
                                $sql = 'DELETE FROM ' . STYLES_IMAGESET_DATA_TABLE . '
									WHERE imageset_id = ' . $imageset['imageset_id'] . '
										AND ' . $db->sql_in_set('image_name', $imageset_keys['buttons']) . "\n\t\t\t\t\t\t\t\t\t\tAND image_lang = '{$language['lang_dir']}'";
                                $db->sql_query($sql);
                                foreach ($cfg_data_imageset_data as $image_name => $value) {
                                    //Lets cut to the chase and make sure we only work with garage images
                                    $image_wanted = substr($image_name, 4);
                                    if (!in_array($image_wanted, $imageset_keys['buttons'])) {
                                        continue;
                                    }
                                    if (strpos($value, '*') !== false) {
                                        if (substr($value, -1, 1) === '*') {
                                            list($image_filename, $image_height) = explode('*', $value);
                                            $image_width = 0;
                                        } else {
                                            list($image_filename, $image_height, $image_width) = explode('*', $value);
                                        }
                                    } else {
                                        $image_filename = $value;
                                        $image_height = $image_width = 0;
                                    }
                                    if (strpos($image_name, 'img_') === 0 && $image_filename) {
                                        $image_name = substr($image_name, 4);
                                        if (in_array($image_name, $imageset_definitions)) {
                                            $sql_ary[] = array('image_name' => (string) $image_name, 'image_filename' => (string) $image_filename, 'image_height' => (int) $image_height, 'image_width' => (int) $image_width, 'imageset_id' => (int) $imageset['imageset_id'], 'image_lang' => (string) $language['lang_dir']);
                                        }
                                    }
                                }
                            }
                        }
                        $db->sql_freeresult($result2);
                        $db->sql_multi_insert(STYLES_IMAGESET_DATA_TABLE, $sql_ary);
                        $db->sql_transaction('commit');
                    }
                    $db->sql_freeresult($result);
                    $cache->destroy('sql', STYLES_IMAGESET_DATA_TABLE);
                    add_log('admin', 'LOG_IMAGESET_REFRESHED', $imageset['imageset_name']);
                    $db->sql_return_on_error(true);
                    $db->sql_query('DELETE FROM ' . GARAGE_CONFIG_TABLE . " WHERE config_name = 'version_update_from'");
                    $db->sql_return_on_error(false);
                    $cache->purge();
                }
                break;
            case 'update_files':
                $this->tpl_name = 'garage_install_update';
                $this->page_title = 'STAGE_UPDATE_FILES';
                $s_hidden_fields = '';
                $conflicts = request_var('conflict', array('' => 0));
                $modified = request_var('modified', array('' => 0));
                foreach ($conflicts as $filename => $merge_option) {
                    $s_hidden_fields .= '<input type="hidden" name="conflict[' . htmlspecialchars($filename) . ']" value="' . $merge_option . '" />';
                }
                foreach ($modified as $filename => $merge_option) {
                    if (!$merge_option) {
                        continue;
                    }
                    $s_hidden_fields .= '<input type="hidden" name="modified[' . htmlspecialchars($filename) . ']" value="' . $merge_option . '" />';
                }
                $no_update = request_var('no_update', array(0 => ''));
                foreach ($no_update as $index => $filename) {
                    $s_hidden_fields .= '<input type="hidden" name="no_update[]" value="' . htmlspecialchars($filename) . '" />';
                }
                if (!empty($_POST['download'])) {
                    $this->include_file('includes/functions_compress.' . $phpEx);
                    $use_method = request_var('use_method', '');
                    $methods = array('.tar');
                    $available_methods = array('.tar.gz' => 'zlib', '.tar.bz2' => 'bz2', '.zip' => 'zlib');
                    foreach ($available_methods as $type => $module) {
                        if (!@extension_loaded($module)) {
                            continue;
                        }
                        $methods[] = $type;
                    }
                    // Let the user decide in which format he wants to have the pack
                    if (!$use_method) {
                        $this->page_title = 'SELECT_DOWNLOAD_FORMAT';
                        $radio_buttons = '';
                        foreach ($methods as $method) {
                            $radio_buttons .= '<label><input type="radio"' . (!$radio_buttons ? ' id="use_method"' : '') . ' class="radio" value="' . $method . '" name="use_method" /> ' . $method . '</label>';
                        }
                        $template->assign_vars(array('S_DOWNLOAD_FILES' => true, 'U_ACTION' => append_sid($this->p_master->module_url, "mode={$mode}&amp;sub=update_files"), 'RADIO_BUTTONS' => $radio_buttons, 'S_HIDDEN_FIELDS' => $s_hidden_fields));
                        // To ease the update process create a file location map
                        $install_list = $cache->get('_install_list');
                        $script_path = $config['force_server_vars'] ? $config['script_path'] == '/' ? '/' : $config['script_path'] . '/' : $user->page['root_script_path'];
                        foreach ($install_list as $status => $files) {
                            if ($status == 'up_to_date' || $status == 'no_update') {
                                continue;
                            }
                            foreach ($files as $file_struct) {
                                if (in_array($file_struct['filename'], $no_update)) {
                                    continue;
                                }
                                $template->assign_block_vars('location', array('SOURCE' => htmlspecialchars($file_struct['filename']), 'DESTINATION' => $script_path . htmlspecialchars($file_struct['filename'])));
                            }
                        }
                        return;
                    }
                    if (!in_array($use_method, $methods)) {
                        $use_method = '.tar';
                    }
                    $update_mode = 'download';
                } else {
                    $this->include_file('includes/functions_transfer.' . $phpEx);
                    // Choose FTP, if not available use fsock...
                    $method = request_var('method', '');
                    $submit = isset($_POST['submit']) ? true : false;
                    $test_ftp_connection = request_var('test_connection', '');
                    if (!$method) {
                        $method = 'ftp';
                        $methods = transfer::methods();
                        if (!in_array('ftp', $methods)) {
                            $method = $methods[0];
                        }
                    }
                    $test_connection = false;
                    if ($test_ftp_connection || $submit) {
                        $transfer = new $method(request_var('host', ''), request_var('username', ''), request_var('password', ''), request_var('root_path', ''), request_var('port', ''), request_var('timeout', ''));
                        $test_connection = $transfer->open_session();
                        // Make sure that the directory is correct by checking for the existence of common.php
                        if ($test_connection === true) {
                            // Check for common.php file
                            if (!$transfer->file_exists($phpbb_root_path, 'common.' . $phpEx)) {
                                $test_connection = 'ERR_WRONG_PATH_TO_PHPBB';
                            }
                        }
                        $transfer->close_session();
                        // Make sure the login details are correct before continuing
                        if ($submit && $test_connection !== true) {
                            $submit = false;
                            $test_ftp_connection = true;
                        }
                    }
                    if (!$submit) {
                        $this->page_title = 'SELECT_FTP_SETTINGS';
                        if (!class_exists($method)) {
                            trigger_error('Method does not exist.', E_USER_ERROR);
                        }
                        $requested_data = call_user_func(array($method, 'data'));
                        foreach ($requested_data as $data => $default) {
                            $template->assign_block_vars('data', array('DATA' => $data, 'NAME' => $user->lang[strtoupper($method . '_' . $data)], 'EXPLAIN' => $user->lang[strtoupper($method . '_' . $data) . '_EXPLAIN'], 'DEFAULT' => !empty($_REQUEST[$data]) ? request_var($data, '') : $default));
                        }
                        $s_hidden_fields .= build_hidden_fields(array('method' => $method));
                        $template->assign_vars(array('S_CONNECTION_SUCCESS' => $test_ftp_connection && $test_connection === true ? true : false, 'S_CONNECTION_FAILED' => $test_ftp_connection && $test_connection !== true ? true : false, 'ERROR_MSG' => $test_ftp_connection && $test_connection !== true ? $user->lang[$test_connection] : '', 'S_FTP_UPLOAD' => true, 'UPLOAD_METHOD' => $method, 'U_ACTION' => append_sid($this->p_master->module_url, "mode={$mode}&amp;sub=update_files"), 'S_HIDDEN_FIELDS' => $s_hidden_fields));
                        return;
                    }
                    $update_mode = 'upload';
                }
                // Now update the installation or download the archive...
                $download_filename = 'install_phpbbgarage_' . $this->install_info['version']['install'];
                $archive_filename = $download_filename . '_' . time() . '_' . unique_id();
                $install_list = $cache->get('_install_list');
                $conflicts = request_var('conflict', array('' => 0));
                $modified = request_var('modified', array('' => 0));
                if ($install_list === false) {
                    trigger_error($user->lang['NO_UPDATE_INFO'], E_USER_ERROR);
                }
                // Check if the conflicts data is valid
                if (sizeof($conflicts)) {
                    $conflict_filenames = array();
                    foreach ($install_list['conflict'] as $files) {
                        $conflict_filenames[] = $files['filename'];
                    }
                    $new_conflicts = array();
                    foreach ($conflicts as $filename => $diff_method) {
                        if (in_array($filename, $conflict_filenames)) {
                            $new_conflicts[$filename] = $diff_method;
                        }
                    }
                    $conflicts = $new_conflicts;
                }
                // Build list for modifications
                if (sizeof($modified)) {
                    $modified_filenames = array();
                    foreach ($install_list['modified'] as $files) {
                        $modified_filenames[] = $files['filename'];
                    }
                    $new_modified = array();
                    foreach ($modified as $filename => $diff_method) {
                        if (in_array($filename, $modified_filenames)) {
                            $new_modified[$filename] = $diff_method;
                        }
                    }
                    $modified = $new_modified;
                }
                // Check number of conflicting files, they need to be equal. For modified files the number can differ
                if (sizeof($install_list['conflict']) != sizeof($conflicts)) {
                    trigger_error($user->lang['MERGE_SELECT_ERROR'], E_USER_ERROR);
                }
                // Now init the connection
                if ($update_mode == 'download') {
                    if ($use_method == '.zip') {
                        $compress = new compress_zip('w', $phpbb_root_path . 'store/' . $archive_filename . $use_method);
                    } else {
                        $compress = new compress_tar('w', $phpbb_root_path . 'store/' . $archive_filename . $use_method, $use_method);
                    }
                } else {
                    $transfer = new $method(request_var('host', ''), request_var('username', ''), request_var('password', ''), request_var('root_path', ''), request_var('port', ''), request_var('timeout', ''));
                    $transfer->open_session();
                }
                // Ok, go through the update list and do the operations based on their status
                foreach ($install_list as $status => $files) {
                    foreach ($files as $file_struct) {
                        // Skip this file if the user selected to not update it
                        if (in_array($file_struct['filename'], $no_update)) {
                            continue;
                        }
                        $original_filename = $file_struct['custom'] ? $file_struct['original'] : $file_struct['filename'];
                        switch ($status) {
                            case 'new':
                            case 'new_conflict':
                            case 'not_modified':
                                if ($update_mode == 'download') {
                                    $compress->add_custom_file($this->new_location . $original_filename, $file_struct['filename']);
                                } else {
                                    if ($status != 'new') {
                                        $transfer->rename($file_struct['filename'], $file_struct['filename'] . '.bak');
                                    }
                                    $transfer->copy_file($this->new_location . $original_filename, $file_struct['filename']);
                                }
                                break;
                            case 'modified':
                                $option = isset($modified[$file_struct['filename']]) ? $modified[$file_struct['filename']] : 0;
                                switch ($option) {
                                    case MERGE_NO_MERGE_NEW:
                                        $contents = file_get_contents($this->new_location . $original_filename);
                                        break;
                                    case MERGE_NO_MERGE_MOD:
                                        $contents = file_get_contents($phpbb_root_path . $file_struct['filename']);
                                        break;
                                    default:
                                        $diff = $this->return_diff($this->old_location . $original_filename, $phpbb_root_path . $file_struct['filename'], $this->new_location . $original_filename);
                                        $contents = implode("\n", $diff->merged_output());
                                        unset($diff);
                                        break;
                                }
                                if ($update_mode == 'download') {
                                    $compress->add_data($contents, $file_struct['filename']);
                                } else {
                                    // @todo add option to specify if a backup file should be created?
                                    $transfer->rename($file_struct['filename'], $file_struct['filename'] . '.bak');
                                    $transfer->write_file($file_struct['filename'], $contents);
                                }
                                break;
                            case 'conflict':
                                $option = $conflicts[$file_struct['filename']];
                                $contents = '';
                                switch ($option) {
                                    case MERGE_NO_MERGE_NEW:
                                        $contents = file_get_contents($this->new_location . $original_filename);
                                        break;
                                    case MERGE_NO_MERGE_MOD:
                                        $contents = file_get_contents($phpbb_root_path . $file_struct['filename']);
                                        break;
                                    default:
                                        $diff = $this->return_diff($this->old_location . $original_filename, $phpbb_root_path . $file_struct['filename'], $this->new_location . $original_filename);
                                        if ($option == MERGE_NEW_FILE) {
                                            $contents = implode("\n", $diff->merged_new_output());
                                        } else {
                                            if ($option == MERGE_MOD_FILE) {
                                                $contents = implode("\n", $diff->merged_orig_output());
                                            } else {
                                                unset($diff);
                                                break 2;
                                            }
                                        }
                                        unset($diff);
                                        break;
                                }
                                if ($update_mode == 'download') {
                                    $compress->add_data($contents, $file_struct['filename']);
                                } else {
                                    $transfer->rename($file_struct['filename'], $file_struct['filename'] . '.bak');
                                    $transfer->write_file($file_struct['filename'], $contents);
                                }
                                break;
                        }
                    }
                }
                if ($update_mode == 'download') {
                    $compress->close();
                    $compress->download($archive_filename, $download_filename);
                    @unlink($phpbb_root_path . 'store/' . $archive_filename . $use_method);
                    exit;
                } else {
                    $transfer->close_session();
                    $template->assign_vars(array('S_UPLOAD_SUCCESS' => true, 'U_ACTION' => append_sid($this->p_master->module_url, "mode={$mode}&amp;sub=final")));
                    return;
                }
                break;
        }
        switch ($sub) {
            case 'final':
                $this->tpl_name = 'garage_install_install';
                // Remove the lock file
                @unlink($phpbb_root_path . 'cache/install_lock');
                $sql = $db->sql_build_query('SELECT', array('SELECT' => 'c.config_name, c.config_value', 'FROM' => array(GARAGE_CONFIG_TABLE => 'c')));
                $result = $db->sql_query($sql);
                while ($row = $db->sql_fetchrow($result)) {
                    $garage_config[$row['config_name']] = $row['config_value'];
                }
                $db->sql_freeresult($result);
                add_log('admin', 'LOG_GARAGE_INSTALL', $garage_config['version']);
                $template->assign_vars(array('S_FILE_CHECK' => false, 'TITLE' => $lang['INSTALL_CONGRATS'], 'BODY' => sprintf($lang['INSTALL_CONGRATS_EXPLAIN'], $garage_config['version'], append_sid($phpbb_root_path . 'garage/install/index.' . $phpEx, 'mode=convert&amp;'), '../docs/README.html')));
                $sql = 'INSERT INTO ' . GARAGE_CONFIG_TABLE . ' ' . $db->sql_build_array('INSERT', array('config_name' => 'installed', 'config_value' => 1));
                $db->sql_query($sql);
                $cache->purge();
                break;
        }
    }
	function main($mode, $sub)
	{
		global $template, $phpEx, $phpbb_root_path, $user, $db, $config, $cache, $auth;

		$this->tpl_name = 'install_update';
		$this->page_title = 'UPDATE_INSTALLATION';
		$this->unequal_version = false;

		$this->old_location = $phpbb_root_path . 'install/update/old/';
		$this->new_location = $phpbb_root_path . 'install/update/new/';

		// Init DB
		require($phpbb_root_path . 'config.' . $phpEx);
		require($phpbb_root_path . 'includes/db/' . $dbms . '.' . $phpEx);
		require($phpbb_root_path . 'includes/constants.' . $phpEx);

		// Special options for conflicts/modified files
		define('MERGE_NO_MERGE_NEW', 1);
		define('MERGE_NO_MERGE_MOD', 2);
		define('MERGE_NEW_FILE', 3);
		define('MERGE_MOD_FILE', 4);

		$db = new $sql_db();

		// Connect to DB
		$db->sql_connect($dbhost, $dbuser, $dbpasswd, $dbname, $dbport, false, false);

		// We do not need this any longer, unset for safety purposes
		unset($dbpasswd);

		$config = array();

		$sql = 'SELECT config_name, config_value
			FROM ' . CONFIG_TABLE;
		$result = $db->sql_query($sql);

		while ($row = $db->sql_fetchrow($result))
		{
			$config[$row['config_name']] = $row['config_value'];
		}
		$db->sql_freeresult($result);

		// Force template recompile
		$config['load_tplcompile'] = 1;

		// First of all, init the user session
		$user->session_begin();
		$auth->acl($user->data);

		$user->setup('install');

		// If we are within the intro page we need to make sure we get up-to-date version info
		if ($sub == 'intro')
		{
			$cache->destroy('_version_info');
		}

		// Set custom template again. ;)
		$template->set_custom_template('../adm/style', 'admin');

		// still, the acp template is never stored in the database
		$user->theme['template_storedb'] = false;

		// Get current and latest version
		if (($latest_version = $cache->get('_version_info')) === false)
		{
			$this->latest_version = $this->get_file('version_info');
			$cache->put('_version_info', $this->latest_version);
		}
		else
		{
			$this->latest_version = $latest_version;
		}

		// For the current version we trick a bit. ;)
		$this->current_version = (!empty($config['version_update_from'])) ? $config['version_update_from'] : $config['version'];

		$up_to_date = (version_compare(str_replace('rc', 'RC', strtolower($this->current_version)), str_replace('rc', 'RC', strtolower($this->latest_version)), '<')) ? false : true;

		// Check for a valid update directory, else point the user to the phpbb.com website
		if (!file_exists($phpbb_root_path . 'install/update') || !file_exists($phpbb_root_path . 'install/update/index.' . $phpEx) || !file_exists($this->old_location) || !file_exists($this->new_location))
		{
			$template->assign_vars(array(
				'S_ERROR'		=> true,
				'ERROR_MSG'		=> ($up_to_date) ? $user->lang['NO_UPDATE_FILES_UP_TO_DATE'] : sprintf($user->lang['NO_UPDATE_FILES_OUTDATED'], $config['version'], $this->current_version, $this->latest_version))
			);

			return;
		}

		$this->update_info = $this->get_file('update_info');

		// Make sure the update directory holds the correct information
		// Since admins are able to run the update/checks more than once we only check if the current version is lower or equal than the version to which we update to.
		if (version_compare(str_replace('rc', 'RC', strtolower($this->current_version)), str_replace('rc', 'RC', strtolower($this->update_info['version']['to'])), '>'))
		{
			$template->assign_vars(array(
				'S_ERROR'		=> true,
				'ERROR_MSG'		=> sprintf($user->lang['INCOMPATIBLE_UPDATE_FILES'], $config['version'], $this->update_info['version']['from'], $this->update_info['version']['to']))
			);

			return;
		}

		// Check if the update files stored are for the latest version...
		if ($this->latest_version != $this->update_info['version']['to'])
		{
			$this->unequal_version = true;

			$template->assign_vars(array(
				'S_WARNING'		=> true,
				'WARNING_MSG'	=> sprintf($user->lang['OLD_UPDATE_FILES'], $this->update_info['version']['from'], $this->update_info['version']['to'], $this->latest_version))
			);
		}

		if ($this->test_update === false)
		{
			// Got the updater template itself updated? If so, we are able to directly use it - but only if all three files are present
			if (in_array('adm/style/install_update.html', $this->update_info['files']))
			{
				$this->tpl_name = '../../install/update/new/adm/style/install_update';
			}

			// What about the language file? Got it updated?
			if (in_array('language/en/install.php', $this->update_info['files']))
			{
				$lang = array();
				include($this->new_location . 'language/en/install.php');
				// only add new keys to user's language in english
				$new_keys = array_diff(array_keys($lang), array_keys($user->lang));
				foreach ($new_keys as $i => $new_key)
				{
					$user->lang[$new_key] = $lang[$new_key];
				}
			}
		}

		// Include renderer and engine
		$this->include_file('includes/diff/diff.' . $phpEx);
		$this->include_file('includes/diff/engine.' . $phpEx);
		$this->include_file('includes/diff/renderer.' . $phpEx);

		// Make sure we stay at the file check if checking the files again
		if (!empty($_POST['check_again']))
		{
			$sub = $this->p_master->sub = 'file_check';
		}

		switch ($sub)
		{
			case 'intro':
				$this->page_title = 'UPDATE_INSTALLATION';

				$template->assign_vars(array(
					'S_INTRO'		=> true,
					'U_ACTION'		=> append_sid($this->p_master->module_url, "mode=$mode&amp;sub=version_check"),
				));

				// Make sure the update list is destroyed.
				$cache->destroy('_update_list');
				$cache->destroy('_diff_files');
			break;

			case 'version_check':
				$this->page_title = 'STAGE_VERSION_CHECK';

				$template->assign_vars(array(
					'S_UP_TO_DATE'		=> $up_to_date,
					'S_VERSION_CHECK'	=> true,

					'U_ACTION'				=> append_sid($this->p_master->module_url, "mode=$mode&amp;sub=file_check"),
					'U_DB_UPDATE_ACTION'	=> append_sid($this->p_master->module_url, "mode=$mode&amp;sub=update_db"),

					'LATEST_VERSION'	=> $this->latest_version,
					'CURRENT_VERSION'	=> $this->current_version)
				);

				// Print out version the update package updates to
				if ($this->unequal_version)
				{
					$template->assign_var('PACKAGE_VERSION', $this->update_info['version']['to']);
				}

			break;

			case 'update_db':

				// Make sure the database update is valid for the latest version
				$valid = false;
				$updates_to_version = '';

				if (file_exists($phpbb_root_path . 'install/database_update.' . $phpEx))
				{
					include_once($phpbb_root_path . 'install/database_update.' . $phpEx);

					if ($updates_to_version === $this->update_info['version']['to'])
					{
						$valid = true;
					}
				}

				// Should not happen at all
				if (!$valid)
				{
					trigger_error($user->lang['DATABASE_UPDATE_INFO_OLD'], E_USER_ERROR);
				}

				// Just a precaution
				$cache->purge();

				// Redirect the user to the database update script with some explanations...
				$template->assign_vars(array(
					'S_DB_UPDATE'			=> true,
					'S_DB_UPDATE_FINISHED'	=> ($config['version'] == $this->update_info['version']['to']) ? true : false,
					'U_DB_UPDATE'			=> append_sid($phpbb_root_path . 'install/database_update.' . $phpEx, 'type=1&amp;language=' . $user->data['user_lang']),
					'U_DB_UPDATE_ACTION'	=> append_sid($this->p_master->module_url, "mode=$mode&amp;sub=update_db"),
					'U_ACTION'				=> append_sid($this->p_master->module_url, "mode=$mode&amp;sub=file_check"),
				));

			break;

			case 'file_check':

				// Make sure the previous file collection is no longer valid...
				$cache->destroy('_diff_files');

				$this->page_title = 'STAGE_FILE_CHECK';

				// Now make sure our update list is correct if the admin refreshes
				$action = request_var('action', '');

				// We are directly within an update. To make sure our update list is correct we check its status.
				$update_list = (!empty($_POST['check_again'])) ? false : $cache->get('_update_list');
				$modified = ($update_list !== false) ? @filemtime($cache->cache_dir . 'data_update_list.' . $phpEx) : 0;

				// Make sure the list is up-to-date
				if ($update_list !== false)
				{
					$get_new_list = false;
					foreach ($this->update_info['files'] as $file)
					{
						if (file_exists($phpbb_root_path . $file) && filemtime($phpbb_root_path . $file) > $modified)
						{
							$get_new_list = true;
							break;
						}
					}
				}
				else
				{
					$get_new_list = true;
				}

				if (!$get_new_list && $update_list['status'] != -1)
				{
					$get_new_list = true;
				}

				if ($get_new_list)
				{
					$this->get_update_structure($update_list);
					$cache->put('_update_list', $update_list);

					// Refresh the page if we are still not finished...
					if ($update_list['status'] != -1)
					{
						$refresh_url = append_sid($this->p_master->module_url, "mode=$mode&amp;sub=file_check");
						meta_refresh(2, $refresh_url);

						$template->assign_vars(array(
							'S_IN_PROGRESS'		=> true,
							'S_COLLECTED'		=> (int) $update_list['status'],
							'S_TO_COLLECT'		=> sizeof($this->update_info['files']),
							'L_IN_PROGRESS'				=> $user->lang['COLLECTING_FILE_DIFFS'],
							'L_IN_PROGRESS_EXPLAIN'		=> sprintf($user->lang['NUMBER_OF_FILES_COLLECTED'], (int) $update_list['status'], sizeof($this->update_info['files'])),
						));

						return;
					}
				}

				if ($action == 'diff')
				{
					$this->show_diff($update_list);
					return;
				}

				if (sizeof($update_list['no_update']))
				{
					$template->assign_vars(array(
						'S_NO_UPDATE_FILES'		=> true,
						'NO_UPDATE_FILES'		=> implode(', ', array_map('htmlspecialchars', $update_list['no_update'])))
					);
				}

				// Now assign the list to the template
				foreach ($update_list as $status => $filelist)
				{
					if ($status == 'no_update' || !sizeof($filelist) || $status == 'status')
					{
						continue;
					}

					$template->assign_block_vars('files', array(
						'S_STATUS'		=> true,
						'STATUS'		=> $status,
						'L_STATUS'		=> $user->lang['STATUS_' . strtoupper($status)],
						'TITLE'			=> $user->lang['FILES_' . strtoupper($status)],
						'EXPLAIN'		=> $user->lang['FILES_' . strtoupper($status) . '_EXPLAIN'],
						)
					);

					foreach ($filelist as $file_struct)
					{
						$s_binary = (!empty($this->update_info['binary']) && in_array($file_struct['filename'], $this->update_info['binary'])) ? true : false;

						$filename = htmlspecialchars($file_struct['filename']);
						if (strrpos($filename, '/') !== false)
						{
							$dir_part = substr($filename, 0, strrpos($filename, '/') + 1);
							$file_part = substr($filename, strrpos($filename, '/') + 1);
						}
						else
						{
							$dir_part = '';
							$file_part = $filename;
						}

						$diff_url = append_sid($this->p_master->module_url, "mode=$mode&amp;sub=file_check&amp;action=diff&amp;status=$status&amp;file=" . urlencode($file_struct['filename']));

						$template->assign_block_vars('files', array(
							'STATUS'			=> $status,

							'FILENAME'			=> $filename,
							'DIR_PART'			=> $dir_part,
							'FILE_PART'			=> $file_part,
							'NUM_CONFLICTS'		=> (isset($file_struct['conflicts'])) ? $file_struct['conflicts'] : 0,

							'S_CUSTOM'			=> ($file_struct['custom']) ? true : false,
							'S_BINARY'			=> $s_binary,
							'CUSTOM_ORIGINAL'	=> ($file_struct['custom']) ? $file_struct['original'] : '',

							'U_SHOW_DIFF'		=> $diff_url,
							'L_SHOW_DIFF'		=> ($status != 'up_to_date') ? $user->lang['SHOW_DIFF_' . strtoupper($status)] : '',

							'U_VIEW_MOD_FILE'		=> $diff_url . '&amp;op=' . MERGE_MOD_FILE,
							'U_VIEW_NEW_FILE'		=> $diff_url . '&amp;op=' . MERGE_NEW_FILE,
							'U_VIEW_NO_MERGE_MOD'	=> $diff_url . '&amp;op=' . MERGE_NO_MERGE_MOD,
							'U_VIEW_NO_MERGE_NEW'	=> $diff_url . '&amp;op=' . MERGE_NO_MERGE_NEW,
						));
					}
				}

				$all_up_to_date = true;
				foreach ($update_list as $status => $filelist)
				{
					if ($status != 'up_to_date' && $status != 'custom' && $status != 'status' && sizeof($filelist))
					{
						$all_up_to_date = false;
						break;
					}
				}

				$template->assign_vars(array(
					'S_FILE_CHECK'			=> true,
					'S_ALL_UP_TO_DATE'		=> $all_up_to_date,
					'S_VERSION_UP_TO_DATE'	=> $up_to_date,
					'U_ACTION'				=> append_sid($this->p_master->module_url, "mode=$mode&amp;sub=file_check"),
					'U_UPDATE_ACTION'		=> append_sid($this->p_master->module_url, "mode=$mode&amp;sub=update_files"),
					'U_DB_UPDATE_ACTION'	=> append_sid($this->p_master->module_url, "mode=$mode&amp;sub=update_db"),
				));

				if ($all_up_to_date)
				{
					// Add database update to log
					add_log('admin', 'LOG_UPDATE_PHPBB', $this->current_version, $this->latest_version);

					// Refresh prosilver css data - this may cause some unhappy users, but
					$sql = 'SELECT *
						FROM ' . STYLES_THEME_TABLE . "
						WHERE theme_name = 'prosilver'";
					$result = $db->sql_query($sql);
					$theme = $db->sql_fetchrow($result);
					$db->sql_freeresult($result);

					if ($theme)
					{
						$recache = (empty($theme['theme_data'])) ? true : false;
						$update_time = time();

						// We test for stylesheet.css because it is faster and most likely the only file changed on common themes
						if (!$recache && $theme['theme_mtime'] < @filemtime("{$phpbb_root_path}styles/" . $theme['theme_path'] . '/theme/stylesheet.css'))
						{
							$recache = true;
							$update_time = @filemtime("{$phpbb_root_path}styles/" . $theme['theme_path'] . '/theme/stylesheet.css');
						}
						else if (!$recache)
						{
							$last_change = $theme['theme_mtime'];
							$dir = @opendir("{$phpbb_root_path}styles/{$theme['theme_path']}/theme");

							if ($dir)
							{
								while (($entry = readdir($dir)) !== false)
								{
									if (substr(strrchr($entry, '.'), 1) == 'css' && $last_change < @filemtime("{$phpbb_root_path}styles/{$theme['theme_path']}/theme/{$entry}"))
									{
										$recache = true;
										break;
									}
								}
								closedir($dir);
							}
						}

						if ($recache)
						{
							include_once($phpbb_root_path . 'includes/acp/acp_styles.' . $phpEx);

							$theme['theme_data'] = acp_styles::db_theme_data($theme);
							$theme['theme_mtime'] = $update_time;

							// Save CSS contents
							$sql_ary = array(
								'theme_mtime'	=> $theme['theme_mtime'],
								'theme_data'	=> $theme['theme_data']
							);

							$sql = 'UPDATE ' . STYLES_THEME_TABLE . ' SET ' . $db->sql_build_array('UPDATE', $sql_ary) . '
								WHERE theme_id = ' . $theme['theme_id'];
							$db->sql_query($sql);

							$cache->destroy('sql', STYLES_THEME_TABLE);
						}
					}

					$db->sql_return_on_error(true);
					$db->sql_query('DELETE FROM ' . CONFIG_TABLE . " WHERE config_name = 'version_update_from'");
					$db->sql_return_on_error(false);

					$cache->purge();
				}

			break;

			case 'update_files':

				$this->page_title = 'STAGE_UPDATE_FILES';

				$s_hidden_fields = '';
				$params = array();
				$conflicts = request_var('conflict', array('' => 0));
				$modified = request_var('modified', array('' => 0));

				foreach ($conflicts as $filename => $merge_option)
				{
					$s_hidden_fields .= '<input type="hidden" name="conflict[' . htmlspecialchars($filename) . ']" value="' . $merge_option . '" />';
					$params[] = 'conflict[' . urlencode($filename) . ']=' . urlencode($merge_option);
				}

				foreach ($modified as $filename => $merge_option)
				{
					if (!$merge_option)
					{
						continue;
					}
					$s_hidden_fields .= '<input type="hidden" name="modified[' . htmlspecialchars($filename) . ']" value="' . $merge_option . '" />';
					$params[] = 'modified[' . urlencode($filename) . ']=' . urlencode($merge_option);
				}

				$no_update = request_var('no_update', array(0 => ''));

				foreach ($no_update as $index => $filename)
				{
					$s_hidden_fields .= '<input type="hidden" name="no_update[]" value="' . htmlspecialchars($filename) . '" />';
					$params[] = 'no_update[]=' . urlencode($filename);
				}

				// Before the user is choosing his preferred method, let's create the content list...
				$update_list = $cache->get('_update_list');

				if ($update_list === false)
				{
					trigger_error($user->lang['NO_UPDATE_INFO'], E_USER_ERROR);
				}

				// Check if the conflicts data is valid
				if (sizeof($conflicts))
				{
					$conflict_filenames = array();
					foreach ($update_list['conflict'] as $files)
					{
						$conflict_filenames[] = $files['filename'];
					}

					$new_conflicts = array();
					foreach ($conflicts as $filename => $diff_method)
					{
						if (in_array($filename, $conflict_filenames))
						{
							$new_conflicts[$filename] = $diff_method;
						}
					}

					$conflicts = $new_conflicts;
				}

				// Build list for modifications
				if (sizeof($modified))
				{
					$modified_filenames = array();
					foreach ($update_list['modified'] as $files)
					{
						$modified_filenames[] = $files['filename'];
					}

					$new_modified = array();
					foreach ($modified as $filename => $diff_method)
					{
						if (in_array($filename, $modified_filenames))
						{
							$new_modified[$filename] = $diff_method;
						}
					}

					$modified = $new_modified;
				}

				// Check number of conflicting files, they need to be equal. For modified files the number can differ
				if (sizeof($update_list['conflict']) != sizeof($conflicts))
				{
					trigger_error($user->lang['MERGE_SELECT_ERROR'], E_USER_ERROR);
				}

				// Before we do anything, let us diff the files and store the raw file information "somewhere"
				$get_files = false;
				$file_list = $cache->get('_diff_files');

				if ($file_list === false || $file_list['status'] != -1)
				{
					$get_files = true;
				}

				if ($get_files)
				{
					if ($file_list === false)
					{
						$file_list = array(
							'status'	=> 0,
						);
					}

					$processed = 0;
					foreach ($update_list as $status => $files)
					{
						if (!is_array($files))
						{
							continue;
						}

						foreach ($files as $file_struct)
						{
							// Skip this file if the user selected to not update it
							if (in_array($file_struct['filename'], $no_update))
							{
								continue;
							}

							// Already handled... then skip of course...
							if (isset($file_list[$file_struct['filename']]))
							{
								continue;
							}

							// Refresh if we reach 5 diffs...
							if ($processed >= 5)
							{
								$cache->put('_diff_files', $file_list);

								if (!empty($_REQUEST['download']))
								{
									$params[] = 'download=1';
								}

								$redirect_url = append_sid($this->p_master->module_url, "mode=$mode&amp;sub=update_files&amp;" . implode('&amp;', $params));
								meta_refresh(3, $redirect_url);

								$template->assign_vars(array(
									'S_IN_PROGRESS'			=> true,
									'L_IN_PROGRESS'			=> $user->lang['MERGING_FILES'],
									'L_IN_PROGRESS_EXPLAIN'	=> $user->lang['MERGING_FILES_EXPLAIN'],
								));

								return;
							}

							$original_filename = ($file_struct['custom']) ? $file_struct['original'] : $file_struct['filename'];

							switch ($status)
							{
								case 'modified':

									$option = (isset($modified[$file_struct['filename']])) ? $modified[$file_struct['filename']] : 0;

									switch ($option)
									{
										case MERGE_NO_MERGE_NEW:
											$contents = file_get_contents($this->new_location . $original_filename);
										break;

										case MERGE_NO_MERGE_MOD:
											$contents = file_get_contents($phpbb_root_path . $file_struct['filename']);
										break;

										default:
											$diff = $this->return_diff($this->old_location . $original_filename, $phpbb_root_path . $file_struct['filename'], $this->new_location . $original_filename);

											$contents = implode("\n", $diff->merged_output());
											unset($diff);
										break;
									}

									$file_list[$file_struct['filename']] = '_file_' . md5($file_struct['filename']);
									$cache->put($file_list[$file_struct['filename']], base64_encode($contents));

									$file_list['status']++;
									$processed++;

								break;

								case 'conflict':

									$option = $conflicts[$file_struct['filename']];
									$contents = '';

									switch ($option)
									{
										case MERGE_NO_MERGE_NEW:
											$contents = file_get_contents($this->new_location . $original_filename);
										break;

										case MERGE_NO_MERGE_MOD:
											$contents = file_get_contents($phpbb_root_path . $file_struct['filename']);
										break;

										default:

											$diff = $this->return_diff($this->old_location . $original_filename, $phpbb_root_path . $file_struct['filename'], $this->new_location . $original_filename);

											if ($option == MERGE_NEW_FILE)
											{
												$contents = implode("\n", $diff->merged_new_output());
											}
											else if ($option == MERGE_MOD_FILE)
											{
												$contents = implode("\n", $diff->merged_orig_output());
											}
											else
											{
												unset($diff);
												break 2;
											}

											unset($diff);
										break;
									}

									$file_list[$file_struct['filename']] = '_file_' . md5($file_struct['filename']);
									$cache->put($file_list[$file_struct['filename']], base64_encode($contents));

									$file_list['status']++;
									$processed++;

								break;
							}
						}
					}
				}

				$file_list['status'] = -1;
				$cache->put('_diff_files', $file_list);

				if (!empty($_REQUEST['download']))
				{
					$this->include_file('includes/functions_compress.' . $phpEx);

					$use_method = request_var('use_method', '');
					$methods = array('.tar');

					$available_methods = array('.tar.gz' => 'zlib', '.tar.bz2' => 'bz2', '.zip' => 'zlib');
					foreach ($available_methods as $type => $module)
					{
						if (!@extension_loaded($module))
						{
							continue;
						}

						$methods[] = $type;
					}

					// Let the user decide in which format he wants to have the pack
					if (!$use_method)
					{
						$this->page_title = 'SELECT_DOWNLOAD_FORMAT';

						$radio_buttons = '';
						foreach ($methods as $method)
						{
							$radio_buttons .= '<label><input type="radio"' . ((!$radio_buttons) ? ' id="use_method"' : '') . ' class="radio" value="' . $method . '" name="use_method" /> ' . $method . '</label>';
						}

						$template->assign_vars(array(
							'S_DOWNLOAD_FILES'		=> true,
							'U_ACTION'				=> append_sid($this->p_master->module_url, "mode=$mode&amp;sub=update_files"),
							'RADIO_BUTTONS'			=> $radio_buttons,
							'S_HIDDEN_FIELDS'		=> $s_hidden_fields)
						);

						// To ease the update process create a file location map
						$update_list = $cache->get('_update_list');
						$script_path = ($config['force_server_vars']) ? (($config['script_path'] == '/') ? '/' : $config['script_path'] . '/') : $user->page['root_script_path'];

						foreach ($update_list as $status => $files)
						{
							if ($status == 'up_to_date' || $status == 'no_update' || $status == 'status')
							{
								continue;
							}

							foreach ($files as $file_struct)
							{
								if (in_array($file_struct['filename'], $no_update))
								{
									continue;
								}

								$template->assign_block_vars('location', array(
									'SOURCE'		=> htmlspecialchars($file_struct['filename']),
									'DESTINATION'	=> $script_path . htmlspecialchars($file_struct['filename']),
								));
							}
						}
						return;
					}

					if (!in_array($use_method, $methods))
					{
						$use_method = '.tar';
					}

					$update_mode = 'download';
				}
				else
				{
					$this->include_file('includes/functions_transfer.' . $phpEx);

					// Choose FTP, if not available use fsock...
					$method = basename(request_var('method', ''));
					$submit = (isset($_POST['submit'])) ? true : false;
					$test_ftp_connection = request_var('test_connection', '');

					if (!$method || !class_exists($method))
					{
						$method = 'ftp';
						$methods = transfer::methods();

						if (!in_array('ftp', $methods))
						{
							$method = $methods[0];
						}
					}

					$test_connection = false;
					if ($test_ftp_connection || $submit)
					{
						$transfer = new $method(request_var('host', ''), request_var('username', ''), request_var('password', ''), request_var('root_path', ''), request_var('port', ''), request_var('timeout', ''));
						$test_connection = $transfer->open_session();

						// Make sure that the directory is correct by checking for the existence of common.php
						if ($test_connection === true)
						{
							// Check for common.php file
							if (!$transfer->file_exists($phpbb_root_path, 'common.' . $phpEx))
							{
								$test_connection = 'ERR_WRONG_PATH_TO_PHPBB';
							}
						}

						$transfer->close_session();

						// Make sure the login details are correct before continuing
						if ($submit && $test_connection !== true)
						{
							$submit = false;
							$test_ftp_connection = true;
						}
					}

					$s_hidden_fields .= build_hidden_fields(array('method' => $method));

					if (!$submit)
					{
						$this->page_title = 'SELECT_FTP_SETTINGS';

						if (!class_exists($method))
						{
							trigger_error('Method does not exist.', E_USER_ERROR);
						}

						$requested_data = call_user_func(array($method, 'data'));
						foreach ($requested_data as $data => $default)
						{
							$template->assign_block_vars('data', array(
								'DATA'		=> $data,
								'NAME'		=> $user->lang[strtoupper($method . '_' . $data)],
								'EXPLAIN'	=> $user->lang[strtoupper($method . '_' . $data) . '_EXPLAIN'],
								'DEFAULT'	=> (!empty($_REQUEST[$data])) ? request_var($data, '') : $default
							));
						}

						$template->assign_vars(array(
							'S_CONNECTION_SUCCESS'		=> ($test_ftp_connection && $test_connection === true) ? true : false,
							'S_CONNECTION_FAILED'		=> ($test_ftp_connection && $test_connection !== true) ? true : false,
							'ERROR_MSG'					=> ($test_ftp_connection && $test_connection !== true) ? $user->lang[$test_connection] : '',

							'S_FTP_UPLOAD'		=> true,
							'UPLOAD_METHOD'		=> $method,
							'U_ACTION'			=> append_sid($this->p_master->module_url, "mode=$mode&amp;sub=update_files"),
							'U_DOWNLOAD_METHOD'	=> append_sid($this->p_master->module_url, "mode=$mode&amp;sub=update_files&amp;download=1"),
							'S_HIDDEN_FIELDS'	=> $s_hidden_fields,
						));

						return;
					}

					$update_mode = 'upload';
				}

				// Now update the installation or download the archive...
				$download_filename = 'update_' . $this->update_info['version']['from'] . '_to_' . $this->update_info['version']['to'];
				$archive_filename = $download_filename . '_' . time() . '_' . unique_id();

				// Now init the connection
				if ($update_mode == 'download')
				{
					if ($use_method == '.zip')
					{
						$compress = new compress_zip('w', $phpbb_root_path . 'store/' . $archive_filename . $use_method);
					}
					else
					{
						$compress = new compress_tar('w', $phpbb_root_path . 'store/' . $archive_filename . $use_method, $use_method);
					}
				}
				else
				{
					$transfer = new $method(request_var('host', ''), request_var('username', ''), request_var('password', ''), request_var('root_path', ''), request_var('port', ''), request_var('timeout', ''));
					$transfer->open_session();
				}

				// Ok, go through the update list and do the operations based on their status
				foreach ($update_list as $status => $files)
				{
					if (!is_array($files))
					{
						continue;
					}

					foreach ($files as $file_struct)
					{
						// Skip this file if the user selected to not update it
						if (in_array($file_struct['filename'], $no_update))
						{
							continue;
						}

						$original_filename = ($file_struct['custom']) ? $file_struct['original'] : $file_struct['filename'];

						switch ($status)
						{
							case 'new':
							case 'new_conflict':
							case 'not_modified':

								if ($update_mode == 'download')
								{
									$compress->add_custom_file($this->new_location . $original_filename, $file_struct['filename']);
								}
								else
								{
									if ($status != 'new')
									{
										$transfer->rename($file_struct['filename'], $file_struct['filename'] . '.bak');
									}

									// New directory too?
									$dirname = dirname($file_struct['filename']);

									if ($dirname && !file_exists($phpbb_root_path . $dirname))
									{
										$transfer->make_dir($dirname);
									}

									$transfer->copy_file($this->new_location . $original_filename, $file_struct['filename']);
								}
							break;

							case 'modified':

								$contents = base64_decode($cache->get($file_list[$file_struct['filename']]));

								if ($update_mode == 'download')
								{
									$compress->add_data($contents, $file_struct['filename']);
								}
								else
								{
									// @todo add option to specify if a backup file should be created?
									$transfer->rename($file_struct['filename'], $file_struct['filename'] . '.bak');
									$transfer->write_file($file_struct['filename'], $contents);
								}
							break;

							case 'conflict':

								$contents = base64_decode($cache->get($file_list[$file_struct['filename']]));

								if ($update_mode == 'download')
								{
									$compress->add_data($contents, $file_struct['filename']);
								}
								else
								{
									$transfer->rename($file_struct['filename'], $file_struct['filename'] . '.bak');
									$transfer->write_file($file_struct['filename'], $contents);
								}
							break;
						}
					}
				}

				if ($update_mode == 'download')
				{
					$compress->close();

					$compress->download($archive_filename, $download_filename);
					@unlink($phpbb_root_path . 'store/' . $archive_filename . $use_method);

					exit;
				}
				else
				{
					$transfer->close_session();

					$template->assign_vars(array(
						'S_UPLOAD_SUCCESS'	=> true,
						'U_ACTION'			=> append_sid($this->p_master->module_url, "mode=$mode&amp;sub=file_check"))
					);
					return;
				}

			break;

		}
	}
Exemplo n.º 4
0
 function main($mode, $sub)
 {
     global $template, $phpEx, $phpbb_root_path, $user, $db, $config, $cache, $auth, $language;
     global $request, $phpbb_admin_path, $phpbb_adm_relative_path, $phpbb_container, $phpbb_config_php_file;
     // We must enable super globals, otherwise creating a new instance of the request class,
     // using the new container with a dbal connection will fail with the following PHP Notice:
     // Object of class phpbb_request_deactivated_super_global could not be converted to int
     $request->enable_super_globals();
     // Create a normal container now
     $phpbb_container_builder = new \phpbb\di\container_builder($phpbb_config_php_file, $phpbb_root_path, $phpEx);
     $phpbb_container_builder->set_dump_container(false);
     $phpbb_container_builder->set_use_extensions(false);
     if (file_exists($phpbb_root_path . 'install/update/new/config')) {
         $phpbb_container_builder->set_config_path($phpbb_root_path . 'install/update/new/config');
     }
     $phpbb_container = $phpbb_container_builder->get_container();
     // Writes into global $cache
     $cache = $phpbb_container->get('cache');
     $this->tpl_name = 'install_update';
     $this->page_title = 'UPDATE_INSTALLATION';
     $this->old_location = $phpbb_root_path . 'install/update/old/';
     $this->new_location = $phpbb_root_path . 'install/update/new/';
     // Init DB
     extract($phpbb_config_php_file->get_all());
     require $phpbb_root_path . 'includes/constants.' . $phpEx;
     // Special options for conflicts/modified files
     define('MERGE_NO_MERGE_NEW', 1);
     define('MERGE_NO_MERGE_MOD', 2);
     define('MERGE_NEW_FILE', 3);
     define('MERGE_MOD_FILE', 4);
     $dbms = $phpbb_config_php_file->convert_30_dbms_to_31($dbms);
     $db = new $dbms();
     // Connect to DB
     $db->sql_connect($dbhost, $dbuser, $dbpasswd, $dbname, $dbport, false, false);
     // We do not need this any longer, unset for safety purposes
     unset($dbpasswd);
     // We need to fill the config to let internal functions correctly work
     $config = new \phpbb\config\db($db, new \phpbb\cache\driver\null(), CONFIG_TABLE);
     set_config(null, null, null, $config);
     set_config_count(null, null, null, $config);
     // Force template recompile
     $config['load_tplcompile'] = 1;
     // First of all, init the user session
     $user->session_begin();
     $auth->acl($user->data);
     // Overwrite user's language with the selected one.
     // Config needs to be changed to ensure that guests also get the selected language.
     $config_default_lang = $config['default_lang'];
     $config['default_lang'] = $language;
     $user->data['user_lang'] = $language;
     $user->add_lang(array('common', 'acp/common', 'acp/board', 'install', 'posting'));
     // Reset the default_lang
     $config['default_lang'] = $config_default_lang;
     unset($config_default_lang);
     // If we are within the intro page we need to make sure we get up-to-date version info
     if ($sub == 'intro') {
         $cache->destroy('_version_info');
     }
     // Set custom template again. ;)
     $paths = array($phpbb_root_path . 'install/update/new/adm/style', $phpbb_admin_path . 'style');
     $paths = array_filter($paths, 'is_dir');
     $template->set_custom_style(array(array('name' => 'adm', 'ext_path' => 'adm/style/')), $paths);
     $template->assign_vars(array('S_USER_LANG' => $user->lang['USER_LANG'], 'S_CONTENT_DIRECTION' => $user->lang['DIRECTION'], 'S_CONTENT_ENCODING' => 'UTF-8', 'S_CONTENT_FLOW_BEGIN' => $user->lang['DIRECTION'] == 'ltr' ? 'left' : 'right', 'S_CONTENT_FLOW_END' => $user->lang['DIRECTION'] == 'ltr' ? 'right' : 'left'));
     // Get current and latest version
     $version_helper = $phpbb_container->get('version_helper');
     try {
         $this->latest_version = $version_helper->get_latest_on_current_branch(true);
     } catch (\RuntimeException $e) {
         $this->latest_version = false;
         $update_info = array();
         include $phpbb_root_path . 'install/update/index.' . $phpEx;
         $info = empty($update_info) || !is_array($update_info) ? false : $update_info;
         if ($info !== false) {
             $this->latest_version = !empty($info['version']['to']) ? trim($info['version']['to']) : false;
         }
     }
     // For the current version we trick a bit. ;)
     $this->current_version = !empty($config['version_update_from']) ? $config['version_update_from'] : $config['version'];
     $up_to_date = version_compare(str_replace('rc', 'RC', strtolower($this->current_version)), str_replace('rc', 'RC', strtolower($this->latest_version)), '<') ? false : true;
     // Check for a valid update directory, else point the user to the phpbb.com website
     if (!file_exists($phpbb_root_path . 'install/update') || !file_exists($phpbb_root_path . 'install/update/index.' . $phpEx) || !file_exists($this->old_location) || !file_exists($this->new_location)) {
         $template->assign_vars(array('S_ERROR' => true, 'ERROR_MSG' => $up_to_date ? $user->lang['NO_UPDATE_FILES_UP_TO_DATE'] : sprintf($user->lang['NO_UPDATE_FILES_OUTDATED'], $config['version'], $this->current_version, $this->latest_version)));
         return;
     }
     $this->update_info = $this->get_file('update_info');
     // Make sure the update directory holds the correct information
     // Since admins are able to run the update/checks more than once we only check if the current version is lower or equal than the version to which we update to.
     if (version_compare(str_replace('rc', 'RC', strtolower($this->current_version)), str_replace('rc', 'RC', strtolower($this->update_info['version']['to'])), '>')) {
         $template->assign_vars(array('S_ERROR' => true, 'ERROR_MSG' => sprintf($user->lang['INCOMPATIBLE_UPDATE_FILES'], $config['version'], $this->update_info['version']['from'], $this->update_info['version']['to'])));
         return;
     }
     // Check if the update files are actually meant to update from the current version
     if ($this->current_version != $this->update_info['version']['from']) {
         $template->assign_vars(array('S_ERROR' => true, 'ERROR_MSG' => sprintf($user->lang['INCOMPATIBLE_UPDATE_FILES'], $this->current_version, $this->update_info['version']['from'], $this->update_info['version']['to'])));
     }
     // Check if the update files stored are for the latest version...
     if (version_compare(strtolower($this->latest_version), strtolower($this->update_info['version']['to']), '>')) {
         $template->assign_vars(array('S_WARNING' => true, 'WARNING_MSG' => sprintf($user->lang['OLD_UPDATE_FILES'], $this->update_info['version']['from'], $this->update_info['version']['to'], $this->latest_version)));
     }
     // We store the "update to" version, because it is not always the latest. ;)
     $this->update_to_version = $this->update_info['version']['to'];
     // Fill DB version
     if (empty($config['dbms_version'])) {
         set_config('dbms_version', $db->sql_server_info(true));
     }
     if ($this->test_update === false) {
         // What about the language file? Got it updated?
         if (in_array('language/' . $language . '/install.' . $phpEx, $this->update_info['files'])) {
             $lang = array();
             include $this->new_location . 'language/' . $language . '/install.' . $phpEx;
             // this is the user's language.. just merge it
             $user->lang = array_merge($user->lang, $lang);
         }
         if ($language != 'en' && in_array('language/en/install.' . $phpEx, $this->update_info['files'])) {
             $lang = array();
             include $this->new_location . 'language/en/install.' . $phpEx;
             // only add new keys to user's language in english
             $new_keys = array_diff(array_keys($lang), array_keys($user->lang));
             foreach ($new_keys as $i => $new_key) {
                 $user->lang[$new_key] = $lang[$new_key];
             }
         }
     }
     // Include renderer and engine
     $this->include_file('includes/diff/diff.' . $phpEx);
     $this->include_file('includes/diff/engine.' . $phpEx);
     $this->include_file('includes/diff/renderer.' . $phpEx);
     // Make sure we stay at the file check if checking the files again
     if ($request->variable('check_again', false, false, \phpbb\request\request_interface::POST)) {
         $sub = $this->p_master->sub = 'file_check';
     }
     switch ($sub) {
         case 'intro':
             $this->page_title = 'UPDATE_INSTALLATION';
             $template->assign_vars(array('S_INTRO' => true, 'U_ACTION' => append_sid($this->p_master->module_url, "language={$language}&amp;mode={$mode}&amp;sub=version_check")));
             // Make sure the update list is destroyed.
             $cache->destroy('_update_list');
             $cache->destroy('_diff_files');
             $cache->destroy('_expected_files');
             break;
         case 'version_check':
             $this->page_title = 'STAGE_VERSION_CHECK';
             $template->assign_vars(array('S_VERSION_CHECK' => true, 'U_ACTION' => append_sid($this->p_master->module_url, "language={$language}&amp;mode={$mode}&amp;sub=file_check"), 'S_UP_TO_DATE' => $up_to_date, 'LATEST_VERSION' => $this->latest_version, 'CURRENT_VERSION' => $this->current_version));
             // Print out version the update package updates to
             if ($this->latest_version != $this->update_info['version']['to']) {
                 $template->assign_var('PACKAGE_VERSION', $this->update_info['version']['to']);
             }
             // Since some people try to update to RC releases, but phpBB.com tells them the last version is the version they currently run
             // we are faced with the updater thinking the database schema is up-to-date; which it is, but should be updated none-the-less
             // We now try to cope with this by triggering the update process
             if (version_compare(str_replace('rc', 'RC', strtolower($this->current_version)), str_replace('rc', 'RC', strtolower($this->update_info['version']['to'])), '<')) {
                 $template->assign_vars(array('S_UP_TO_DATE' => false));
             }
             break;
         case 'update_db':
             // Redirect the user to the database update script with some explanations...
             $template->assign_vars(array('S_DB_UPDATE' => true, 'S_DB_UPDATE_FINISHED' => $config['version'] == $this->update_info['version']['to'] ? true : false, 'U_DB_UPDATE' => append_sid($phpbb_root_path . 'install/database_update.' . $phpEx, 'type=1&amp;language=' . $user->data['user_lang']), 'U_DB_UPDATE_ACTION' => append_sid($this->p_master->module_url, "language={$language}&amp;mode={$mode}&amp;sub=update_db"), 'U_ACTION' => append_sid($this->p_master->module_url, "language={$language}&amp;mode={$mode}&amp;sub=file_check"), 'L_EVERYTHING_UP_TO_DATE' => $user->lang('EVERYTHING_UP_TO_DATE', append_sid("{$phpbb_root_path}ucp.{$phpEx}", 'mode=login'), append_sid("{$phpbb_root_path}ucp.{$phpEx}", 'mode=login&amp;redirect=' . $phpbb_adm_relative_path . 'index.php%3Fi=send_statistics%26mode=send_statistics'))));
             // Do not display incompatible package note after successful update
             if ($config['version'] == $this->update_info['version']['to']) {
                 $template->assign_var('S_ERROR', false);
             }
             break;
         case 'file_check':
             // retrieve info on what changes should have already been made to the files.
             $expected_files = $cache->get('_expected_files');
             if (!$expected_files) {
                 $expected_files = array();
             }
             // Now make sure the previous file collection is no longer valid...
             $cache->destroy('_diff_files');
             $this->page_title = 'STAGE_FILE_CHECK';
             // Now make sure our update list is correct if the admin refreshes
             $action = request_var('action', '');
             // We are directly within an update. To make sure our update list is correct we check its status.
             $update_list = $request->variable('check_again', false, false, \phpbb\request\request_interface::POST) ? false : $cache->get('_update_list');
             $modified = $update_list !== false ? @filemtime($cache->get_driver()->cache_dir . 'data_update_list.' . $phpEx) : 0;
             // Make sure the list is up-to-date
             if ($update_list !== false) {
                 $get_new_list = false;
                 foreach ($this->update_info['files'] as $file) {
                     if (file_exists($phpbb_root_path . $file) && filemtime($phpbb_root_path . $file) > $modified) {
                         $get_new_list = true;
                         break;
                     }
                 }
             } else {
                 $get_new_list = true;
             }
             if (!$get_new_list && $update_list['status'] != -1) {
                 $get_new_list = true;
             }
             if ($get_new_list) {
                 $this->get_update_structure($update_list, $expected_files);
                 $cache->put('_update_list', $update_list);
                 // Refresh the page if we are still not finished...
                 if ($update_list['status'] != -1) {
                     $refresh_url = append_sid($this->p_master->module_url, "language={$language}&amp;mode={$mode}&amp;sub=file_check");
                     meta_refresh(2, $refresh_url);
                     $template->assign_vars(array('S_IN_PROGRESS' => true, 'S_COLLECTED' => (int) $update_list['status'], 'S_TO_COLLECT' => sizeof($this->update_info['files']), 'L_IN_PROGRESS' => $user->lang['COLLECTING_FILE_DIFFS'], 'L_IN_PROGRESS_EXPLAIN' => sprintf($user->lang['NUMBER_OF_FILES_COLLECTED'], (int) $update_list['status'], sizeof($this->update_info['files']) + sizeof($this->update_info['deleted']))));
                     return;
                 }
             }
             if ($action == 'diff') {
                 $this->show_diff($update_list);
                 return;
             }
             if (sizeof($update_list['no_update'])) {
                 $template->assign_vars(array('S_NO_UPDATE_FILES' => true, 'NO_UPDATE_FILES' => implode(', ', array_map('htmlspecialchars', $update_list['no_update']))));
             }
             $new_expected_files = array();
             // Now assign the list to the template
             foreach ($update_list as $status => $filelist) {
                 if ($status == 'no_update' || !sizeof($filelist) || $status == 'status' || $status == 'status_deleted') {
                     continue;
                 }
                 /*					$template->assign_block_vars('files', array(
                 						'S_STATUS'		=> true,
                 						'STATUS'		=> $status,
                 						'L_STATUS'		=> $user->lang['STATUS_' . strtoupper($status)],
                 						'TITLE'			=> $user->lang['FILES_' . strtoupper($status)],
                 						'EXPLAIN'		=> $user->lang['FILES_' . strtoupper($status) . '_EXPLAIN'],
                 						)
                 					);*/
                 foreach ($filelist as $file_struct) {
                     $s_binary = !empty($this->update_info['binary']) && in_array($file_struct['filename'], $this->update_info['binary']) ? true : false;
                     $filename = htmlspecialchars($file_struct['filename']);
                     if (strrpos($filename, '/') !== false) {
                         $dir_part = substr($filename, 0, strrpos($filename, '/') + 1);
                         $file_part = substr($filename, strrpos($filename, '/') + 1);
                     } else {
                         $dir_part = '';
                         $file_part = $filename;
                     }
                     $diff_url = append_sid($this->p_master->module_url, "language={$language}&amp;mode={$mode}&amp;sub=file_check&amp;action=diff&amp;status={$status}&amp;file=" . urlencode($file_struct['filename']));
                     if (isset($file_struct['as_expected']) && $file_struct['as_expected']) {
                         $new_expected_files[$file_struct['filename']] = $expected_files[$file_struct['filename']];
                     } else {
                         $template->assign_block_vars($status, array('STATUS' => $status, 'FILENAME' => $filename, 'DIR_PART' => $dir_part, 'FILE_PART' => $file_part, 'NUM_CONFLICTS' => isset($file_struct['conflicts']) ? $file_struct['conflicts'] : 0, 'S_CUSTOM' => $file_struct['custom'] ? true : false, 'S_BINARY' => $s_binary, 'CUSTOM_ORIGINAL' => $file_struct['custom'] ? $file_struct['original'] : '', 'U_SHOW_DIFF' => $diff_url, 'L_SHOW_DIFF' => $status != 'up_to_date' ? $user->lang['SHOW_DIFF_' . strtoupper($status)] : '', 'U_VIEW_MOD_FILE' => $diff_url . '&amp;op=' . MERGE_MOD_FILE, 'U_VIEW_NEW_FILE' => $diff_url . '&amp;op=' . MERGE_NEW_FILE, 'U_VIEW_NO_MERGE_MOD' => $diff_url . '&amp;op=' . MERGE_NO_MERGE_MOD, 'U_VIEW_NO_MERGE_NEW' => $diff_url . '&amp;op=' . MERGE_NO_MERGE_NEW));
                     }
                 }
             }
             $cache->put('_expected_files', $new_expected_files);
             $all_up_to_date = true;
             foreach ($update_list as $status => $filelist) {
                 if ($status != 'up_to_date' && $status != 'custom' && $status != 'status' && $status != 'status_deleted' && sizeof($filelist)) {
                     $all_up_to_date = false;
                     break;
                 }
             }
             $template->assign_vars(array('S_FILE_CHECK' => true, 'S_ALL_UP_TO_DATE' => $all_up_to_date, 'S_VERSION_UP_TO_DATE' => $up_to_date, 'S_UP_TO_DATE' => $up_to_date, 'U_ACTION' => append_sid($this->p_master->module_url, "language={$language}&amp;mode={$mode}&amp;sub=file_check"), 'U_UPDATE_ACTION' => append_sid($this->p_master->module_url, "language={$language}&amp;mode={$mode}&amp;sub=update_files"), 'U_DB_UPDATE_ACTION' => append_sid($this->p_master->module_url, "language={$language}&amp;mode={$mode}&amp;sub=update_db")));
             // Since some people try to update to RC releases, but phpBB.com tells them the last version is the version they currently run
             // we are faced with the updater thinking the database schema is up-to-date; which it is, but should be updated none-the-less
             // We now try to cope with this by triggering the update process
             if (version_compare(str_replace('rc', 'RC', strtolower($this->current_version)), str_replace('rc', 'RC', strtolower($this->update_info['version']['to'])), '<')) {
                 $template->assign_vars(array('S_UP_TO_DATE' => false));
             }
             if ($all_up_to_date) {
                 global $phpbb_container;
                 $phpbb_log = $phpbb_container->get('log');
                 // Add database update to log
                 $phpbb_log->add('admin', $user->data['user_id'], $user->ip, 'LOG_UPDATE_PHPBB', time(), array($this->current_version, $this->update_to_version));
                 $db->sql_return_on_error(true);
                 $db->sql_query('DELETE FROM ' . CONFIG_TABLE . " WHERE config_name = 'version_update_from'");
                 $db->sql_return_on_error(false);
                 $cache->purge();
             }
             break;
         case 'update_files':
             $this->page_title = 'STAGE_UPDATE_FILES';
             $s_hidden_fields = '';
             $params = array();
             $conflicts = request_var('conflict', array('' => 0));
             $modified = request_var('modified', array('' => 0));
             foreach ($conflicts as $filename => $merge_option) {
                 $s_hidden_fields .= '<input type="hidden" name="conflict[' . htmlspecialchars($filename) . ']" value="' . $merge_option . '" />';
                 $params[] = 'conflict[' . urlencode($filename) . ']=' . urlencode($merge_option);
             }
             foreach ($modified as $filename => $merge_option) {
                 if (!$merge_option) {
                     continue;
                 }
                 $s_hidden_fields .= '<input type="hidden" name="modified[' . htmlspecialchars($filename) . ']" value="' . $merge_option . '" />';
                 $params[] = 'modified[' . urlencode($filename) . ']=' . urlencode($merge_option);
             }
             $no_update = request_var('no_update', array(0 => ''));
             foreach ($no_update as $index => $filename) {
                 $s_hidden_fields .= '<input type="hidden" name="no_update[]" value="' . htmlspecialchars($filename) . '" />';
                 $params[] = 'no_update[]=' . urlencode($filename);
             }
             // Before the user is choosing his preferred method, let's create the content list...
             $update_list = $cache->get('_update_list');
             if ($update_list === false) {
                 trigger_error($user->lang['NO_UPDATE_INFO'], E_USER_ERROR);
             }
             // Check if the conflicts data is valid
             if (sizeof($conflicts)) {
                 $conflict_filenames = array();
                 foreach ($update_list['conflict'] as $files) {
                     $conflict_filenames[] = $files['filename'];
                 }
                 $new_conflicts = array();
                 foreach ($conflicts as $filename => $diff_method) {
                     if (in_array($filename, $conflict_filenames)) {
                         $new_conflicts[$filename] = $diff_method;
                     }
                 }
                 $conflicts = $new_conflicts;
             }
             // Build list for modifications
             if (sizeof($modified)) {
                 $modified_filenames = array();
                 foreach ($update_list['modified'] as $files) {
                     $modified_filenames[] = $files['filename'];
                 }
                 $new_modified = array();
                 foreach ($modified as $filename => $diff_method) {
                     if (in_array($filename, $modified_filenames)) {
                         $new_modified[$filename] = $diff_method;
                     }
                 }
                 $modified = $new_modified;
             }
             // Check number of conflicting files, they need to be equal. For modified files the number can differ
             if (sizeof($update_list['conflict']) != sizeof($conflicts)) {
                 trigger_error($user->lang['MERGE_SELECT_ERROR'], E_USER_ERROR);
             }
             // Before we do anything, let us diff the files and store the raw file information "somewhere"
             $get_files = false;
             $file_list = $cache->get('_diff_files');
             $expected_files = $cache->get('_expected_files');
             if ($file_list === false || $file_list['status'] != -1) {
                 $get_files = true;
             }
             if ($get_files) {
                 if ($file_list === false) {
                     $file_list = array('status' => 0);
                 }
                 if (!isset($expected_files) || $expected_files === false) {
                     $expected_files = array();
                 }
                 $processed = 0;
                 foreach ($update_list as $status => $files) {
                     if (!is_array($files)) {
                         continue;
                     }
                     foreach ($files as $file_struct) {
                         // Skip this file if the user selected to not update it
                         if (in_array($file_struct['filename'], $no_update)) {
                             $expected_files[$file_struct['filename']] = false;
                             continue;
                         }
                         // Already handled... then skip of course...
                         if (isset($file_list[$file_struct['filename']])) {
                             continue;
                         }
                         // Refresh if we reach 5 diffs...
                         if ($processed >= 5) {
                             $cache->put('_diff_files', $file_list);
                             if ($request->variable('download', false)) {
                                 $params[] = 'download=1';
                             }
                             $redirect_url = append_sid($this->p_master->module_url, "language={$language}&amp;mode={$mode}&amp;sub=update_files&amp;" . implode('&amp;', $params));
                             meta_refresh(3, $redirect_url);
                             $template->assign_vars(array('S_IN_PROGRESS' => true, 'L_IN_PROGRESS' => $user->lang['MERGING_FILES'], 'L_IN_PROGRESS_EXPLAIN' => $user->lang['MERGING_FILES_EXPLAIN']));
                             return;
                         }
                         if (file_exists($phpbb_root_path . $file_struct['filename'])) {
                             $contents = file_get_contents($phpbb_root_path . $file_struct['filename']);
                             if (isset($expected_files[$file_struct['filename']]) && md5($contents) == $expected_files[$file_struct['filename']]) {
                                 continue;
                             }
                         }
                         $original_filename = $file_struct['custom'] ? $file_struct['original'] : $file_struct['filename'];
                         switch ($status) {
                             case 'modified':
                                 $option = isset($modified[$file_struct['filename']]) ? $modified[$file_struct['filename']] : 0;
                                 switch ($option) {
                                     case MERGE_NO_MERGE_NEW:
                                         $contents = file_get_contents($this->new_location . $original_filename);
                                         break;
                                     case MERGE_NO_MERGE_MOD:
                                         $contents = file_get_contents($phpbb_root_path . $file_struct['filename']);
                                         break;
                                     default:
                                         $diff = $this->return_diff($this->old_location . $original_filename, $phpbb_root_path . $file_struct['filename'], $this->new_location . $original_filename);
                                         $contents = implode("\n", $diff->merged_output());
                                         unset($diff);
                                         break;
                                 }
                                 $expected_files[$file_struct['filename']] = md5($contents);
                                 $file_list[$file_struct['filename']] = '_file_' . md5($file_struct['filename']);
                                 $cache->put($file_list[$file_struct['filename']], base64_encode($contents));
                                 $file_list['status']++;
                                 $processed++;
                                 break;
                             case 'conflict':
                                 $option = $conflicts[$file_struct['filename']];
                                 $contents = '';
                                 switch ($option) {
                                     case MERGE_NO_MERGE_NEW:
                                         $contents = file_get_contents($this->new_location . $original_filename);
                                         break;
                                     case MERGE_NO_MERGE_MOD:
                                         $contents = file_get_contents($phpbb_root_path . $file_struct['filename']);
                                         break;
                                     default:
                                         $diff = $this->return_diff($this->old_location . $original_filename, $phpbb_root_path . $file_struct['filename'], $this->new_location . $original_filename);
                                         if ($option == MERGE_NEW_FILE) {
                                             $contents = implode("\n", $diff->merged_new_output());
                                         } else {
                                             if ($option == MERGE_MOD_FILE) {
                                                 $contents = implode("\n", $diff->merged_orig_output());
                                             } else {
                                                 unset($diff);
                                                 break 2;
                                             }
                                         }
                                         unset($diff);
                                         break;
                                 }
                                 $expected_files[$file_struct['filename']] = md5($contents);
                                 $file_list[$file_struct['filename']] = '_file_' . md5($file_struct['filename']);
                                 $cache->put($file_list[$file_struct['filename']], base64_encode($contents));
                                 $file_list['status']++;
                                 $processed++;
                                 break;
                         }
                     }
                 }
                 $cache->put('_expected_files', $expected_files);
             }
             $file_list['status'] = -1;
             $cache->put('_diff_files', $file_list);
             if ($request->variable('download', false)) {
                 $this->include_file('includes/functions_compress.' . $phpEx);
                 $use_method = request_var('use_method', '');
                 $methods = array('.tar');
                 $available_methods = array('.tar.gz' => 'zlib', '.tar.bz2' => 'bz2', '.zip' => 'zlib');
                 foreach ($available_methods as $type => $module) {
                     if (!@extension_loaded($module)) {
                         continue;
                     }
                     $methods[] = $type;
                 }
                 // Let the user decide in which format he wants to have the pack
                 if (!$use_method) {
                     $this->page_title = 'SELECT_DOWNLOAD_FORMAT';
                     $radio_buttons = '';
                     foreach ($methods as $method) {
                         $radio_buttons .= '<label><input type="radio"' . (!$radio_buttons ? ' id="use_method"' : '') . ' class="radio" value="' . $method . '" name="use_method" /> ' . $method . '</label>';
                     }
                     $template->assign_vars(array('S_DOWNLOAD_FILES' => true, 'U_ACTION' => append_sid($this->p_master->module_url, "language={$language}&amp;mode={$mode}&amp;sub=update_files"), 'RADIO_BUTTONS' => $radio_buttons, 'S_HIDDEN_FIELDS' => $s_hidden_fields));
                     // To ease the update process create a file location map
                     $update_list = $cache->get('_update_list');
                     $script_path = $config['force_server_vars'] ? $config['script_path'] == '/' ? '/' : $config['script_path'] . '/' : $user->page['root_script_path'];
                     foreach ($update_list as $status => $files) {
                         if ($status == 'up_to_date' || $status == 'no_update' || $status == 'status' || $status == 'status_deleted') {
                             continue;
                         }
                         foreach ($files as $file_struct) {
                             if (in_array($file_struct['filename'], $no_update)) {
                                 continue;
                             }
                             $template->assign_block_vars('location', array('SOURCE' => htmlspecialchars($file_struct['filename']), 'DESTINATION' => $script_path . htmlspecialchars($file_struct['filename'])));
                         }
                     }
                     return;
                 }
                 if (!in_array($use_method, $methods)) {
                     $use_method = '.tar';
                 }
                 $update_mode = 'download';
             } else {
                 $this->include_file('includes/functions_transfer.' . $phpEx);
                 // Choose FTP, if not available use fsock...
                 $method = basename(request_var('method', ''));
                 $submit = isset($_POST['submit']) ? true : false;
                 $test_ftp_connection = request_var('test_connection', '');
                 if (!$method || !class_exists($method)) {
                     $method = 'ftp';
                     $methods = transfer::methods();
                     if (!in_array('ftp', $methods)) {
                         $method = $methods[0];
                     }
                 }
                 $test_connection = false;
                 if ($test_ftp_connection || $submit) {
                     $transfer = new $method(request_var('host', ''), request_var('username', ''), htmlspecialchars_decode($request->untrimmed_variable('password', '')), request_var('root_path', ''), request_var('port', ''), request_var('timeout', ''));
                     $test_connection = $transfer->open_session();
                     // Make sure that the directory is correct by checking for the existence of common.php
                     if ($test_connection === true) {
                         // Check for common.php file
                         if (!$transfer->file_exists($phpbb_root_path, 'common.' . $phpEx)) {
                             $test_connection = 'ERR_WRONG_PATH_TO_PHPBB';
                         }
                     }
                     $transfer->close_session();
                     // Make sure the login details are correct before continuing
                     if ($submit && $test_connection !== true) {
                         $submit = false;
                         $test_ftp_connection = true;
                     }
                 }
                 $s_hidden_fields .= build_hidden_fields(array('method' => $method));
                 if (!$submit) {
                     $this->page_title = 'SELECT_FTP_SETTINGS';
                     if (!class_exists($method)) {
                         trigger_error('Method does not exist.', E_USER_ERROR);
                     }
                     $requested_data = call_user_func(array($method, 'data'));
                     foreach ($requested_data as $data => $default) {
                         $template->assign_block_vars('data', array('DATA' => $data, 'NAME' => $user->lang[strtoupper($method . '_' . $data)], 'EXPLAIN' => $user->lang[strtoupper($method . '_' . $data) . '_EXPLAIN'], 'DEFAULT' => $request->variable($data, (string) $default)));
                     }
                     $template->assign_vars(array('S_CONNECTION_SUCCESS' => $test_ftp_connection && $test_connection === true ? true : false, 'S_CONNECTION_FAILED' => $test_ftp_connection && $test_connection !== true ? true : false, 'ERROR_MSG' => $test_ftp_connection && $test_connection !== true ? $user->lang[$test_connection] : '', 'S_FTP_UPLOAD' => true, 'UPLOAD_METHOD' => $method, 'U_ACTION' => append_sid($this->p_master->module_url, "language={$language}&amp;mode={$mode}&amp;sub=update_files"), 'U_DOWNLOAD_METHOD' => append_sid($this->p_master->module_url, "language={$language}&amp;mode={$mode}&amp;sub=update_files&amp;download=1"), 'S_HIDDEN_FIELDS' => $s_hidden_fields));
                     return;
                 }
                 $update_mode = 'upload';
             }
             // Now update the installation or download the archive...
             $download_filename = 'update_' . $this->update_info['version']['from'] . '_to_' . $this->update_info['version']['to'];
             $archive_filename = $download_filename . '_' . time() . '_' . unique_id();
             // Now init the connection
             if ($update_mode == 'download') {
                 if (function_exists('phpbb_is_writable') && !phpbb_is_writable($phpbb_root_path . 'store/')) {
                     trigger_error(sprintf('The directory “%s” is not writable.', $phpbb_root_path . 'store/'), E_USER_ERROR);
                 }
                 if ($use_method == '.zip') {
                     $compress = new compress_zip('w', $phpbb_root_path . 'store/' . $archive_filename . $use_method);
                 } else {
                     $compress = new compress_tar('w', $phpbb_root_path . 'store/' . $archive_filename . $use_method, $use_method);
                 }
             } else {
                 $transfer = new $method(request_var('host', ''), request_var('username', ''), htmlspecialchars_decode($request->untrimmed_variable('password', '')), request_var('root_path', ''), request_var('port', ''), request_var('timeout', ''));
                 $transfer->open_session();
             }
             // Ok, go through the update list and do the operations based on their status
             foreach ($update_list as $status => $files) {
                 if (!is_array($files)) {
                     continue;
                 }
                 foreach ($files as $file_struct) {
                     // Skip this file if the user selected to not update it
                     if (in_array($file_struct['filename'], $no_update)) {
                         continue;
                     }
                     $original_filename = $file_struct['custom'] ? $file_struct['original'] : $file_struct['filename'];
                     switch ($status) {
                         case 'new':
                         case 'new_conflict':
                         case 'not_modified':
                             if ($update_mode == 'download') {
                                 $compress->add_custom_file($this->new_location . $original_filename, $file_struct['filename']);
                             } else {
                                 if ($status != 'new') {
                                     $transfer->rename($file_struct['filename'], $file_struct['filename'] . '.bak');
                                 }
                                 // New directory too?
                                 $dirname = dirname($file_struct['filename']);
                                 if ($dirname && !file_exists($phpbb_root_path . $dirname)) {
                                     $transfer->make_dir($dirname);
                                 }
                                 $transfer->copy_file($this->new_location . $original_filename, $file_struct['filename']);
                             }
                             break;
                         case 'modified':
                             $contents = base64_decode($cache->get($file_list[$file_struct['filename']]));
                             if ($update_mode == 'download') {
                                 $compress->add_data($contents, $file_struct['filename']);
                             } else {
                                 // @todo add option to specify if a backup file should be created?
                                 $transfer->rename($file_struct['filename'], $file_struct['filename'] . '.bak');
                                 $transfer->write_file($file_struct['filename'], $contents);
                             }
                             break;
                         case 'conflict':
                             $contents = base64_decode($cache->get($file_list[$file_struct['filename']]));
                             if ($update_mode == 'download') {
                                 $compress->add_data($contents, $file_struct['filename']);
                             } else {
                                 $transfer->rename($file_struct['filename'], $file_struct['filename'] . '.bak');
                                 $transfer->write_file($file_struct['filename'], $contents);
                             }
                             break;
                         case 'deleted':
                             if ($update_mode != 'download') {
                                 $transfer->rename($file_struct['filename'], $file_struct['filename'] . '.bak');
                             }
                             break;
                     }
                 }
             }
             if ($update_mode == 'download') {
                 $compress->close();
                 $compress->download($archive_filename, $download_filename);
                 @unlink($phpbb_root_path . 'store/' . $archive_filename . $use_method);
                 exit;
             } else {
                 $transfer->close_session();
                 $template->assign_vars(array('S_UPLOAD_SUCCESS' => true, 'U_ACTION' => append_sid($this->p_master->module_url, "language={$language}&amp;mode={$mode}&amp;sub=file_check")));
                 return;
             }
             break;
     }
 }