]> git.mxchange.org Git - friendica.git/blob - src/Module/Media/Attachment/Upload.php
Move Browser & Upload to own namespace
[friendica.git] / src / Module / Media / Attachment / Upload.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2022, 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
78                 if (!$owner) {
79                         $this->logger->warning('Owner not found.', ['uid' => $this->userSession->getLocalUserId()]);
80                         return $this->return(401, $this->t('Invalid request.'));
81                 }
82
83                 if (empty($_FILES['userfile'])) {
84                         $this->logger->warning('No file uploaded (empty userfile)');
85                         return $this->return(401, $this->t('Invalid request.'), true);
86                 }
87
88                 $tempFileName = $_FILES['userfile']['tmp_name'];
89                 $fileName     = basename($_FILES['userfile']['name']);
90                 $fileSize     = intval($_FILES['userfile']['size']);
91                 $maxFileSize  = $this->config->get('system', 'maxfilesize');
92
93                 /*
94                  * Found html code written in text field of form, when trying to upload a
95                  * file with filesize greater than upload_max_filesize. Cause is unknown.
96                  * Then Filesize gets <= 0.
97                  */
98                 if ($fileSize <= 0) {
99                         @unlink($tempFileName);
100                         $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?');
101                         $this->logger->warning($msg, ['fileSize' => $fileSize]);
102                         return $this->return(401, $msg, true);
103                 }
104
105                 if ($maxFileSize && $fileSize > $maxFileSize) {
106                         @unlink($tempFileName);
107                         $msg = $this->t('File exceeds size limit of %s', Strings::formatBytes($maxFileSize));
108                         $this->logger->warning($msg, ['fileSize' => $fileSize]);
109                         return $this->return(401, $msg);
110                 }
111
112                 $newid = Attach::storeFile($tempFileName, $owner['uid'], $fileName, '<' . $owner['id'] . '>');
113
114                 @unlink($tempFileName);
115
116                 if ($newid === false) {
117                         $msg = $this->t('File upload failed.');
118                         $this->logger->warning($msg);
119                         return $this->return(500, $msg);
120                 }
121
122                 if ($this->isJson) {
123                         $content = json_encode(['ok' => true, 'id' => $newid], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
124                 } else {
125                         $content = "\n\n" . '[attachment]' . $newid . '[/attachment]' . "\n";
126                 }
127
128                 return $this->response->addContent($content);
129         }
130
131         /**
132          * @param int    $httpCode
133          * @param string $message
134          * @param bool   $systemMessage
135          * @return void
136          * @throws InternalServerErrorException
137          */
138         private function return(int $httpCode, string $message, bool $systemMessage = false): void
139         {
140                 $this->response->setStatus($httpCode, $message);
141
142                 if ($this->isJson) {
143                         $this->response->addContent(json_encode(['error' => $message], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
144                 } else {
145                         if ($systemMessage) {
146                                 $this->systemMessages->addNotice($message);
147                         }
148
149                         $this->response->addContent($message);
150                 }
151         }
152 }