]> git.mxchange.org Git - friendica.git/blob - src/Module/Media/Attachment/Upload.php
spelling: one
[friendica.git] / src / Module / Media / Attachment / Upload.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2023, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Module\Media\Attachment;
23
24 use Friendica\App;
25 use Friendica\Core\Config\Capability\IManageConfigValues;
26 use Friendica\Core\L10n;
27 use Friendica\Core\Session\Capability\IHandleUserSessions;
28 use Friendica\Core\System;
29 use Friendica\Model\Attach;
30 use Friendica\Model\User;
31 use Friendica\Module\Response;
32 use Friendica\Navigation\SystemMessages;
33 use Friendica\Network\HTTPException\InternalServerErrorException;
34 use Friendica\Util\Profiler;
35 use Friendica\Util\Strings;
36 use Psr\Log\LoggerInterface;
37
38 /**
39  * Asynchronous attachment upload module
40  *
41  * Only used as the target action of the AjaxUpload JavaScript library
42  */
43 class Upload extends \Friendica\BaseModule
44 {
45         /** @var IHandleUserSessions */
46         private $userSession;
47
48         /** @var IManageConfigValues */
49         private $config;
50
51         /** @var SystemMessages */
52         private $systemMessages;
53
54         /** @var bool */
55         private $isJson;
56
57         /** @var App\Page */
58         private $page;
59
60         public function __construct(App\Page $page, SystemMessages $systemMessages, IManageConfigValues $config, IHandleUserSessions $userSession, L10n $l10n, App\BaseURL $baseUrl, App\Arguments $args, LoggerInterface $logger, Profiler $profiler, Response $response, array $server, array $parameters = [])
61         {
62                 parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
63
64                 $this->userSession    = $userSession;
65                 $this->config         = $config;
66                 $this->systemMessages = $systemMessages;
67                 $this->page           = $page;
68         }
69
70         protected function post(array $request = [])
71         {
72                 $this->isJson = !empty($request['response']) && $request['response'] == 'json';
73
74                 $owner = User::getOwnerDataById($this->userSession->getLocalUserId());
75                 if (!$owner) {
76                         $this->logger->warning('Owner not found.', ['uid' => $this->userSession->getLocalUserId()]);
77                         $this->return(401, $this->t('Invalid request.'));
78                 }
79
80                 if (empty($_FILES['userfile'])) {
81                         $this->logger->warning('No file uploaded (empty userfile)');
82                         $this->return(401, $this->t('Invalid request.'), true);
83                 }
84
85                 $tempFileName = $_FILES['userfile']['tmp_name'];
86                 $fileName     = basename($_FILES['userfile']['name']);
87                 $fileSize     = intval($_FILES['userfile']['size']);
88                 $maxFileSize  = $this->config->get('system', 'maxfilesize');
89
90                 /*
91                  * Found html code written in text field of form, when trying to upload a
92                  * file with filesize greater than upload_max_filesize. Cause is unknown.
93                  * Then Filesize gets <= 0.
94                  */
95                 if ($fileSize <= 0) {
96                         @unlink($tempFileName);
97                         $msg = $this->t('Sorry, maybe your upload is bigger than the PHP configuration allows') . '<br />' . $this->t('Or - did you try to upload an empty file?');
98                         $this->logger->warning($msg, ['fileSize' => $fileSize]);
99                         $this->return(401, $msg, true);
100                 }
101
102                 if ($maxFileSize && $fileSize > $maxFileSize) {
103                         @unlink($tempFileName);
104                         $msg = $this->t('File exceeds size limit of %s', Strings::formatBytes($maxFileSize));
105                         $this->logger->warning($msg, ['fileSize' => $fileSize]);
106                         $this->return(401, $msg);
107                 }
108
109                 $newid = Attach::storeFile($tempFileName, $owner['uid'], $fileName, '<' . $owner['id'] . '>');
110
111                 @unlink($tempFileName);
112
113                 if ($newid === false) {
114                         $msg = $this->t('File upload failed.');
115                         $this->logger->warning($msg);
116                         $this->return(500, $msg);
117                 }
118
119                 if ($this->isJson) {
120                         $content = $newid;
121                 } else {
122                         $content = "\n\n" . '[attachment]' . $newid . '[/attachment]' . "\n";
123                 }
124
125                 $this->return(200, $content);
126         }
127
128         /**
129          * @param int    $httpCode
130          * @param string $message
131          * @param bool   $systemMessage
132          * @return void
133          * @throws InternalServerErrorException
134          */
135         private function return(int $httpCode, string $message, bool $systemMessage = false): void
136         {
137                 if ($this->isJson) {
138                         $message = $httpCode >= 400 ? ['error' => $message] : ['ok' => true, 'id' => $message];
139                         $this->response->setType(Response::TYPE_JSON, 'application/json');
140                         $this->response->addContent(json_encode($message, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
141                 } else {
142                         if ($systemMessage) {
143                                 $this->systemMessages->addNotice($message);
144                         }
145
146                         if ($httpCode >= 400) {
147                                 $this->response->setStatus($httpCode, $message);
148                         }
149
150                         $this->response->addContent($message);
151                 }
152
153                 $this->page->exit($this->response->generate());
154                 System::exit();
155         }
156 }