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
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)
{
@ -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';

View file

@ -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;
}
}

View file

@ -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;
}

View file

@ -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();
}
}
}
}

View file

@ -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();
}
}
}
}

View file

@ -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;
}
}

View file

@ -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';

View file

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

View file

@ -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;
}
}

View file

@ -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()

View file

@ -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)
{

View file

@ -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();

View file

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