Increasing readability

This commit is contained in:
Marcin Kurczewski 2014-04-30 08:08:24 +02:00
parent c18c9ec680
commit c52531e8fc
7 changed files with 889 additions and 867 deletions

View file

@ -61,8 +61,9 @@ class AuthController
return;
}
if (InputHelper::get('submit'))
{
if (!InputHelper::get('submit'))
return;
$suppliedName = InputHelper::get('name');
$suppliedPassword = InputHelper::get('password');
$dbUser = self::tryLogin($suppliedName, $suppliedPassword);
@ -75,7 +76,6 @@ class AuthController
StatusHelper::success();
self::redirectAfterLog();
}
}
public function logoutAction()
{

View file

@ -40,8 +40,9 @@ class CommentController
$post = PostModel::findById($postId);
$context->transport->post = $post;
if (InputHelper::get('submit'))
{
if (!InputHelper::get('submit'))
return;
$text = InputHelper::get('text');
$text = CommentModel::validateText($text);
@ -62,7 +63,6 @@ class CommentController
$context->transport->textPreview = $comment->getText();
StatusHelper::success();
}
}
public function editAction($id)
{
@ -74,8 +74,9 @@ class CommentController
Privilege::EditComment,
Access::getIdentity($comment->getCommenter()));
if (InputHelper::get('submit'))
{
if (!InputHelper::get('submit'))
return;
$text = InputHelper::get('text');
$text = CommentModel::validateText($text);
@ -90,7 +91,6 @@ class CommentController
$context->transport->textPreview = $comment->getText();
StatusHelper::success();
}
}
public function deleteAction($id)
{

View file

@ -1,41 +1,6 @@
<?php
class PostController
{
private static function handleUploadErrors($file)
{
switch ($file['error'])
{
case UPLOAD_ERR_OK:
break;
case UPLOAD_ERR_INI_SIZE:
throw new SimpleException('File is too big (maximum size: %s)', ini_get('upload_max_filesize'));
case UPLOAD_ERR_FORM_SIZE:
throw new SimpleException('File is too big than it was allowed in HTML form');
case UPLOAD_ERR_PARTIAL:
throw new SimpleException('File transfer was interrupted');
case UPLOAD_ERR_NO_FILE:
throw new SimpleException('No file was uploaded');
case UPLOAD_ERR_NO_TMP_DIR:
throw new SimpleException('Server misconfiguration error: missing temporary folder');
case UPLOAD_ERR_CANT_WRITE:
throw new SimpleException('Server misconfiguration error: cannot write to disk');
case UPLOAD_ERR_EXTENSION:
throw new SimpleException('Server misconfiguration error: upload was canceled by an extension');
default:
throw new SimpleException('Generic file upload error (id: ' . $file['error'] . ')');
}
if (!is_uploaded_file($file['tmp_name']))
throw new SimpleException('Generic file upload error');
}
public function listAction($query = null, $page = 1, $source = 'posts', $additionalInfo = null)
{
$context = getContext();
@ -98,8 +63,9 @@ class PostController
$post = PostModel::findByIdOrName($id);
$context->transport->post = $post;
if (InputHelper::get('submit'))
{
if (!InputHelper::get('submit'))
return;
Access::assert(
Privilege::MassTag,
Access::getIdentity($post->getUploader()));
@ -137,7 +103,6 @@ class PostController
PostModel::save($post);
StatusHelper::success();
}
}
public function favoritesAction($page = 1)
{
@ -161,8 +126,9 @@ class PostController
if (getConfig()->registration->needEmailForUploading)
Access::assertEmailConfirmation();
if (InputHelper::get('submit'))
{
if (!InputHelper::get('submit'))
return;
\Chibi\Database::transaction(function() use ($context)
{
$post = PostModel::spawn();
@ -204,7 +170,6 @@ class PostController
StatusHelper::success();
}
}
public function editAction($id)
{
@ -212,8 +177,9 @@ class PostController
$post = PostModel::findByIdOrName($id);
$context->transport->post = $post;
if (InputHelper::get('submit'))
{
if (!InputHelper::get('submit'))
return;
$editToken = InputHelper::get('edit-token');
if ($editToken != $post->getEditToken())
throw new SimpleException('This post was already edited by someone else in the meantime');
@ -227,15 +193,15 @@ class PostController
StatusHelper::success();
}
}
public function flagAction($id)
{
$post = PostModel::findByIdOrName($id);
Access::assert(Privilege::FlagPost, Access::getIdentity($post->getUploader()));
if (InputHelper::get('submit'))
{
if (!InputHelper::get('submit'))
return;
$key = TextHelper::reprPost($post);
$flagged = SessionHelper::get('flagged', []);
@ -247,51 +213,50 @@ class PostController
LogHelper::log('{user} flagged {post} for moderator attention', ['post' => TextHelper::reprPost($post)]);
StatusHelper::success();
}
}
public function hideAction($id)
{
$post = PostModel::findByIdOrName($id);
Access::assert(Privilege::HidePost, Access::getIdentity($post->getUploader()));
if (InputHelper::get('submit'))
{
if (!InputHelper::get('submit'))
return;
$post->setHidden(true);
PostModel::save($post);
LogHelper::log('{user} hidden {post}', ['post' => TextHelper::reprPost($post)]);
StatusHelper::success();
}
}
public function unhideAction($id)
{
$post = PostModel::findByIdOrName($id);
Access::assert(Privilege::HidePost, Access::getIdentity($post->getUploader()));
if (InputHelper::get('submit'))
{
if (!InputHelper::get('submit'))
return;
$post->setHidden(false);
PostModel::save($post);
LogHelper::log('{user} unhidden {post}', ['post' => TextHelper::reprPost($post)]);
StatusHelper::success();
}
}
public function deleteAction($id)
{
$post = PostModel::findByIdOrName($id);
Access::assert(Privilege::DeletePost, Access::getIdentity($post->getUploader()));
if (InputHelper::get('submit'))
{
if (!InputHelper::get('submit'))
return;
PostModel::remove($post);
LogHelper::log('{user} deleted {post}', ['post' => TextHelper::reprPost($id)]);
StatusHelper::success();
}
}
public function addFavoriteAction($id)
{
@ -299,8 +264,9 @@ class PostController
$post = PostModel::findByIdOrName($id);
Access::assert(Privilege::FavoritePost, Access::getIdentity($post->getUploader()));
if (InputHelper::get('submit'))
{
if (!InputHelper::get('submit'))
return;
if (!$context->loggedIn)
throw new SimpleException('Not logged in');
@ -308,7 +274,6 @@ class PostController
UserModel::addToUserFavorites($context->user, $post);
StatusHelper::success();
}
}
public function removeFavoriteAction($id)
{
@ -316,15 +281,15 @@ class PostController
$post = PostModel::findByIdOrName($id);
Access::assert(Privilege::FavoritePost, Access::getIdentity($post->getUploader()));
if (InputHelper::get('submit'))
{
if (!InputHelper::get('submit'))
return;
if (!$context->loggedIn)
throw new SimpleException('Not logged in');
UserModel::removeFromUserFavorites($context->user, $post);
StatusHelper::success();
}
}
public function scoreAction($id, $score)
{
@ -332,15 +297,15 @@ class PostController
$post = PostModel::findByIdOrName($id);
Access::assert(Privilege::ScorePost, Access::getIdentity($post->getUploader()));
if (InputHelper::get('submit'))
{
if (!InputHelper::get('submit'))
return;
if (!$context->loggedIn)
throw new SimpleException('Not logged in');
UserModel::updateUserScore($context->user, $post, $score);
StatusHelper::success();
}
}
public function featureAction($id)
{
@ -457,39 +422,8 @@ class PostController
$context->transport->filePath = $path;
}
private function doEdit($post, $isNew)
{
/* file contents */
if (!empty($_FILES['file']['name']))
{
if (!$isNew)
Access::assert(Privilege::EditPostFile, Access::getIdentity($post->getUploader()));
$suppliedFile = $_FILES['file'];
self::handleUploadErrors($suppliedFile);
$srcPath = $suppliedFile['tmp_name'];
$post->setContentFromPath($srcPath);
$post->origName = $suppliedFile['name'];
if (!$isNew)
LogHelper::log('{user} changed contents of {post}', ['post' => TextHelper::reprPost($post)]);
}
elseif (InputHelper::get('url'))
{
if (!$isNew)
Access::assert(Privilege::EditPostFile, Access::getIdentity($post->getUploader()));
$url = InputHelper::get('url');
$post->setContentFromUrl($url);
$post->origName = $url;
if (!$isNew)
LogHelper::log('{user} changed contents of {post}', ['post' => TextHelper::reprPost($post)]);
}
/* safety */
$suppliedSafety = InputHelper::get('safety');
if ($suppliedSafety !== null)
@ -580,6 +514,32 @@ class PostController
}
}
/* file contents */
if (!empty($_FILES['file']['name']))
{
if (!$isNew)
Access::assert(Privilege::EditPostFile, Access::getIdentity($post->getUploader()));
$suppliedFile = $_FILES['file'];
TransferHelper::handleUploadErrors($suppliedFile);
$post->setContentFromPath($suppliedFile['tmp_name'], $suppliedFile['name']);
if (!$isNew)
LogHelper::log('{user} changed contents of {post}', ['post' => TextHelper::reprPost($post)]);
}
elseif (InputHelper::get('url'))
{
if (!$isNew)
Access::assert(Privilege::EditPostFile, Access::getIdentity($post->getUploader()));
$url = InputHelper::get('url');
$post->setContentFromUrl($url);
if (!$isNew)
LogHelper::log('{user} changed contents of {post}', ['post' => TextHelper::reprPost($post)]);
}
/* thumbnail */
if (!empty($_FILES['thumb']['name']))
{
@ -587,10 +547,9 @@ class PostController
Access::assert(Privilege::EditPostThumb, Access::getIdentity($post->getUploader()));
$suppliedFile = $_FILES['thumb'];
self::handleUploadErrors($suppliedFile);
TransferHelper::handleUploadErrors($suppliedFile);
$srcPath = $suppliedFile['tmp_name'];
$post->setCustomThumbnailFromPath($srcPath);
$post->setCustomThumbnailFromPath($srcPath = $suppliedFile['tmp_name']);
LogHelper::log('{user} changed thumb of {post}', ['post' => TextHelper::reprPost($post)]);
}

View file

@ -86,8 +86,9 @@ class TagController
$context->handleExceptions = true;
Access::assert(Privilege::MergeTags);
if (InputHelper::get('submit'))
{
if (!InputHelper::get('submit'))
return;
TagModel::removeUnused();
$suppliedSourceTag = InputHelper::get('source-tag');
@ -104,7 +105,6 @@ class TagController
StatusHelper::success('Tags merged successfully.');
}
}
public function renameAction()
{
@ -113,8 +113,9 @@ class TagController
$context->handleExceptions = true;
Access::assert(Privilege::MergeTags);
if (InputHelper::get('submit'))
{
if (!InputHelper::get('submit'))
return;
TagModel::removeUnused();
$suppliedSourceTag = InputHelper::get('source-tag');
@ -131,7 +132,6 @@ class TagController
StatusHelper::success('Tag renamed successfully.');
}
}
public function massTagRedirectAction()
{
@ -139,8 +139,9 @@ class TagController
$context->viewName = 'tag-list-wrapper';
Access::assert(Privilege::MassTag);
if (InputHelper::get('submit'))
{
if (!InputHelper::get('submit'))
return;
$suppliedOldPage = intval(InputHelper::get('old-page'));
$suppliedOldQuery = InputHelper::get('old-query');
$suppliedQuery = InputHelper::get('query');
@ -155,5 +156,4 @@ class TagController
$params['page'] = $suppliedOldPage;
\Chibi\Util\Url::forward(\Chibi\Router::linkTo(['PostController', 'listAction'], $params));
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,94 @@
<?php
class TransferHelper
{
public static function download($srcUrl, $dstPath, $maxBytes = null)
{
set_time_limit(0);
$srcHandle = fopen($srcUrl, 'rb');
if (!$srcHandle)
throw new SimpleException('Cannot open URL for reading');
$dstHandle = fopen($dstPath, 'w+b');
if (!$dstHandle)
{
fclose($srcHandle);
throw new SimpleException('Cannot open file for writing');
}
try
{
while (!feof($srcHandle))
{
$buffer = fread($srcHandle, 4 * 1024);
if (fwrite($dstHandle, $buffer) === false)
throw new SimpleException('Cannot write into file');
fflush($dstHandle);
if ($maxBytes !== null and ftell($dstHandle) > $maxBytes)
{
fclose($srcHandle);
fclose($dstHandle);
throw new SimpleException(
'File is too big (maximum size: %s)',
TextHelper::useBytesUnits($maxBytes));
}
}
}
finally
{
fclose($srcHandle);
fclose($dstHandle);
chmod($dstPath, 0644);
}
}
public static function moveUpload($srcPath, $dstPath)
{
if (is_uploaded_file($srcPath))
{
move_uploaded_file($srcPath, $dstPath);
}
else
{
//problems with permissions on some systems?
#rename($srcPath, $dstPath);
copy($srcPath, $dstPath);
unlink($srcPath);
}
}
public static function handleUploadErrors($file)
{
switch ($file['error'])
{
case UPLOAD_ERR_OK:
break;
case UPLOAD_ERR_INI_SIZE:
throw new SimpleException('File is too big (maximum size: %s)', ini_get('upload_max_filesize'));
case UPLOAD_ERR_FORM_SIZE:
throw new SimpleException('File is too big than it was allowed in HTML form');
case UPLOAD_ERR_PARTIAL:
throw new SimpleException('File transfer was interrupted');
case UPLOAD_ERR_NO_FILE:
throw new SimpleException('No file was uploaded');
case UPLOAD_ERR_NO_TMP_DIR:
throw new SimpleException('Server misconfiguration error: missing temporary folder');
case UPLOAD_ERR_CANT_WRITE:
throw new SimpleException('Server misconfiguration error: cannot write to disk');
case UPLOAD_ERR_EXTENSION:
throw new SimpleException('Server misconfiguration error: upload was canceled by an extension');
default:
throw new SimpleException('Generic file upload error (id: ' . $file['error'] . ')');
}
if (!is_uploaded_file($file['tmp_name']))
throw new SimpleException('Generic file upload error');
}
}

View file

@ -213,17 +213,18 @@ class PostEntity extends AbstractEntity
throw new SimpleException('Invalid thumbnail type "%s"', $mimeType);
list ($imageWidth, $imageHeight) = getimagesize($srcPath);
if ($imageWidth != $config->browsing->thumbWidth)
throw new SimpleException('Invalid thumbnail width (should be %d)', $config->browsing->thumbWidth);
if ($imageHeight != $config->browsing->thumbHeight)
throw new SimpleException('Invalid thumbnail height (should be %d)', $config->browsing->thumbHeight);
if ($imageWidth != $config->browsing->thumbWidth
or $imageHeight != $config->browsing->thumbHeight)
{
throw new SimpleException(
'Invalid thumbnail size (should be %dx%d)',
$config->browsing->thumbWidth,
$config->browsing->thumbHeight);
}
$dstPath = $this->getThumbCustomPath();
if (is_uploaded_file($srcPath))
move_uploaded_file($srcPath, $dstPath);
else
rename($srcPath, $dstPath);
TransferHelper::moveUpload($srcPath, $dstPath);
}
public function makeThumb($width = null, $height = null)
@ -334,10 +335,11 @@ class PostEntity extends AbstractEntity
return true;
}
public function setContentFromPath($srcPath)
public function setContentFromPath($srcPath, $origName)
{
$this->fileSize = filesize($srcPath);
$this->fileHash = md5_file($srcPath);
$this->origName = $origName;
if ($this->fileSize == 0)
throw new SimpleException('Specified file is empty');
@ -384,10 +386,7 @@ class PostEntity extends AbstractEntity
$dstPath = $this->getFullPath();
if (is_uploaded_file($srcPath))
move_uploaded_file($srcPath, $dstPath);
else
rename($srcPath, $dstPath);
TransferHelper::moveUpload($srcPath, $dstPath);
$thumbPath = $this->getThumbDefaultPath();
if (file_exists($thumbPath))
@ -399,6 +398,8 @@ class PostEntity extends AbstractEntity
if (!preg_match('/^https?:\/\//', $srcUrl))
throw new SimpleException('Invalid URL "%s"', $srcUrl);
$this->origName = $srcUrl;
if (preg_match('/youtube.com\/watch.*?=([a-zA-Z0-9_-]+)/', $srcUrl, $matches))
{
$youtubeId = $matches[1];
@ -425,45 +426,13 @@ class PostEntity extends AbstractEntity
$srcPath = tempnam(sys_get_temp_dir(), 'upload') . '.dat';
//warning: low level sh*t ahead
//download the URL $srcUrl into $srcPath
try
{
$maxBytes = TextHelper::stripBytesUnits(ini_get('upload_max_filesize'));
set_time_limit(0);
$urlFP = fopen($srcUrl, 'rb');
if (!$urlFP)
throw new SimpleException('Cannot open URL for reading');
$srcFP = fopen($srcPath, 'w+b');
if (!$srcFP)
{
fclose($urlFP);
throw new SimpleException('Cannot open file for writing');
}
try
{
while (!feof($urlFP))
{
$buffer = fread($urlFP, 4 * 1024);
if (fwrite($srcFP, $buffer) === false)
throw new SimpleException('Cannot write into file');
fflush($srcFP);
if (ftell($srcFP) > $maxBytes)
{
throw new SimpleException(
'File is too big (maximum size: %s)',
TextHelper::useBytesUnits($maxBytes));
}
}
}
finally
{
fclose($urlFP);
fclose($srcFP);
}
TransferHelper::download($srcUrl, $srcPath, $maxBytes);
try
{
$this->setContentFromPath($srcPath);
$this->setContentFromPath($srcPath, basename($srcUrl));
}
finally
{