]> git.mxchange.org Git - friendica.git/blob - src/Module/Media/Attachment/Upload.php
Merge pull request #12591 from MrPetovan/task/2023-licence
[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\Database\Database;
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 Database */
46         private $database;
47
48         /** @var IHandleUserSessions */
49         private $userSession;
50
51         /** @var IManageConfigValues */
52         private $config;
53
54         /** @var SystemMessages */
55         private $systemMessages;
56
57         /** @var bool */
58         private $isJson;
59
60         public function __construct(SystemMessages $systemMessages, IManageConfigValues $config, IHandleUserSessions $userSession, Database $database, 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->database       = $database;
65                 $this->userSession    = $userSession;
66                 $this->config         = $config;
67                 $this->systemMessages = $systemMessages;
68         }
69
70         protected function post(array $request = [])
71         {
72                 if ($this->isJson = !empty($request['response']) && $request['response'] == 'json') {
73                         $this->response->setType(Response::TYPE_JSON, 'application/json');
74                 }
75
76                 $owner = User::getOwnerDataById($this->userSession->getLocalUserId());
77                 if (!$owner) {
78                         $this->logger->warning('Owner not found.', ['uid' => $this->userSession->getLocalUserId()]);
79                         return $this->return(401, $this->t('Invalid request.'));
80                 }
81
82                 if (empty($_FILES['userfile'])) {
83                         $this->logger->warning('No file uploaded (empty userfile)');
84                         return $this->return(401, $this->t('Invalid request.'), true);
85                 }
86
87                 $tempFileName = $_FILES['userfile']['tmp_name'];
88                 $fileName     = basename($_FILES['userfile']['name']);
89                 $fileSize     = intval($_FILES['userfile']['size']);
90                 $maxFileSize  = $this->config->get('system', 'maxfilesize');
91
92                 /*
93                  * Found html code written in text field of form, when trying to upload a
94                  * file with filesize greater than upload_max_filesize. Cause is unknown.
95                  * Then Filesize gets <= 0.
96                  */
97                 if ($fileSize <= 0) {
98                         @unlink($tempFileName);
99                         $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?');
100                         $this->logger->warning($msg, ['fileSize' => $fileSize]);
101                         return $this->return(401, $msg, true);
102                 }
103
104                 if ($maxFileSize && $fileSize > $maxFileSize) {
105                         @unlink($tempFileName);
106                         $msg = $this->t('File exceeds size limit of %s', Strings::formatBytes($maxFileSize));
107                         $this->logger->warning($msg, ['fileSize' => $fileSize]);
108                         return $this->return(401, $msg);
109                 }
110
111                 $newid = Attach::storeFile($tempFileName, $owner['uid'], $fileName, '<' . $owner['id'] . '>');
112
113                 @unlink($tempFileName);
114
115                 if ($newid === false) {
116                         $msg = $this->t('File upload failed.');
117                         $this->logger->warning($msg);
118                         return $this->return(500, $msg);
119                 }
120
121                 if ($this->isJson) {
122                         $content = json_encode(['ok' => true, 'id' => $newid], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
123                 } else {
124                         $content = "\n\n" . '[attachment]' . $newid . '[/attachment]' . "\n";
125                 }
126
127                 return $this->response->addContent($content);
128         }
129
130         /**
131          * @param int    $httpCode
132          * @param string $message
133          * @param bool   $systemMessage
134          * @return void
135          * @throws InternalServerErrorException
136          */
137         private function return(int $httpCode, string $message, bool $systemMessage = false): void
138         {
139                 $this->response->setStatus($httpCode, $message);
140
141                 if ($this->isJson) {
142                         $this->response->addContent(json_encode(['error' => $message], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
143                 } else {
144                         if ($systemMessage) {
145                                 $this->systemMessages->addNotice($message);
146                         }
147
148                         $this->response->addContent($message);
149                 }
150         }
151 }