Browse code

Add user id to filename

Benjamin Roth authored on24/06/2024 12:08:26
Showing1 changed files
... ...
@@ -134,7 +134,7 @@ class Member
134 134
             static::deleteAvatar($objMember);
135 135
 
136 136
             // Rename file
137
-            $fileName =  self::AVATAR_NAME . '.' . $objFile->extension;
137
+            $fileName =  self::AVATAR_NAME . '_' . $objMember->id . '.' . $objFile->extension;
138 138
 
139 139
             // Move the file to its destination
140 140
             $filesObj = Files::getInstance();
Browse code

Version 1.5 initial commit

Benjamin Roth authored on24/06/2024 12:06:17
Showing1 changed files
1 1
new file mode 100644
... ...
@@ -0,0 +1,252 @@
1
+<?php
2
+
3
+declare(strict_types=1);
4
+
5
+/*
6
+ * This file is part of Oveleon ContaoMemberExtension Bundle.
7
+ *
8
+ * @package     contao-member-extension-bundle
9
+ * @license     MIT
10
+ * @author      Sebastian Zoglowek     <https://github.com/zoglo>
11
+ * @author      Daniele Sciannimanica  <https://github.com/doishub>
12
+ * @author      Fabian Ekert           <https://github.com/eki89>
13
+ * @copyright   Oveleon                <https://www.oveleon.de/>
14
+ */
15
+
16
+namespace Oveleon\ContaoMemberExtensionBundle;
17
+
18
+use Contao\Config;
19
+use Contao\Dbafs;
20
+use Contao\File;
21
+use Contao\Files;
22
+use Contao\FilesModel;
23
+use Contao\FileUpload;
24
+use Contao\MemberModel;
25
+use Contao\StringUtil;
26
+use Contao\System;
27
+use Contao\Validator;
28
+use Exception;
29
+
30
+/**
31
+ * Class Member
32
+ *
33
+ * @property int $avatar UUID of the avatar
34
+ */
35
+class Member
36
+{
37
+    const DEFAULT_PICTURE = 'bundles/contaomemberextension/assets/avatar.png';
38
+    const AVATAR_NAME = 'memberAvatar';
39
+
40
+    /**
41
+     * Process avatar upload for a member
42
+     * @throws Exception
43
+     */
44
+    public static function processAvatar(?MemberModel $objMember, ?array $arrData): void
45
+    {
46
+        if (null === $objMember)
47
+        {
48
+            return;
49
+        }
50
+
51
+        $container = System::getContainer();
52
+        $request = $container->get('request_stack')->getCurrentRequest();
53
+
54
+        if (null === ($file = $request->files->get('avatar')))
55
+        {
56
+            return;
57
+        }
58
+
59
+        $maxlength_kb = FileUpload::getMaxUploadSize();
60
+        //$maxlength_kb_readable = System::getReadableSize($maxlength_kb);
61
+
62
+        // Sanitize the filename
63
+        try {
64
+            $fileName = StringUtil::sanitizeFileName($file->getClientOriginalName());
65
+        } catch (\InvalidArgumentException $e) {
66
+            return; // ToDo: add error message for invalid characters
67
+        }
68
+
69
+        // Invalid file name
70
+        if (!Validator::isValidFileName($fileName))
71
+        {
72
+            return; // ToDo: add error message for invalid characters
73
+        }
74
+
75
+        // File was not uploaded
76
+        if (!$path = $file->getRealPath())
77
+        {
78
+            // ToDo: Add error messages
79
+            /*if ($file['error'] == 1 || $file['error'] == 2) { // Add error message for maximum file size }
80
+            elseif ($file['error'] == 3) { // Add error message for partial upload }
81
+            elseif ($file['error'] > 0) { // Add error message for failed upload }*/
82
+
83
+            return;
84
+        }
85
+
86
+        // File is too big
87
+        if ($file->getSize() > $maxlength_kb)
88
+        {
89
+            return; // ToDo: add error message for maximum file size
90
+        }
91
+
92
+        $objFile = new File($fileName);
93
+
94
+        // File type is not allowed
95
+        if (!\in_array($objFile->extension, $container->getParameter('contao.image.valid_extensions')))
96
+        {
97
+            return; // ToDo: add error message for not allowed file type
98
+        }
99
+
100
+        if (
101
+            ($arrImageSize = getimagesize($path)) &&
102
+            ($arrImageSize[0] > Config::get('imageWidth') || $arrImageSize[1] > Config::get('imageHeight'))
103
+        ) {
104
+            return;
105
+        }
106
+
107
+        // Upload valid file type with no width and height -> svg
108
+
109
+        // Don't upload if no homedir is assigned
110
+        // ToDo: Create homedir?
111
+        if (!$objMember->assignDir || !$objMember->homeDir)
112
+        {
113
+            return; // ToDo: add error message for no homedir
114
+        }
115
+
116
+        $intUploadFolder = $objMember->homeDir;
117
+
118
+        $objUploadFolder = FilesModel::findByUuid($intUploadFolder);
119
+
120
+        // The upload folder could not be found
121
+        if ($objUploadFolder === null)
122
+        {
123
+            throw new Exception("Invalid upload folder ID $intUploadFolder");
124
+        }
125
+
126
+        $strUploadFolder = $objUploadFolder->path;
127
+
128
+        // Store the file if the upload folder exists
129
+        $projectDir = $container->getParameter('kernel.project_dir');
130
+
131
+        if (!!$strUploadFolder & is_dir($projectDir . '/' . $strUploadFolder))
132
+        {
133
+            // Delete existing avatar if it exists
134
+            static::deleteAvatar($objMember);
135
+
136
+            // Rename file
137
+            $fileName =  self::AVATAR_NAME . '.' . $objFile->extension;
138
+
139
+            // Move the file to its destination
140
+            $filesObj = Files::getInstance();
141
+            $filesObj->move_uploaded_file($path, $strUploadFolder . '/' . $fileName);
142
+            $filesObj->chmod($strUploadFolder . '/' . $fileName, 0666 & ~umask());
143
+
144
+            $strFile = $strUploadFolder . '/' . $fileName;
145
+
146
+
147
+            // Generate the DB entries
148
+            if (Dbafs::shouldBeSynchronized($strFile))
149
+            {
150
+                $objModel = FilesModel::findByPath($strFile);
151
+
152
+                if ($objModel === null)
153
+                {
154
+                    $objModel = Dbafs::addResource($strFile);
155
+                }
156
+
157
+                // Update the hash of the target folder
158
+                Dbafs::updateFolderHashes($strUploadFolder);
159
+
160
+                // Update member avatar
161
+                $objMember->avatar = $objModel->uuid;
162
+                $objMember->save();
163
+            }
164
+
165
+            $container->get('monolog.logger.contao.files')->info('File "' . $strUploadFolder . '/' . $fileName . '" has been uploaded');
166
+        }
167
+    }
168
+
169
+    /**
170
+     * Parses an avatar to the template
171
+     */
172
+    public static function parseMemberAvatar(?MemberModel $objMember, &$objTemplate, ?string $imgSize): void
173
+    {
174
+        $container = System::getContainer();
175
+
176
+        $objTemplate->addImage= true;
177
+
178
+        $objTemplate->singleSRC = self::DEFAULT_PICTURE;
179
+        $objTemplate->addFallbackImage = true;
180
+
181
+        $projectDir = $container->getParameter('kernel.project_dir');
182
+
183
+        // Check if member avatar exists
184
+        if (null === $objMember || null === $objMember->avatar || null === ($objFile = FilesModel::findByUuid($objMember->avatar)) || !\is_file($projectDir.'/'. $objFile->path))
185
+        {
186
+            $objFile = !!($uuidDefault = Config::get('defaultAvatar')) ? FilesModel::findByUuid($uuidDefault) : null;
187
+        }
188
+
189
+        // Check if config avatar exists
190
+        if (null === $objFile || !\is_file($projectDir . '/' . $objFile->path))
191
+        {
192
+            return;
193
+        }
194
+
195
+        $objTemplate->addFallbackImage = false;
196
+        $imgSize = $imgSize ?? null;
197
+
198
+        $figureBuilder = $container
199
+            ->get('contao.image.studio')
200
+            ->createFigureBuilder()
201
+            ->from($objFile->path)
202
+            ->setSize($imgSize)
203
+        ;
204
+
205
+        if (null !== ($figure = $figureBuilder->buildIfResourceExists()))
206
+        {
207
+            $figure->applyLegacyTemplateData($objTemplate);
208
+        }
209
+    }
210
+
211
+    /**
212
+     * Gets the url for a member avatar
213
+     */
214
+    public static function getMemberAvatarURL(?MemberModel $objMember): string
215
+    {
216
+        // ToDo: Merge logic with parseMemberAvatar
217
+        $projectDir = System::getContainer()->getParameter('kernel.project_dir');
218
+
219
+        if (null === $objMember || null === $objMember->avatar || null === ($objFile = FilesModel::findByUuid($objMember->avatar)) || !\is_file($projectDir.'/'. $objFile->path))
220
+        {
221
+            $objFile = !!($uuidDefault = Config::get('defaultAvatar')) ? FilesModel::findByUuid($uuidDefault) : null;
222
+        }
223
+
224
+        // Check if config avatar exists
225
+        if (null === $objFile || !\is_file($projectDir . '/' . $objFile->path))
226
+        {
227
+            return self::DEFAULT_PICTURE;
228
+        }
229
+
230
+        return $objFile->path;
231
+    }
232
+
233
+    /**
234
+     * Deletes an avatar
235
+     * @throws Exception
236
+     */
237
+    public static function deleteAvatar(MemberModel $objMember): void
238
+    {
239
+        if (!!$objMember->avatar)
240
+        {
241
+            $objFile = FilesModel::findByUuid($objMember->avatar) ?: '';
242
+            $projectDir = System::getContainer()->getParameter('kernel.project_dir');
243
+
244
+            // Only delete if file exists
245
+            if (!!$objFile && file_exists($projectDir . '/' . $objFile->path))
246
+            {
247
+                $file = new File($objFile->path);
248
+                $file->delete();
249
+            }
250
+        }
251
+    }
252
+}