#TITLE#
#CONTENT#
'package2.tar.gz', 'zip' => 'package2.zip', ); private $_paths = array( '6' => 'https://keitaro.io/updates/6.7.4/', '7' => 'https://keitaro.io/updates/7.5/' ); public function __construct() { if (isset($_POST['step'])){ $this->_step = $_POST['step']; } session_start(); } public function setTemplate($tpl) { $this->_template = $tpl; } private function _step1() { $this->_title = $this->t('step1.title'); $this->_content .= ''."\r\n"; $this->_content .= ''; $this->_content .= ''; $this->_content .= ''; $this->_content .= '
PHP:'.$this->_checkPhpVersion().'
IonCube Loader:'.$this->_checkIoncubeStatus().'
' . $this->t('step1.permissions') . ':'.$this->_checkDirStatus().'
'; if ($this->_stepStatus) { $this->_content .= '
'; $this->_content .= ''; $this->_content .= '
'; $this->_content .= '
'; $this->_content .= '
'; $this->_content .= '
' . $this->t('step1.warning') .'
'; $this->_footer .= ''."\r\n"; } else { $this->_footer .= '

' . $this->t('failure'). '.

'; $this->_footer .= ''."\r\n"; } } private function _checkIoncubeStatus() { $version = ioncube_loader_version(); if (version_compare(self::MIN_IONCUBE_VERSION, $version) >= 0) { return $this->_wrapError($version . ' — ' . $this->t('step1.min_version'). ''); } else { return $this->_wrapSuccess($version); } } private function _checkDirStatus() { if (!is_writeable('./')){ $this->_stepStatus = false; return $this->_wrapError($this->t('step1.dir_isnt_writable')); } else { return $this->_wrapSuccess($this->t('step1.dir_is_writable')); } } private function _checkPhpVersion() { if (version_compare(phpversion(), '5.4') > 0) { return $this->_wrapSuccess(phpversion()); } else { $this->_stepStatus = false; return $this->_wrapError( phpversion() . ' — ' . $this->t('step1.php_error')); } } private function _wrapSuccess($text) { return '
' . $text . '
'; } private function _wrapError($text) { return '
' . $text . '
'; } private function _stepUpgrade() { $this->_title = $this->t('upgrade.title'); $this->_downloadPackage(7); if ($this->_stepStatus) { $this->_content = $this->t('upgrade.content'); $this->_footer .= '' . $this->t('continue'). ''."\r\n"; } else { $this->_footer .= '

' . $this->t('failure'). '.

'; $this->_footer .= ''."\r\n"; } } private function _stepDowngrade() { $this->_title = $this->t('downgrade.title'); $this->_downloadPackage(6); $remove = array( 'lib/Keitaro/Json.php', 'application/redirects/AbstractRedirect.php', 'application/redirects/AbstractRedirect2.php', 'application/redirects/BaseRedirect.php', 'application/redirects/campaign.php', 'application/redirects/frame.php', 'application/redirects/http.php', 'application/redirects/stream.php', 'application/redirects/sub_id.php', 'application/macros/os.php', 'application/macros/AbstractMacros.php', 'application/macros/BaseMacros.php', 'application/macros/country_name.php', 'application/macros/country.php', 'application/macros/operator.php', 'application/macros/operator_name.php', 'application/macros/region.php', 'application/macros/region_name.php', 'application/macros/campaign_id.php', 'application/macros/random.php', ); foreach ($remove as $file) { if (file_exists($file)) { unlink($file); } } $this->_connect(); $sql = 'UPDATE ' . $this->_cnf['db']['prefix']. 'streams SET redirect_type = "group" WHERE redirect_type = "campaign"'; @mysql_query($sql); if ($this->_stepStatus) { $this->_content = $this->t('downgrade.content'); $this->_footer .= '' . $this->t('continue'). ''."\r\n"; } else { $this->_footer .= '

' . $this->t('failure'). '.

'; $this->_footer .= ''."\r\n"; } } private function _downloadPackage($version) { @set_time_limit(180); $package = $this->_findPackage($version); $localPackage = 'package.pack'; if (!file_exists($localPackage)) { if (!ini_get('allow_url_fopen')){ if (function_exists('curl_init')) { $ch = curl_init($package); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_TIMEOUT, 100); curl_setopt($ch, CURLOPT_BINARYTRANSFER, true); curl_setopt($ch, CURLOPT_HEADER, 0); $content = curl_exec($ch); if ($error = curl_error($ch)) { $this->_stepStatus = false; $this->_content .= '
Connection Error. Curl error: ' . $error . '
'; } curl_close($ch); if (!file_put_contents($localPackage, $content)){ $this->_stepStatus = false; $this->_content .= '
Permission Error
'; } } else { $this->_stepStatus = false; $this->_content .= '
Tools Error
'; } } else { file_put_contents($localPackage, fopen($package, 'rb')); } } if (file_exists($localPackage) && filesize($localPackage) > 0) { $this->_unpack($localPackage); if (file_exists('www/version.php')) { $this->_dirmv('www', './', true); } if (!file_exists('version.php')) { $this->_stepStatus = false; $this->_content .= '
Unpack Error
'; return; } $uid = fileowner(dirname(__FILE__)); $gid = filegroup(dirname(__FILE__)); $this->_chmod('var', 0777); $this->_chown('./', $uid, $gid); $this->_chown('www', $uid, $gid); @mkdir('var/cache', 0777); @chmod('var/cache', 0777); @mkdir('var/cron', 0777); @chmod('var/cron', 0777); @mkdir('var/exports', 0777); @mkdir('var/log', 0777); @mkdir('var/sessions', 0777); @chmod('application/config/config.ini', 0777); @chmod('application/config/menu.ini', 0777); @unlink($localPackage); $this->_rmdir('www'); } else { $this->_stepStatus = false; $this->_content .= '
Download Error
'; } } private function _unpack($localPackage) { if (class_exists('ZipArchive')) { $zip = new ZipArchive; $zip->open($localPackage); $zip->extractTo('./'); $zip->close(); } elseif (class_exists('PharData')) { @mkdir('www', 0777); try { $archive = new PharData($localPackage); $archive->extractTo('./', null, true); } catch (Exception $e) { $this->_stepStatus = false; $this->_content .= '
' . $e->getMessage() . '
'; } } else { $disabled = ini_get('disable_functions'); if (!strstr($disabled, 'system')) { system("tar -xzf " . $localPackage); } elseif (!strstr($disabled, 'exec')) { exec("tar -xzf " . $localPackage); } } if (!file_exists('www/version.php')) { $this->_stepStatus = false; $this->_content .= '
Unable to unpack. Please install php_zip.
'; } } private function _findPackage($version) { if (class_exists('ZipArchive')) { return $this->_paths[$version] . $this->_packages['zip']; } else { return $this->_paths[$version] . $this->_packages['tar']; } } private function _rmdir($path) { if (is_dir($path) AND !is_link($path)) { foreach ( scandir ($path) as $value ) { if ( $value != "." && $value != ".." ) { $value = $path . "/" . $value; if (is_dir($value)) { $this->_rmdir( $value ); } elseif (is_file( $value )) { unlink ( $value ); } } } return rmdir($path); } else { return false; } } private function _chmod($path, $attr = 0777) { $d = @opendir($path); if (!@is_dir($d) || is_link($d)) { return; } while(($file = readdir($d)) !== false) { if ($file != "." && $file != ".." && $file != $_SERVER['PHP_SELF']) { $typepath = $path . "/" . $file ; if (filetype ($typepath) == 'dir') { $this->_chmod($typepath, $attr); } @chmod($typepath, $attr); } } } private function _chown($path, $uid, $gid) { $d = @opendir ($path) ; if (!@is_dir($d) || is_link($d)) { return; } while(($file = readdir($d)) !== false) { if ($file != "." && $file != ".." && $file != $_SERVER['PHP_SELF']) { $typepath = $path . "/" . $file ; if (filetype ($typepath) == 'dir') { $this->_chown($typepath,$uid,$gid); } @chown($typepath, $uid); @chgrp($typepath, $gid); } } } private function _dirmv($source, $dest, $overwrite = false, $funcloc = NULL) { if (is_null($funcloc)){ $dest .= '/' . strrev(substr(strrev($source), 0, strpos(strrev($source), '/'))); $funcloc = '/'; } if (!is_dir($dest . $funcloc)) { @mkdir( $dest . $funcloc, 0755); } if ($handle = @opendir( $source . $funcloc)) { while(false !== ($file = readdir($handle))) { if($file != '.' && $file != '..') { $path = $source . $funcloc . $file; $path4 = $dest . $funcloc . $file; if(is_file( $path)) { if(!is_file( $path4)){ if(!@rename( $path, $path4)) { //echo 'File ('.$path.') could not be moved, likely a permissions problem.
'; } } elseif($overwrite){ if(!@unlink( $path4)){ //echo 'Unable to overwrite file ("'.$path4.'"), likely to be a permissions problem.
'; } elseif(!@rename( $path, $path4)) { //echo 'File ('.$path.') could not be moved while overwritting, likely a permissions problem.
'; } } } elseif(is_dir($path) AND !is_link($path)) { $this->_dirmv($source, $dest, $overwrite, $funcloc . $file . '/'); @rmdir($path); } } } closedir($handle); } } public function _unzip($archive, $file) { $sfp = gzopen($archive, "rb"); $fp = fopen($file, "w"); while ($string = gzread($sfp, 4096)) { fwrite($fp, $string, strlen($string)); } gzclose($sfp); fclose($fp); unlink($archive); } private function _initConfig() { $this->_cnf = parse_ini_file('application/config/config.ini', true); } private function _connect() { $this->_initConfig(); if ($res = @mysql_connect($this->_cnf['db']['server'], $this->_cnf['db']['user'], $this->_cnf['db']['password'])) { if (!@$this->_db = mysql_select_db($this->_cnf['db']['name'])) { $this->_stepStatus = false; $this->_content .= '
' . $this->t('step7.db_error') . ': ' . mysql_error($res) . '
'; } else { mysql_query("set character_set_client=utf8"); mysql_query("set character_set_connection=utf8"); mysql_query("set character_set_results=utf8"); mysql_query("set collation_connection=utf8_unicode_ci"); } } else { $this->_stepStatus = false; $this->_footer .= '
MySQL connection error
'; } } public function dispatch() { if (!session_id()) { session_start(); } $this->_checkLang(); $content = $this->_template; if (defined('CHECKER') && CHECKER) { $this->_step = 1; } $action = '_step'.$this->_step; if (method_exists($this, $action)){ $this->$action(); } else { $this->_title = 'Error'; $this->_content = 'Step not exists'; } $content = str_replace('#DOMAIN#', $this->_site, $content); $content = str_replace('#CONTENT#', $this->_content, $content); $content = str_replace('#FOOTER#', $this->_footer, $content); $content = str_replace('#STEP#', $this->_step, $content); $content = str_replace('#TITLE#', $this->_title, $content); $content = str_replace('#MAIN_TITLE#', $this->t('main_title'), $content); $content = str_replace('#DOCUMENTATION#', $this->t('documentation'), $content); $content = str_replace('#CURRENT_STEP#', (int) $this->_step, $content); $content = str_replace('#ANOTHER_LANG#', $this->_getAnotherLang(), $content); $content = str_replace('#CHANGE_LANG#', $this->_getChangeLangText(), $content); $content = str_replace('#WIKI#', $this->_getWikiDomain(), $content); echo $content; } public function t($key, $params = null) { return KLocale::get($key, $params); } private function _getWikiDomain() { if (KLocale::getPreferredLanguage() == 'ru') { return 'help.keitarotds.ru/keitaroupdate#как_обновиться_с_версии_6_на_версию_7'; } else { return 'help.keitarotds.com/keitaroupdate'; } } private function _getAnotherLang() { if (KLocale::getPreferredLanguage() == 'ru') { return 'en'; } else { return 'ru'; } } private function _getChangeLangText() { if (KLocale::getPreferredLanguage() == 'ru') { return 'RU → EN'; } else { return 'EN → RU'; } } private function _checkLang() { if (isset($_GET['lang'])) { KLocale::setPreferredLanguage($_GET['lang']); } } } class KLocale { protected static $_data = array( 'ru' => array( 'main_title' => 'Обновление Keitaro 7', 'step1' => array( 'title' => 'Проверка совместимости и выбор действия', 'php_error' => 'необходима версия 5.4 или выше', 'min_version' => 'Необходима версия 4.6 или выше', 'permissions' => 'Права записи на текущую директорию', 'dir_isnt_writable' => 'Не разрешено', 'dir_is_writable' => 'Разрешено', 'operation' => 'Действие', 'upgrade' => 'Обновление на версию 7', 'downgrade' => 'Откат на версию 6', 'warning' => '

ВНИМАНИЕ! Обязательно сделайте бекап текущей TDS и базы данных.

До завершения всех миграций в базе данных, TDS не будет принимать трафик. Поэтому рекомендуем остановить или куда-нибудь перенаправить трафик. Также, возможна потеря некоторых-то данных из статистики.

Успешность обновления сильно зависит от объемов базы данных. Максимально очистите статистику перед обновлением.

', ), 'upgrade' => array( 'title' => 'Обновление', 'content' => '

Обновление файлов завершено.

Удалите файл upgrader7.php

Затем авторизуйтесь в Keitaro, зайти на страницу "Обслуживание > Миграции" и запустить процесс миграции базы.

', ), 'downgrade' => array( 'title' => 'Откат', 'content' => '

Замена файлов завершена.

Пожалуйста, напишите нам на feedback@keitaro.io по какой причине вы вынуждены были сделать откат.

Не забудьте удалить файл upgrader7.php

', ), 'failure' => 'Обнаружена несовместимость', 'documentation' => 'Инструкция и решение проблем по обновлению на версию 7', 'do' => 'Выполнить', 'continue' => 'Продолжить', 'retry' => 'Повторить проверку' ), 'en' => array( 'main_title' => 'Keitaro 7 Update', 'step1' => array( 'title' => 'Compatibility check', 'php_error' => 'required version 5.4 or newer', 'min_version' => 'Required 4.6 or higher', 'permissions' => 'Writable permissions', 'dir_isnt_writable' => 'No allowed', 'dir_is_writable' => 'Allowed', 'operation' => 'What to do?', 'upgrade' => 'Update to Keitaro 7', 'downgrade' => 'Downgrade to Keitaro 6', 'warning' => '

WARNING! Make sure that you made a backup. You might want to downgrade.

TDS won\'t work until all migrations complete. Strongly suggest switching off traffic while updating.

', ), 'upgrade' => array( 'title' => 'Update', 'content' => '

Files updated.

Remove file upgrader7.php.

Then sign in to Keitaro and go to page "Maintenance > Migrations". Press "Run migrations" there.

', ), 'downgrade' => array( 'title' => 'Downgrade', 'content' => '

Files restored.

Please tell us about the reason of downgrade to feedback@keitarotds.com

Do not forger to remove upgrader7.php

', ), 'failure' => 'Failure', 'documentation' => 'Instructions on update Keitaro 7.', 'do' => 'Continue', 'continue' => 'Continue', 'retry' => 'Retry' ) ); protected static $_language; protected static $_languages = array('ru', 'en'); const DEFAULT_LANGUAGE = 'ru'; public static function setPreferredLanguage($lang) { if (!in_array($lang, self::$_languages)) { throw new Exception('Language ' . $lang . ' not exists'); } setcookie('installer_lang', $lang); $_COOKIE['installer_lang'] = $lang; } public static function getPreferredLanguage() { if (isset($_COOKIE['installer_lang'])) { $lang = $_COOKIE['installer_lang']; } else { if (strstr($_SERVER["HTTP_ACCEPT_LANGUAGE"], 'en')) { $lang = 'en'; } if (strstr($_SERVER["HTTP_ACCEPT_LANGUAGE"], 'ru')) { $lang = 'ru'; } } if (!in_array($lang, self::$_languages)) { $lang = self::DEFAULT_LANGUAGE; } return $lang; } public static function get($key, $params = null) { $path = explode('.', $key); $data = self::$_data[self::getPreferredLanguage()]; $translation = self::_find($path, $data); if (!isset($translation)) { $translation = $key; } if ($params) { if (!is_array($params)) { $params = array($params); } $args = array_merge(array($translation), $params); $translation = call_user_func_array('sprintf', $args); } return $translation; } public static function t($key, $params = null) { return KLocale::get($key, $params); } protected static function _find($path, $data) { $key = array_shift($path); if (!isset($data[$key])) { return null; } if (count($path)) { return self::_find($path, $data[$key]); } return $data[$key]; } } $Installer = new Upgrader7(); $Installer->setTemplate(ob_get_contents()); ob_clean(); $Installer->dispatch();