Reorganized code to reduce comments

This commit is contained in:
Marcin Kurczewski 2014-08-09 20:35:31 +02:00
parent 9b9ba9c33c
commit 40e774cce9
13 changed files with 233 additions and 211 deletions

View file

@ -1,10 +1,22 @@
<?php <?php
require_once 'src/core.php'; require_once 'src/core.php';
$config = Core::getConfig();
$fontsPath = TextHelper::absolutePath($config->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) function download($source, $destination = null)
{ {
@ -26,16 +38,16 @@ function download($source, $destination = null)
return $content; return $content;
} }
$version = exec('git describe --tags --always --dirty'); function downloadJquery()
$branch = exec('git rev-parse --abbrev-ref HEAD'); {
PropertyModel::set(PropertyModel::EngineVersion, $version . '@' . $branch); $libPath = getLibPath();
//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.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'); download('http://code.jquery.com/jquery-2.1.1.min.map', $libPath . DS . 'jquery' . DS . 'jquery.min.map');
}
//jQuery UI 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'); 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'); $manifest = download('http://ajax.googleapis.com/ajax/libs/jqueryui/1/MANIFEST');
$lines = explode("\n", str_replace("\r", '', $manifest)); $lines = explode("\n", str_replace("\r", '', $manifest));
@ -48,18 +60,32 @@ foreach ($lines as $line)
download($srcUrl, $dstUrl); download($srcUrl, $dstUrl);
} }
} }
}
//jQuery Tag-it! 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/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'); download('http://raw.github.com/aehlke/tag-it/master/js/tag-it.min.js', $libPath . DS . 'tagit' . DS . 'jquery.tagit.js');
}
//Mousetrap function downloadMousetrap()
{
$libPath = getLibPath();
download('http://raw.github.com/ccampbell/mousetrap/master/mousetrap.min.js', $libPath . DS . 'mousetrap' . DS . 'mousetrap.min.js'); download('http://raw.github.com/ccampbell/mousetrap/master/mousetrap.min.js', $libPath . DS . 'mousetrap' . DS . 'mousetrap.min.js');
}
//fonts 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.ttf', $fontsPath . DS . 'DroidSans.ttf');
download('http://googlefontdirectory.googlecode.com/hg/apache/droidsans/DroidSans-Bold.ttf', $fontsPath . DS . 'DroidSans-Bold.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'; require_once 'upgrade.php';

View file

@ -23,18 +23,9 @@ class GetLogJob extends AbstractJob implements IPagedJob
? $this->getArgument(JobArgs::ARG_QUERY) ? $this->getArgument(JobArgs::ARG_QUERY)
: ''; : '';
//parse input
$page = max(1, intval($page)); $page = max(1, intval($page));
$name = str_replace(['/', '\\'], '', $name); //paranoia mode $path = $this->getPath($name);
$path = TextHelper::absolutePath(dirname(Core::getConfig()->main->logsPath) . DS . $name); $lines = $this->loadLines($path);
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);
if (!empty($query)) if (!empty($query))
{ {
@ -77,4 +68,22 @@ class GetLogJob extends AbstractJob implements IPagedJob
{ {
return false; 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;
}
} }

View file

@ -9,11 +9,8 @@ class ListLogsJob extends AbstractJob
foreach (glob(dirname($path) . DS . '*.log') as $log) foreach (glob(dirname($path) . DS . '*.log') as $log)
$logs []= basename($log); $logs []= basename($log);
usort($logs, function($a, $b) natcasesort($logs);
{ $logs = array_reverse($logs);
return strnatcasecmp($b, $a); //reverse natcasesort
});
return $logs; return $logs;
} }

View file

@ -29,24 +29,7 @@ class AddPostJob extends AbstractJob
$arguments = $this->getArguments(); $arguments = $this->getArguments();
$arguments[JobArgs::ARG_POST_ENTITY] = $post; $arguments[JobArgs::ARG_POST_ENTITY] = $post;
Logger::bufferChanges(); $this->runSubJobs($this->getSubJobs(), $arguments);
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
PostModel::save($post); PostModel::save($post);
Logger::log('{user} added {post} (tags: {tags}, safety: {safety}, source: {source})', [ Logger::log('{user} added {post} (tags: {tags}, safety: {safety}, source: {source})', [
@ -87,4 +70,24 @@ class AddPostJob extends AbstractJob
{ {
return Core::getConfig()->uploads->needEmailForUploading; 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();
}
}
}
} }

View file

@ -30,25 +30,7 @@ class AddUserJob extends AbstractJob
$arguments = $this->getArguments(); $arguments = $this->getArguments();
$arguments[JobArgs::ARG_USER_ENTITY] = $user; $arguments[JobArgs::ARG_USER_ENTITY] = $user;
Logger::bufferChanges(); $this->runSubJobs($this->getSubJobs(), $arguments);
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
UserModel::save($user); UserModel::save($user);
EditUserEmailJob::observeSave($user); EditUserEmailJob::observeSave($user);
@ -84,4 +66,24 @@ class AddUserJob extends AbstractJob
{ {
return false; 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();
}
}
}
} }

View file

@ -10,19 +10,8 @@ class LogController extends AbstractController
public function logView($name, $page = 1, $filter = '') public function logView($name, $page = 1, $filter = '')
{ {
//redirect requests in form of ?query=... to canonical address if ($this->redirectIfUnattractiveUrl($name))
$formQuery = InputHelper::get('query');
if ($formQuery !== null)
{
$this->redirect(Core::getRouter()->linkTo(
['LogController', 'logView'],
[
'name' => $name,
'filter' => $formQuery,
'page' => 1
]));
return; return;
}
$ret = Api::run( $ret = Api::run(
new GetLogJob(), new GetLogJob(),
@ -32,13 +21,7 @@ class LogController extends AbstractController
JobArgs::ARG_QUERY => $filter, JobArgs::ARG_QUERY => $filter,
]); ]);
//stylize important lines $lines = $this->stylizeImportantLines($ret->entities);
$lines = $ret->entities;
foreach ($lines as &$line)
if (strpos($line, 'flag') !== false)
$line = '**' . $line . '**';
unset($line);
$lines = join(PHP_EOL, $lines); $lines = join(PHP_EOL, $lines);
$lines = TextHelper::parseMarkdown($lines, true); $lines = TextHelper::parseMarkdown($lines, true);
$lines = trim($lines); $lines = trim($lines);
@ -50,4 +33,30 @@ class LogController extends AbstractController
$context->transport->name = $name; $context->transport->name = $name;
$this->renderView('log-view'); $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;
}
} }

View file

@ -129,7 +129,6 @@ class PostController extends AbstractController
public function uploadThumbnailView($url) public function uploadThumbnailView($url)
{ {
$url = base64_decode($url); $url = base64_decode($url);
if (!Core::getConfig()->misc->proxyThumbsInUpload) if (!Core::getConfig()->misc->proxyThumbsInUpload)
{ {
$this->redirect($url); $this->redirect($url);
@ -144,7 +143,7 @@ class PostController extends AbstractController
$options->lastModified = time() - 3600; $options->lastModified = time() - 3600;
$options->cacheDaysToLive = 0.5; $options->cacheDaysToLive = 0.5;
$options->mimeType = mime_content_type($tmpPath); $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->mimeType = 'image/jpeg';
$options->fileHash = 'thumb.jpg'; $options->fileHash = 'thumb.jpg';

View file

@ -64,7 +64,6 @@ class Logger
self::flush(); self::flush();
} }
//methods for manipulating buffered logs
public static function getBuffer() public static function getBuffer()
{ {
return self::$buffer; return self::$buffer;

View file

@ -85,16 +85,20 @@ class Mailer
Mail $mail, Mail $mail,
array $tokens = []) 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 = TokenModel::spawn();
$token->setUser($user); $token->setUser($user);
$token->setUsed(false); $token->setUsed(false);
$token->setExpirationTime(null); $token->setExpirationTime(null);
TokenModel::save($token); TokenModel::save($token);
return $token;
$tokens['link'] = Core::getRouter()->linkTo($linkDestination, ['tokenText' => $token->getText()]);
$tokens['token'] = $token->getText(); //yeah
return self::sendMail($mail, $tokens);
} }
} }

View file

@ -315,23 +315,14 @@ final class PostModel extends AbstractCrudModel
$featuredPostId = PropertyModel::get(PropertyModel::FeaturedPostId); $featuredPostId = PropertyModel::get(PropertyModel::FeaturedPostId);
$featuredPostUnixTime = PropertyModel::get(PropertyModel::FeaturedPostUnixTime); $featuredPostUnixTime = PropertyModel::get(PropertyModel::FeaturedPostUnixTime);
$deleted = PostModel::tryGetById($featuredPostId) === null;
$expired = $featuredPostUnixTime + $featuredPostRotationTime < time();
$featuringNecessary = ($deleted or $expired);
//check if too old if ($featuringNecessary)
if (!$featuredPostId or $featuredPostUnixTime + $featuredPostRotationTime < time())
{
self::featureRandomPost(); self::featureRandomPost();
return true;
}
//check if post was deleted return $featuringNecessary;
$featuredPost = PostModel::tryGetById($featuredPostId);
if (!$featuredPost)
{
self::featureRandomPost();
return true;
}
return false;
} }
public static function featureRandomPost() public static function featureRandomPost()

View file

@ -15,30 +15,11 @@ class TagSearchService extends AbstractSearchService
return []; return [];
$parentTagId = $parentTagEntity->getId(); $parentTagId = $parentTagEntity->getId();
$punishCommonTags = false;
$rows = self::getSiblingTagsWithOccurences($parentTagId); $rows = self::getSiblingTagsWithOccurences($parentTagId);
unset($rows[$parentTagId]); unset($rows[$parentTagId]);
if ($punishCommonTags)
{
$rowsGlobal = self::getGlobalOccurencesForTags(array_keys($rows));
foreach ($rows as $i => &$row) 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']; $row['sort'] = $row['post_count'];
}
}
usort($rows, function($a, $b) usort($rows, function($a, $b)
{ {

View file

@ -10,7 +10,7 @@ final class Core
private static $database; private static $database;
private static $rootDir; private static $rootDir;
static function init() public static function init()
{ {
self::$rootDir = __DIR__ . DS . '..' . DS; self::$rootDir = __DIR__ . DS . '..' . DS;
chdir(self::$rootDir); chdir(self::$rootDir);
@ -26,55 +26,37 @@ final class Core
\Chibi\AutoLoader::registerFilesystem(__DIR__); \Chibi\AutoLoader::registerFilesystem(__DIR__);
self::$router = new Router(); self::$router = new Router();
self::prepareConfig();
self::checkExtensions();
} }
static function getRouter() public static function getRouter()
{ {
return self::$router; return self::$router;
} }
static function getConfig() public static function getConfig()
{ {
return self::$config; return self::$config;
} }
static function getContext() public static function getContext()
{ {
return self::$context; return self::$context;
} }
static function getDatabase() public static function getDatabase()
{ {
return self::$database; return self::$database;
} }
static function setConfig(\Chibi\Config $config) public static function setConfig(\Chibi\Config $config)
{ {
self::$config = $config; self::$config = $config;
self::$config->rootDir = self::$rootDir; self::$config->rootDir = self::$rootDir;
} }
static function prepareConfig() public static function prepareDatabase()
{
$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()
{ {
$config = self::getConfig(); $config = self::getConfig();
self::$database = new \Chibi\Db\Database( self::$database = new \Chibi\Db\Database(
@ -85,7 +67,7 @@ final class Core
\Chibi\Sql\Config::setDriver(self::$database->getDriver()); \Chibi\Sql\Config::setDriver(self::$database->getDriver());
} }
static function prepareEnvironment() public static function prepareEnvironment()
{ {
self::prepareContext(); self::prepareContext();
@ -95,46 +77,13 @@ final class Core
TransferHelper::createDirectory($config->main->thumbnailsPath); TransferHelper::createDirectory($config->main->thumbnailsPath);
TransferHelper::createDirectory($config->main->avatarsPath); 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(); Access::init();
Logger::init(); Logger::init();
Mailer::init(); Mailer::init();
PropertyModel::init(); PropertyModel::init();
} }
static function getDbVersion() public static function upgradeDatabase()
{
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()
{ {
$config = self::getConfig(); $config = self::getConfig();
$upgradesPath = TextHelper::absolutePath($config->rootDir $upgradesPath = TextHelper::absolutePath($config->rootDir
@ -190,9 +139,64 @@ final class Core
list ($dbVersionMajor, $dbVersionMinor) = self::getDbVersion(); list ($dbVersionMajor, $dbVersionMinor) = self::getDbVersion();
printf('Database version: %d.%d' . PHP_EOL, $dbVersionMajor, $dbVersionMinor); 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::init();
Core::prepareConfig();
Core::prepareDatabase(); Core::prepareDatabase();
Core::prepareEnvironment(); Core::prepareEnvironment();

View file

@ -123,9 +123,7 @@ class ReflectionBasedTestRunner implements ITestRunner
} }
}; };
//run all the methods
echo 'Starting tests' . PHP_EOL; echo 'Starting tests' . PHP_EOL;
$success = true; $success = true;
foreach ($testFixtures as $className => $testFixture) foreach ($testFixtures as $className => $testFixture)
{ {