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,20 +61,20 @@ class AuthController
return; return;
} }
if (InputHelper::get('submit')) if (!InputHelper::get('submit'))
{ return;
$suppliedName = InputHelper::get('name');
$suppliedPassword = InputHelper::get('password');
$dbUser = self::tryLogin($suppliedName, $suppliedPassword);
if (InputHelper::get('remember')) $suppliedName = InputHelper::get('name');
{ $suppliedPassword = InputHelper::get('password');
$token = implode('|', [base64_encode($suppliedName), base64_encode($suppliedPassword)]); $dbUser = self::tryLogin($suppliedName, $suppliedPassword);
setcookie('auth', TextHelper::encrypt($token), time() + 365 * 24 * 3600, '/');
} if (InputHelper::get('remember'))
StatusHelper::success(); {
self::redirectAfterLog(); $token = implode('|', [base64_encode($suppliedName), base64_encode($suppliedPassword)]);
setcookie('auth', TextHelper::encrypt($token), time() + 365 * 24 * 3600, '/');
} }
StatusHelper::success();
self::redirectAfterLog();
} }
public function logoutAction() public function logoutAction()

View file

@ -40,28 +40,28 @@ class CommentController
$post = PostModel::findById($postId); $post = PostModel::findById($postId);
$context->transport->post = $post; $context->transport->post = $post;
if (InputHelper::get('submit')) if (!InputHelper::get('submit'))
return;
$text = InputHelper::get('text');
$text = CommentModel::validateText($text);
$comment = CommentModel::spawn();
$comment->setPost($post);
if ($context->loggedIn)
$comment->setCommenter($context->user);
else
$comment->setCommenter(null);
$comment->commentDate = time();
$comment->text = $text;
if (InputHelper::get('sender') != 'preview')
{ {
$text = InputHelper::get('text'); CommentModel::save($comment);
$text = CommentModel::validateText($text); LogHelper::log('{user} commented on {post}', ['post' => TextHelper::reprPost($post->id)]);
$comment = CommentModel::spawn();
$comment->setPost($post);
if ($context->loggedIn)
$comment->setCommenter($context->user);
else
$comment->setCommenter(null);
$comment->commentDate = time();
$comment->text = $text;
if (InputHelper::get('sender') != 'preview')
{
CommentModel::save($comment);
LogHelper::log('{user} commented on {post}', ['post' => TextHelper::reprPost($post->id)]);
}
$context->transport->textPreview = $comment->getText();
StatusHelper::success();
} }
$context->transport->textPreview = $comment->getText();
StatusHelper::success();
} }
public function editAction($id) public function editAction($id)
@ -74,22 +74,22 @@ class CommentController
Privilege::EditComment, Privilege::EditComment,
Access::getIdentity($comment->getCommenter())); Access::getIdentity($comment->getCommenter()));
if (InputHelper::get('submit')) if (!InputHelper::get('submit'))
return;
$text = InputHelper::get('text');
$text = CommentModel::validateText($text);
$comment->text = $text;
if (InputHelper::get('sender') != 'preview')
{ {
$text = InputHelper::get('text'); CommentModel::save($comment);
$text = CommentModel::validateText($text); LogHelper::log('{user} edited comment in {post}', [
'post' => TextHelper::reprPost($comment->getPost())]);
$comment->text = $text;
if (InputHelper::get('sender') != 'preview')
{
CommentModel::save($comment);
LogHelper::log('{user} edited comment in {post}', [
'post' => TextHelper::reprPost($comment->getPost())]);
}
$context->transport->textPreview = $comment->getText();
StatusHelper::success();
} }
$context->transport->textPreview = $comment->getText();
StatusHelper::success();
} }
public function deleteAction($id) public function deleteAction($id)

View file

@ -1,41 +1,6 @@
<?php <?php
class PostController 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) public function listAction($query = null, $page = 1, $source = 'posts', $additionalInfo = null)
{ {
$context = getContext(); $context = getContext();
@ -98,45 +63,45 @@ class PostController
$post = PostModel::findByIdOrName($id); $post = PostModel::findByIdOrName($id);
$context->transport->post = $post; $context->transport->post = $post;
if (InputHelper::get('submit')) if (!InputHelper::get('submit'))
return;
Access::assert(
Privilege::MassTag,
Access::getIdentity($post->getUploader()));
$tags = $post->getTags();
if (!$enable)
{ {
Access::assert( foreach ($tags as $i => $tag)
Privilege::MassTag, if ($tag->name == $tagName)
Access::getIdentity($post->getUploader())); unset($tags[$i]);
$tags = $post->getTags(); LogHelper::log('{user} untagged {post} with {tag}', [
'post' => TextHelper::reprPost($post),
if (!$enable) 'tag' => TextHelper::reprTag($tag)]);
{
foreach ($tags as $i => $tag)
if ($tag->name == $tagName)
unset($tags[$i]);
LogHelper::log('{user} untagged {post} with {tag}', [
'post' => TextHelper::reprPost($post),
'tag' => TextHelper::reprTag($tag)]);
}
elseif ($enable)
{
$tag = TagModel::findByName($tagName, false);
if ($tag === null)
{
$tag = TagModel::spawn();
$tag->name = $tagName;
TagModel::save($tag);
}
$tags []= $tag;
LogHelper::log('{user} tagged {post} with {tag}', [
'post' => TextHelper::reprPost($post),
'tag' => TextHelper::reprTag($tag)]);
}
$post->setTags($tags);
PostModel::save($post);
StatusHelper::success();
} }
elseif ($enable)
{
$tag = TagModel::findByName($tagName, false);
if ($tag === null)
{
$tag = TagModel::spawn();
$tag->name = $tagName;
TagModel::save($tag);
}
$tags []= $tag;
LogHelper::log('{user} tagged {post} with {tag}', [
'post' => TextHelper::reprPost($post),
'tag' => TextHelper::reprTag($tag)]);
}
$post->setTags($tags);
PostModel::save($post);
StatusHelper::success();
} }
public function favoritesAction($page = 1) public function favoritesAction($page = 1)
@ -161,49 +126,49 @@ class PostController
if (getConfig()->registration->needEmailForUploading) if (getConfig()->registration->needEmailForUploading)
Access::assertEmailConfirmation(); Access::assertEmailConfirmation();
if (InputHelper::get('submit')) if (!InputHelper::get('submit'))
return;
\Chibi\Database::transaction(function() use ($context)
{ {
\Chibi\Database::transaction(function() use ($context) $post = PostModel::spawn();
{ LogHelper::bufferChanges();
$post = PostModel::spawn();
LogHelper::bufferChanges();
//basic stuff //basic stuff
$anonymous = InputHelper::get('anonymous'); $anonymous = InputHelper::get('anonymous');
if ($context->loggedIn and !$anonymous) if ($context->loggedIn and !$anonymous)
$post->setUploader($context->user); $post->setUploader($context->user);
//store the post to get the ID in the logs //store the post to get the ID in the logs
PostModel::forgeId($post); PostModel::forgeId($post);
//do the edits //do the edits
$this->doEdit($post, true); $this->doEdit($post, true);
//this basically means that user didn't specify file nor url //this basically means that user didn't specify file nor url
if (empty($post->type)) if (empty($post->type))
throw new SimpleException('No post type detected; upload faled'); throw new SimpleException('No post type detected; upload faled');
//clean edit log //clean edit log
LogHelper::setBuffer([]); LogHelper::setBuffer([]);
//log //log
$fmt = ($anonymous and !getConfig()->misc->logAnonymousUploads) $fmt = ($anonymous and !getConfig()->misc->logAnonymousUploads)
? '{anon}' ? '{anon}'
: '{user}'; : '{user}';
$fmt .= ' added {post} (tags: {tags}, safety: {safety}, source: {source})'; $fmt .= ' added {post} (tags: {tags}, safety: {safety}, source: {source})';
LogHelper::log($fmt, [ LogHelper::log($fmt, [
'post' => TextHelper::reprPost($post), 'post' => TextHelper::reprPost($post),
'tags' => TextHelper::reprTags($post->getTags()), 'tags' => TextHelper::reprTags($post->getTags()),
'safety' => PostSafety::toString($post->safety), 'safety' => PostSafety::toString($post->safety),
'source' => $post->source]); 'source' => $post->source]);
//finish //finish
LogHelper::flush(); LogHelper::flush();
PostModel::save($post); PostModel::save($post);
}); });
StatusHelper::success(); StatusHelper::success();
}
} }
public function editAction($id) public function editAction($id)
@ -212,21 +177,21 @@ class PostController
$post = PostModel::findByIdOrName($id); $post = PostModel::findByIdOrName($id);
$context->transport->post = $post; $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');
LogHelper::bufferChanges(); $editToken = InputHelper::get('edit-token');
$this->doEdit($post, false); if ($editToken != $post->getEditToken())
LogHelper::flush(); throw new SimpleException('This post was already edited by someone else in the meantime');
PostModel::save($post); LogHelper::bufferChanges();
TagModel::removeUnused(); $this->doEdit($post, false);
LogHelper::flush();
StatusHelper::success(); PostModel::save($post);
} TagModel::removeUnused();
StatusHelper::success();
} }
public function flagAction($id) public function flagAction($id)
@ -234,19 +199,19 @@ class PostController
$post = PostModel::findByIdOrName($id); $post = PostModel::findByIdOrName($id);
Access::assert(Privilege::FlagPost, Access::getIdentity($post->getUploader())); 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', []); $key = TextHelper::reprPost($post);
if (in_array($key, $flagged))
throw new SimpleException('You already flagged this post');
$flagged []= $key;
SessionHelper::set('flagged', $flagged);
LogHelper::log('{user} flagged {post} for moderator attention', ['post' => TextHelper::reprPost($post)]); $flagged = SessionHelper::get('flagged', []);
StatusHelper::success(); if (in_array($key, $flagged))
} throw new SimpleException('You already flagged this post');
$flagged []= $key;
SessionHelper::set('flagged', $flagged);
LogHelper::log('{user} flagged {post} for moderator attention', ['post' => TextHelper::reprPost($post)]);
StatusHelper::success();
} }
public function hideAction($id) public function hideAction($id)
@ -254,14 +219,14 @@ class PostController
$post = PostModel::findByIdOrName($id); $post = PostModel::findByIdOrName($id);
Access::assert(Privilege::HidePost, Access::getIdentity($post->getUploader())); 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)]); $post->setHidden(true);
StatusHelper::success(); PostModel::save($post);
}
LogHelper::log('{user} hidden {post}', ['post' => TextHelper::reprPost($post)]);
StatusHelper::success();
} }
public function unhideAction($id) public function unhideAction($id)
@ -269,14 +234,14 @@ class PostController
$post = PostModel::findByIdOrName($id); $post = PostModel::findByIdOrName($id);
Access::assert(Privilege::HidePost, Access::getIdentity($post->getUploader())); 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)]); $post->setHidden(false);
StatusHelper::success(); PostModel::save($post);
}
LogHelper::log('{user} unhidden {post}', ['post' => TextHelper::reprPost($post)]);
StatusHelper::success();
} }
public function deleteAction($id) public function deleteAction($id)
@ -284,13 +249,13 @@ class PostController
$post = PostModel::findByIdOrName($id); $post = PostModel::findByIdOrName($id);
Access::assert(Privilege::DeletePost, Access::getIdentity($post->getUploader())); 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)]); PostModel::remove($post);
StatusHelper::success();
} LogHelper::log('{user} deleted {post}', ['post' => TextHelper::reprPost($id)]);
StatusHelper::success();
} }
public function addFavoriteAction($id) public function addFavoriteAction($id)
@ -299,15 +264,15 @@ class PostController
$post = PostModel::findByIdOrName($id); $post = PostModel::findByIdOrName($id);
Access::assert(Privilege::FavoritePost, Access::getIdentity($post->getUploader())); 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::updateUserScore($context->user, $post, 1); if (!$context->loggedIn)
UserModel::addToUserFavorites($context->user, $post); throw new SimpleException('Not logged in');
StatusHelper::success();
} UserModel::updateUserScore($context->user, $post, 1);
UserModel::addToUserFavorites($context->user, $post);
StatusHelper::success();
} }
public function removeFavoriteAction($id) public function removeFavoriteAction($id)
@ -316,14 +281,14 @@ class PostController
$post = PostModel::findByIdOrName($id); $post = PostModel::findByIdOrName($id);
Access::assert(Privilege::FavoritePost, Access::getIdentity($post->getUploader())); 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); if (!$context->loggedIn)
StatusHelper::success(); throw new SimpleException('Not logged in');
}
UserModel::removeFromUserFavorites($context->user, $post);
StatusHelper::success();
} }
public function scoreAction($id, $score) public function scoreAction($id, $score)
@ -332,14 +297,14 @@ class PostController
$post = PostModel::findByIdOrName($id); $post = PostModel::findByIdOrName($id);
Access::assert(Privilege::ScorePost, Access::getIdentity($post->getUploader())); 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); if (!$context->loggedIn)
StatusHelper::success(); throw new SimpleException('Not logged in');
}
UserModel::updateUserScore($context->user, $post, $score);
StatusHelper::success();
} }
public function featureAction($id) public function featureAction($id)
@ -457,39 +422,8 @@ class PostController
$context->transport->filePath = $path; $context->transport->filePath = $path;
} }
private function doEdit($post, $isNew) 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 */ /* safety */
$suppliedSafety = InputHelper::get('safety'); $suppliedSafety = InputHelper::get('safety');
if ($suppliedSafety !== null) 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 */ /* thumbnail */
if (!empty($_FILES['thumb']['name'])) if (!empty($_FILES['thumb']['name']))
{ {
@ -587,10 +547,9 @@ class PostController
Access::assert(Privilege::EditPostThumb, Access::getIdentity($post->getUploader())); Access::assert(Privilege::EditPostThumb, Access::getIdentity($post->getUploader()));
$suppliedFile = $_FILES['thumb']; $suppliedFile = $_FILES['thumb'];
self::handleUploadErrors($suppliedFile); TransferHelper::handleUploadErrors($suppliedFile);
$srcPath = $suppliedFile['tmp_name']; $post->setCustomThumbnailFromPath($srcPath = $suppliedFile['tmp_name']);
$post->setCustomThumbnailFromPath($srcPath);
LogHelper::log('{user} changed thumb of {post}', ['post' => TextHelper::reprPost($post)]); LogHelper::log('{user} changed thumb of {post}', ['post' => TextHelper::reprPost($post)]);
} }

View file

@ -86,24 +86,24 @@ class TagController
$context->handleExceptions = true; $context->handleExceptions = true;
Access::assert(Privilege::MergeTags); Access::assert(Privilege::MergeTags);
if (InputHelper::get('submit')) if (!InputHelper::get('submit'))
{ return;
TagModel::removeUnused();
$suppliedSourceTag = InputHelper::get('source-tag'); TagModel::removeUnused();
$suppliedSourceTag = TagModel::validateTag($suppliedSourceTag);
$suppliedTargetTag = InputHelper::get('target-tag'); $suppliedSourceTag = InputHelper::get('source-tag');
$suppliedTargetTag = TagModel::validateTag($suppliedTargetTag); $suppliedSourceTag = TagModel::validateTag($suppliedSourceTag);
TagModel::merge($suppliedSourceTag, $suppliedTargetTag); $suppliedTargetTag = InputHelper::get('target-tag');
$suppliedTargetTag = TagModel::validateTag($suppliedTargetTag);
LogHelper::log('{user} merged {source} with {target}', [ TagModel::merge($suppliedSourceTag, $suppliedTargetTag);
'source' => TextHelper::reprTag($suppliedSourceTag),
'target' => TextHelper::reprTag($suppliedTargetTag)]);
StatusHelper::success('Tags merged successfully.'); LogHelper::log('{user} merged {source} with {target}', [
} 'source' => TextHelper::reprTag($suppliedSourceTag),
'target' => TextHelper::reprTag($suppliedTargetTag)]);
StatusHelper::success('Tags merged successfully.');
} }
public function renameAction() public function renameAction()
@ -113,24 +113,24 @@ class TagController
$context->handleExceptions = true; $context->handleExceptions = true;
Access::assert(Privilege::MergeTags); Access::assert(Privilege::MergeTags);
if (InputHelper::get('submit')) if (!InputHelper::get('submit'))
{ return;
TagModel::removeUnused();
$suppliedSourceTag = InputHelper::get('source-tag'); TagModel::removeUnused();
$suppliedSourceTag = TagModel::validateTag($suppliedSourceTag);
$suppliedTargetTag = InputHelper::get('target-tag'); $suppliedSourceTag = InputHelper::get('source-tag');
$suppliedTargetTag = TagModel::validateTag($suppliedTargetTag); $suppliedSourceTag = TagModel::validateTag($suppliedSourceTag);
TagModel::rename($suppliedSourceTag, $suppliedTargetTag); $suppliedTargetTag = InputHelper::get('target-tag');
$suppliedTargetTag = TagModel::validateTag($suppliedTargetTag);
LogHelper::log('{user} renamed {source} to {target}', [ TagModel::rename($suppliedSourceTag, $suppliedTargetTag);
'source' => TextHelper::reprTag($suppliedSourceTag),
'target' => TextHelper::reprTag($suppliedTargetTag)]);
StatusHelper::success('Tag renamed successfully.'); LogHelper::log('{user} renamed {source} to {target}', [
} 'source' => TextHelper::reprTag($suppliedSourceTag),
'target' => TextHelper::reprTag($suppliedTargetTag)]);
StatusHelper::success('Tag renamed successfully.');
} }
public function massTagRedirectAction() public function massTagRedirectAction()
@ -139,21 +139,21 @@ class TagController
$context->viewName = 'tag-list-wrapper'; $context->viewName = 'tag-list-wrapper';
Access::assert(Privilege::MassTag); 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');
$suppliedTag = InputHelper::get('tag');
$params = [ $suppliedOldPage = intval(InputHelper::get('old-page'));
'source' => 'mass-tag', $suppliedOldQuery = InputHelper::get('old-query');
'query' => $suppliedQuery ?: ' ', $suppliedQuery = InputHelper::get('query');
'additionalInfo' => $suppliedTag ? TagModel::validateTag($suppliedTag) : '', $suppliedTag = InputHelper::get('tag');
];
if ($suppliedOldPage != 0 and $suppliedOldQuery == $suppliedQuery) $params = [
$params['page'] = $suppliedOldPage; 'source' => 'mass-tag',
\Chibi\Util\Url::forward(\Chibi\Router::linkTo(['PostController', 'listAction'], $params)); 'query' => $suppliedQuery ?: ' ',
} 'additionalInfo' => $suppliedTag ? TagModel::validateTag($suppliedTag) : '',
];
if ($suppliedOldPage != 0 and $suppliedOldQuery == $suppliedQuery)
$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); throw new SimpleException('Invalid thumbnail type "%s"', $mimeType);
list ($imageWidth, $imageHeight) = getimagesize($srcPath); list ($imageWidth, $imageHeight) = getimagesize($srcPath);
if ($imageWidth != $config->browsing->thumbWidth) if ($imageWidth != $config->browsing->thumbWidth
throw new SimpleException('Invalid thumbnail width (should be %d)', $config->browsing->thumbWidth); or $imageHeight != $config->browsing->thumbHeight)
if ($imageHeight != $config->browsing->thumbHeight) {
throw new SimpleException('Invalid thumbnail height (should be %d)', $config->browsing->thumbHeight); throw new SimpleException(
'Invalid thumbnail size (should be %dx%d)',
$config->browsing->thumbWidth,
$config->browsing->thumbHeight);
}
$dstPath = $this->getThumbCustomPath(); $dstPath = $this->getThumbCustomPath();
if (is_uploaded_file($srcPath)) TransferHelper::moveUpload($srcPath, $dstPath);
move_uploaded_file($srcPath, $dstPath);
else
rename($srcPath, $dstPath);
} }
public function makeThumb($width = null, $height = null) public function makeThumb($width = null, $height = null)
@ -334,10 +335,11 @@ class PostEntity extends AbstractEntity
return true; return true;
} }
public function setContentFromPath($srcPath) public function setContentFromPath($srcPath, $origName)
{ {
$this->fileSize = filesize($srcPath); $this->fileSize = filesize($srcPath);
$this->fileHash = md5_file($srcPath); $this->fileHash = md5_file($srcPath);
$this->origName = $origName;
if ($this->fileSize == 0) if ($this->fileSize == 0)
throw new SimpleException('Specified file is empty'); throw new SimpleException('Specified file is empty');
@ -384,10 +386,7 @@ class PostEntity extends AbstractEntity
$dstPath = $this->getFullPath(); $dstPath = $this->getFullPath();
if (is_uploaded_file($srcPath)) TransferHelper::moveUpload($srcPath, $dstPath);
move_uploaded_file($srcPath, $dstPath);
else
rename($srcPath, $dstPath);
$thumbPath = $this->getThumbDefaultPath(); $thumbPath = $this->getThumbDefaultPath();
if (file_exists($thumbPath)) if (file_exists($thumbPath))
@ -399,6 +398,8 @@ class PostEntity extends AbstractEntity
if (!preg_match('/^https?:\/\//', $srcUrl)) if (!preg_match('/^https?:\/\//', $srcUrl))
throw new SimpleException('Invalid URL "%s"', $srcUrl); throw new SimpleException('Invalid URL "%s"', $srcUrl);
$this->origName = $srcUrl;
if (preg_match('/youtube.com\/watch.*?=([a-zA-Z0-9_-]+)/', $srcUrl, $matches)) if (preg_match('/youtube.com\/watch.*?=([a-zA-Z0-9_-]+)/', $srcUrl, $matches))
{ {
$youtubeId = $matches[1]; $youtubeId = $matches[1];
@ -425,45 +426,13 @@ class PostEntity extends AbstractEntity
$srcPath = tempnam(sys_get_temp_dir(), 'upload') . '.dat'; $srcPath = tempnam(sys_get_temp_dir(), 'upload') . '.dat';
//warning: low level sh*t ahead
//download the URL $srcUrl into $srcPath
$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 try
{ {
while (!feof($urlFP)) $maxBytes = TextHelper::stripBytesUnits(ini_get('upload_max_filesize'));
{
$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);
}
try TransferHelper::download($srcUrl, $srcPath, $maxBytes);
{
$this->setContentFromPath($srcPath); $this->setContentFromPath($srcPath, basename($srcUrl));
} }
finally finally
{ {