From 40e774cce95057d5f5ed83f19911b66ebd2dad61 Mon Sep 17 00:00:00 2001 From: Marcin Kurczewski Date: Sat, 9 Aug 2014 20:35:31 +0200 Subject: [PATCH] Reorganized code to reduce comments --- init.php | 86 ++++++++---- src/Api/Jobs/LogJobs/GetLogJob.php | 31 +++-- src/Api/Jobs/LogJobs/ListLogsJob.php | 7 +- src/Api/Jobs/PostJobs/AddPostJob.php | 39 +++--- src/Api/Jobs/UserJobs/AddUserJob.php | 40 +++--- src/Controllers/LogController.php | 47 ++++--- src/Controllers/PostController.php | 3 +- src/Logger.php | 1 - src/Mailer.php | 16 ++- src/Models/PostModel.php | 19 +-- .../SearchServices/TagSearchService.php | 23 +--- src/core.php | 130 +++++++++--------- tests/ReflectionBasedTestRunner.php | 2 - 13 files changed, 233 insertions(+), 211 deletions(-) diff --git a/init.php b/init.php index f0063515..55d42318 100644 --- a/init.php +++ b/init.php @@ -1,10 +1,22 @@ main->mediaPath . DS . 'fonts'); -$libPath = TextHelper::absolutePath($config->main->mediaPath . DS . 'lib'); +function updateVersion() +{ + $version = exec('git describe --tags --always --dirty'); + $branch = exec('git rev-parse --abbrev-ref HEAD'); + PropertyModel::set(PropertyModel::EngineVersion, $version . '@' . $branch); +} +function getLibPath() +{ + return TextHelper::absolutePath(Core::getConfig()->main->mediaPath . DS . 'lib'); +} + +function getFontsPath() +{ + return TextHelper::absolutePath(Core::getConfig()->main->mediaPath . DS . 'fonts'); +} function download($source, $destination = null) { @@ -26,40 +38,54 @@ function download($source, $destination = null) return $content; } -$version = exec('git describe --tags --always --dirty'); -$branch = exec('git rev-parse --abbrev-ref HEAD'); -PropertyModel::set(PropertyModel::EngineVersion, $version . '@' . $branch); - - -//jQuery -download('http://code.jquery.com/jquery-2.1.1.min.js', $libPath . DS . 'jquery' . DS . 'jquery.min.js'); -download('http://code.jquery.com/jquery-2.1.1.min.map', $libPath . DS . 'jquery' . DS . 'jquery.min.map'); - -//jQuery UI -download('http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js', $libPath . DS . 'jquery-ui' . DS . 'jquery-ui.min.js'); -$manifest = download('http://ajax.googleapis.com/ajax/libs/jqueryui/1/MANIFEST'); -$lines = explode("\n", str_replace("\r", '', $manifest)); -foreach ($lines as $line) +function downloadJquery() { - if (preg_match('/themes\/flick\/(.*?) /', $line, $matches)) + $libPath = getLibPath(); + download('http://code.jquery.com/jquery-2.1.1.min.js', $libPath . DS . 'jquery' . DS . 'jquery.min.js'); + download('http://code.jquery.com/jquery-2.1.1.min.map', $libPath . DS . 'jquery' . DS . 'jquery.min.map'); +} + +function downloadJqueryUi() +{ + $libPath = getLibPath(); + download('http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js', $libPath . DS . 'jquery-ui' . DS . 'jquery-ui.min.js'); + $manifest = download('http://ajax.googleapis.com/ajax/libs/jqueryui/1/MANIFEST'); + $lines = explode("\n", str_replace("\r", '', $manifest)); + foreach ($lines as $line) { - $srcUrl = 'http://ajax.googleapis.com/ajax/libs/jqueryui/1/' . $matches[0]; - $dstUrl = $libPath . DS . 'jquery-ui' . DS . $matches[1]; - download($srcUrl, $dstUrl); + if (preg_match('/themes\/flick\/(.*?) /', $line, $matches)) + { + $srcUrl = 'http://ajax.googleapis.com/ajax/libs/jqueryui/1/' . $matches[0]; + $dstUrl = $libPath . DS . 'jquery-ui' . DS . $matches[1]; + download($srcUrl, $dstUrl); + } } } -//jQuery Tag-it! -download('http://raw.github.com/aehlke/tag-it/master/css/jquery.tagit.css', $libPath . DS . 'tagit' . DS . 'jquery.tagit.css'); -download('http://raw.github.com/aehlke/tag-it/master/js/tag-it.min.js', $libPath . DS . 'tagit' . DS . 'jquery.tagit.js'); +function downloadJqueryTagIt() +{ + $libPath = getLibPath(); + download('http://raw.github.com/aehlke/tag-it/master/css/jquery.tagit.css', $libPath . DS . 'tagit' . DS . 'jquery.tagit.css'); + download('http://raw.github.com/aehlke/tag-it/master/js/tag-it.min.js', $libPath . DS . 'tagit' . DS . 'jquery.tagit.js'); +} -//Mousetrap -download('http://raw.github.com/ccampbell/mousetrap/master/mousetrap.min.js', $libPath . DS . 'mousetrap' . DS . 'mousetrap.min.js'); - -//fonts -download('http://googlefontdirectory.googlecode.com/hg/apache/droidsans/DroidSans.ttf', $fontsPath . DS . 'DroidSans.ttf'); -download('http://googlefontdirectory.googlecode.com/hg/apache/droidsans/DroidSans-Bold.ttf', $fontsPath . DS . 'DroidSans-Bold.ttf'); +function downloadMousetrap() +{ + $libPath = getLibPath(); + download('http://raw.github.com/ccampbell/mousetrap/master/mousetrap.min.js', $libPath . DS . 'mousetrap' . DS . 'mousetrap.min.js'); +} +function downloadFonts() +{ + $fontsPath = getFontsPath(); + download('http://googlefontdirectory.googlecode.com/hg/apache/droidsans/DroidSans.ttf', $fontsPath . DS . 'DroidSans.ttf'); + download('http://googlefontdirectory.googlecode.com/hg/apache/droidsans/DroidSans-Bold.ttf', $fontsPath . DS . 'DroidSans-Bold.ttf'); +} +downloadJquery(); +downloadJqueryUi(); +downloadJqueryTagIt(); +downloadMousetrap(); +downloadFonts(); require_once 'upgrade.php'; diff --git a/src/Api/Jobs/LogJobs/GetLogJob.php b/src/Api/Jobs/LogJobs/GetLogJob.php index c777dfd7..8902b3b2 100644 --- a/src/Api/Jobs/LogJobs/GetLogJob.php +++ b/src/Api/Jobs/LogJobs/GetLogJob.php @@ -23,18 +23,9 @@ class GetLogJob extends AbstractJob implements IPagedJob ? $this->getArgument(JobArgs::ARG_QUERY) : ''; - //parse input $page = max(1, intval($page)); - $name = str_replace(['/', '\\'], '', $name); //paranoia mode - $path = TextHelper::absolutePath(dirname(Core::getConfig()->main->logsPath) . DS . $name); - if (!file_exists($path)) - throw new SimpleNotFoundException('Specified log doesn\'t exist'); - - //load lines - $lines = file_get_contents($path); - $lines = trim($lines); - $lines = explode(PHP_EOL, str_replace(["\r", "\n"], PHP_EOL, $lines)); - $lines = array_reverse($lines); + $path = $this->getPath($name); + $lines = $this->loadLines($path); if (!empty($query)) { @@ -77,4 +68,22 @@ class GetLogJob extends AbstractJob implements IPagedJob { return false; } + + private function getPath($name) + { + $name = str_replace(['/', '\\'], '', $name); + return TextHelper::absolutePath(dirname(Core::getConfig()->main->logsPath) . DS . $name); + } + + private function loadLines($path) + { + if (!file_exists($path)) + throw new SimpleNotFoundException('Specified log doesn\'t exist'); + + $lines = file_get_contents($path); + $lines = trim($lines); + $lines = explode(PHP_EOL, str_replace(["\r", "\n"], PHP_EOL, $lines)); + $lines = array_reverse($lines); + return $lines; + } } diff --git a/src/Api/Jobs/LogJobs/ListLogsJob.php b/src/Api/Jobs/LogJobs/ListLogsJob.php index 466cadb6..4c3afecf 100644 --- a/src/Api/Jobs/LogJobs/ListLogsJob.php +++ b/src/Api/Jobs/LogJobs/ListLogsJob.php @@ -9,11 +9,8 @@ class ListLogsJob extends AbstractJob foreach (glob(dirname($path) . DS . '*.log') as $log) $logs []= basename($log); - usort($logs, function($a, $b) - { - return strnatcasecmp($b, $a); //reverse natcasesort - }); - + natcasesort($logs); + $logs = array_reverse($logs); return $logs; } diff --git a/src/Api/Jobs/PostJobs/AddPostJob.php b/src/Api/Jobs/PostJobs/AddPostJob.php index 258eef4a..c7e9d8f3 100644 --- a/src/Api/Jobs/PostJobs/AddPostJob.php +++ b/src/Api/Jobs/PostJobs/AddPostJob.php @@ -29,24 +29,7 @@ class AddPostJob extends AbstractJob $arguments = $this->getArguments(); $arguments[JobArgs::ARG_POST_ENTITY] = $post; - Logger::bufferChanges(); - foreach ($this->getSubJobs() as $subJob) - { - $subJob->setContext(self::CONTEXT_BATCH_ADD); - try - { - Api::run($subJob, $arguments); - } - catch (ApiJobUnsatisfiedException $e) - { - } - finally - { - Logger::discardBuffer(); - } - } - - //save the post to db if everything went okay + $this->runSubJobs($this->getSubJobs(), $arguments); PostModel::save($post); Logger::log('{user} added {post} (tags: {tags}, safety: {safety}, source: {source})', [ @@ -87,4 +70,24 @@ class AddPostJob extends AbstractJob { return Core::getConfig()->uploads->needEmailForUploading; } + + private function runSubJobs($subJobs, $arguments) + { + foreach ($subJobs as $subJob) + { + Logger::bufferChanges(); + $subJob->setContext(self::CONTEXT_BATCH_ADD); + try + { + Api::run($subJob, $arguments); + } + catch (ApiJobUnsatisfiedException $e) + { + } + finally + { + Logger::discardBuffer(); + } + } + } } diff --git a/src/Api/Jobs/UserJobs/AddUserJob.php b/src/Api/Jobs/UserJobs/AddUserJob.php index 990f6363..3c0c02b4 100644 --- a/src/Api/Jobs/UserJobs/AddUserJob.php +++ b/src/Api/Jobs/UserJobs/AddUserJob.php @@ -30,25 +30,7 @@ class AddUserJob extends AbstractJob $arguments = $this->getArguments(); $arguments[JobArgs::ARG_USER_ENTITY] = $user; - Logger::bufferChanges(); - foreach ($this->getSubJobs() as $subJob) - { - $subJob->setContext(self::CONTEXT_BATCH_ADD); - - try - { - Api::run($subJob, $arguments); - } - catch (ApiJobUnsatisfiedException $e) - { - } - finally - { - Logger::discardBuffer(); - } - } - - //save the user to db if everything went okay + $this->runSubJobs($this->getSubJobs(), $arguments); UserModel::save($user); EditUserEmailJob::observeSave($user); @@ -84,4 +66,24 @@ class AddUserJob extends AbstractJob { return false; } + + private function runSubJobs($subJobs, $arguments) + { + foreach ($subJobs as $subJob) + { + Logger::bufferChanges(); + $subJob->setContext(self::CONTEXT_BATCH_ADD); + try + { + Api::run($subJob, $arguments); + } + catch (ApiJobUnsatisfiedException $e) + { + } + finally + { + Logger::discardBuffer(); + } + } + } } diff --git a/src/Controllers/LogController.php b/src/Controllers/LogController.php index 01a91b45..1dfac550 100644 --- a/src/Controllers/LogController.php +++ b/src/Controllers/LogController.php @@ -10,19 +10,8 @@ class LogController extends AbstractController public function logView($name, $page = 1, $filter = '') { - //redirect requests in form of ?query=... to canonical address - $formQuery = InputHelper::get('query'); - if ($formQuery !== null) - { - $this->redirect(Core::getRouter()->linkTo( - ['LogController', 'logView'], - [ - 'name' => $name, - 'filter' => $formQuery, - 'page' => 1 - ])); + if ($this->redirectIfUnattractiveUrl($name)) return; - } $ret = Api::run( new GetLogJob(), @@ -32,13 +21,7 @@ class LogController extends AbstractController JobArgs::ARG_QUERY => $filter, ]); - //stylize important lines - $lines = $ret->entities; - foreach ($lines as &$line) - if (strpos($line, 'flag') !== false) - $line = '**' . $line . '**'; - unset($line); - + $lines = $this->stylizeImportantLines($ret->entities); $lines = join(PHP_EOL, $lines); $lines = TextHelper::parseMarkdown($lines, true); $lines = trim($lines); @@ -50,4 +33,30 @@ class LogController extends AbstractController $context->transport->name = $name; $this->renderView('log-view'); } + + private function redirectIfUnattractiveUrl($name) + { + $formQuery = InputHelper::get('query'); + if ($formQuery !== null) + { + $this->redirect(Core::getRouter()->linkTo( + ['LogController', 'logView'], + [ + 'name' => $name, + 'filter' => $formQuery, + 'page' => 1 + ])); + return true; + } + return false; + } + + private function stylizeImportantLines($lines) + { + foreach ($lines as &$line) + if (strpos($line, 'flag') !== false) + $line = '**' . $line . '**'; + unset($line); + return $lines; + } } diff --git a/src/Controllers/PostController.php b/src/Controllers/PostController.php index fd3b700a..255b2a86 100644 --- a/src/Controllers/PostController.php +++ b/src/Controllers/PostController.php @@ -129,7 +129,6 @@ class PostController extends AbstractController public function uploadThumbnailView($url) { $url = base64_decode($url); - if (!Core::getConfig()->misc->proxyThumbsInUpload) { $this->redirect($url); @@ -144,7 +143,7 @@ class PostController extends AbstractController $options->lastModified = time() - 3600; $options->cacheDaysToLive = 0.5; $options->mimeType = mime_content_type($tmpPath); - if (strpos($options->mimeType, 'image/') !== 0) //not an image + if (strpos($options->mimeType, 'image/') !== 0) { $options->mimeType = 'image/jpeg'; $options->fileHash = 'thumb.jpg'; diff --git a/src/Logger.php b/src/Logger.php index 0b3ca8db..ed9a44f7 100644 --- a/src/Logger.php +++ b/src/Logger.php @@ -64,7 +64,6 @@ class Logger self::flush(); } - //methods for manipulating buffered logs public static function getBuffer() { return self::$buffer; diff --git a/src/Mailer.php b/src/Mailer.php index 9029906e..3888b173 100644 --- a/src/Mailer.php +++ b/src/Mailer.php @@ -85,16 +85,20 @@ class Mailer Mail $mail, array $tokens = []) { - //prepare unique user token + $userToken = self::prepareUniqueUserToken($user); + $userTokenText = $userToken->getText(); + $replacementTokens['link'] = Core::getRouter()->linkTo($linkDestination, ['tokenText' => $userTokenText]); + $replacementTokens['token'] = $userTokenText; + return self::sendMail($mail, $replacementTokens); + } + + private static function prepareUniqueUserToken($user) + { $token = TokenModel::spawn(); $token->setUser($user); $token->setUsed(false); $token->setExpirationTime(null); TokenModel::save($token); - - $tokens['link'] = Core::getRouter()->linkTo($linkDestination, ['tokenText' => $token->getText()]); - $tokens['token'] = $token->getText(); //yeah - - return self::sendMail($mail, $tokens); + return $token; } } diff --git a/src/Models/PostModel.php b/src/Models/PostModel.php index 5481ace3..f4eb47d5 100644 --- a/src/Models/PostModel.php +++ b/src/Models/PostModel.php @@ -315,23 +315,14 @@ final class PostModel extends AbstractCrudModel $featuredPostId = PropertyModel::get(PropertyModel::FeaturedPostId); $featuredPostUnixTime = PropertyModel::get(PropertyModel::FeaturedPostUnixTime); + $deleted = PostModel::tryGetById($featuredPostId) === null; + $expired = $featuredPostUnixTime + $featuredPostRotationTime < time(); + $featuringNecessary = ($deleted or $expired); - //check if too old - if (!$featuredPostId or $featuredPostUnixTime + $featuredPostRotationTime < time()) - { + if ($featuringNecessary) self::featureRandomPost(); - return true; - } - //check if post was deleted - $featuredPost = PostModel::tryGetById($featuredPostId); - if (!$featuredPost) - { - self::featureRandomPost(); - return true; - } - - return false; + return $featuringNecessary; } public static function featureRandomPost() diff --git a/src/Models/SearchServices/TagSearchService.php b/src/Models/SearchServices/TagSearchService.php index 9cd00002..671209bf 100644 --- a/src/Models/SearchServices/TagSearchService.php +++ b/src/Models/SearchServices/TagSearchService.php @@ -15,30 +15,11 @@ class TagSearchService extends AbstractSearchService return []; $parentTagId = $parentTagEntity->getId(); - $punishCommonTags = false; - $rows = self::getSiblingTagsWithOccurences($parentTagId); unset($rows[$parentTagId]); - if ($punishCommonTags) - { - $rowsGlobal = self::getGlobalOccurencesForTags(array_keys($rows)); - - foreach ($rows as $i => &$row) - { - //multiply own occurences by two because we are going to subtract them - $row['sort'] = $row['post_count'] * 2; - //subtract global occurencecount - $row['sort'] -= isset($rowsGlobal[$i]) ? $rowsGlobal[$i]['post_count'] : 0; - } - } - else - { - foreach ($rows as $i => &$row) - { - $row['sort'] = $row['post_count']; - } - } + foreach ($rows as $i => &$row) + $row['sort'] = $row['post_count']; usort($rows, function($a, $b) { diff --git a/src/core.php b/src/core.php index adf93065..5c9d65fe 100644 --- a/src/core.php +++ b/src/core.php @@ -10,7 +10,7 @@ final class Core private static $database; private static $rootDir; - static function init() + public static function init() { self::$rootDir = __DIR__ . DS . '..' . DS; chdir(self::$rootDir); @@ -26,55 +26,37 @@ final class Core \Chibi\AutoLoader::registerFilesystem(__DIR__); self::$router = new Router(); + self::prepareConfig(); + self::checkExtensions(); } - static function getRouter() + public static function getRouter() { return self::$router; } - static function getConfig() + public static function getConfig() { return self::$config; } - static function getContext() + public static function getContext() { return self::$context; } - static function getDatabase() + public static function getDatabase() { return self::$database; } - static function setConfig(\Chibi\Config $config) + public static function setConfig(\Chibi\Config $config) { self::$config = $config; self::$config->rootDir = self::$rootDir; } - static function prepareConfig() - { - $configPaths = []; - $configPaths []= self::$rootDir . DS . 'data' . DS . 'config.ini'; - $configPaths []= self::$rootDir . DS . 'data' . DS . 'local.ini'; - - self::$config = new \Chibi\Config(); - foreach ($configPaths as $path) - if (file_exists($path)) - self::$config->loadIni($path); - self::$config->rootDir = self::$rootDir; - } - - static function prepareContext() - { - global $startTime; - self::$context = new StdClass; - self::$context->startTime = $startTime; - } - - static function prepareDatabase() + public static function prepareDatabase() { $config = self::getConfig(); self::$database = new \Chibi\Db\Database( @@ -85,7 +67,7 @@ final class Core \Chibi\Sql\Config::setDriver(self::$database->getDriver()); } - static function prepareEnvironment() + public static function prepareEnvironment() { self::prepareContext(); @@ -95,46 +77,13 @@ final class Core TransferHelper::createDirectory($config->main->thumbnailsPath); TransferHelper::createDirectory($config->main->avatarsPath); - //extension sanity checks - $requiredExtensions = ['pdo', 'pdo_' . $config->main->dbDriver, 'openssl', 'fileinfo']; - foreach ($requiredExtensions as $ext) - if (!extension_loaded($ext)) - die('PHP extension "' . $ext . '" must be enabled to continue.' . PHP_EOL); - Access::init(); Logger::init(); Mailer::init(); PropertyModel::init(); } - static function getDbVersion() - { - try - { - $dbVersion = PropertyModel::get(PropertyModel::DbVersion); - } - catch (Exception $e) - { - return [null, null]; - } - if (strpos($dbVersion, '.') !== false) - { - list ($dbVersionMajor, $dbVersionMinor) = explode('.', $dbVersion); - } - elseif ($dbVersion) - { - $dbVersionMajor = $dbVersion; - $dbVersionMinor = null; - } - else - { - $dbVersionMajor = 0; - $dbVersionMinor = 0; - } - return [$dbVersionMajor, $dbVersionMinor]; - } - - static function upgradeDatabase() + public static function upgradeDatabase() { $config = self::getConfig(); $upgradesPath = TextHelper::absolutePath($config->rootDir @@ -190,9 +139,64 @@ final class Core list ($dbVersionMajor, $dbVersionMinor) = self::getDbVersion(); printf('Database version: %d.%d' . PHP_EOL, $dbVersionMajor, $dbVersionMinor); } + + private static function checkExtensions() + { + $config = self::getConfig(); + $requiredExtensions = ['pdo', 'pdo_' . $config->main->dbDriver, 'openssl', 'fileinfo']; + foreach ($requiredExtensions as $ext) + if (!extension_loaded($ext)) + die('PHP extension "' . $ext . '" must be enabled to continue.' . PHP_EOL); + } + + private static function prepareContext() + { + global $startTime; + self::$context = new StdClass; + self::$context->startTime = $startTime; + } + + private static function prepareConfig() + { + $configPaths = []; + $configPaths []= self::$rootDir . DS . 'data' . DS . 'config.ini'; + $configPaths []= self::$rootDir . DS . 'data' . DS . 'local.ini'; + + self::$config = new \Chibi\Config(); + foreach ($configPaths as $path) + if (file_exists($path)) + self::$config->loadIni($path); + self::$config->rootDir = self::$rootDir; + } + + private static function getDbVersion() + { + try + { + $dbVersion = PropertyModel::get(PropertyModel::DbVersion); + } + catch (Exception $e) + { + return [null, null]; + } + if (strpos($dbVersion, '.') !== false) + { + list ($dbVersionMajor, $dbVersionMinor) = explode('.', $dbVersion); + } + elseif ($dbVersion) + { + $dbVersionMajor = $dbVersion; + $dbVersionMinor = null; + } + else + { + $dbVersionMajor = 0; + $dbVersionMinor = 0; + } + return [$dbVersionMajor, $dbVersionMinor]; + } } Core::init(); -Core::prepareConfig(); Core::prepareDatabase(); Core::prepareEnvironment(); diff --git a/tests/ReflectionBasedTestRunner.php b/tests/ReflectionBasedTestRunner.php index b6097c9d..87309224 100644 --- a/tests/ReflectionBasedTestRunner.php +++ b/tests/ReflectionBasedTestRunner.php @@ -123,9 +123,7 @@ class ReflectionBasedTestRunner implements ITestRunner } }; - //run all the methods echo 'Starting tests' . PHP_EOL; - $success = true; foreach ($testFixtures as $className => $testFixture) {