Subversion Repositories oidplus

Rev

Rev 1180 | Rev 1199 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
635 daniel-mar 1
<?php
2
 
3
/*
4
 * OIDplus 2.0
1086 daniel-mar 5
 * Copyright 2019 - 2023 Daniel Marschall, ViaThinkSoft
635 daniel-mar 6
 *
7
 * Licensed under the Apache License, Version 2.0 (the "License");
8
 * you may not use this file except in compliance with the License.
9
 * You may obtain a copy of the License at
10
 *
11
 *     http://www.apache.org/licenses/LICENSE-2.0
12
 *
13
 * Unless required by applicable law or agreed to in writing, software
14
 * distributed under the License is distributed on an "AS IS" BASIS,
15
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
 * See the License for the specific language governing permissions and
17
 * limitations under the License.
18
 */
19
 
1050 daniel-mar 20
namespace ViaThinkSoft\OIDplus;
635 daniel-mar 21
 
1086 daniel-mar 22
// phpcs:disable PSR1.Files.SideEffects
23
\defined('INSIDE_OIDPLUS') or die;
24
// phpcs:enable PSR1.Files.SideEffects
25
 
1131 daniel-mar 26
class OIDplusPagePublicAttachments extends OIDplusPagePluginPublic
27
        implements INTF_OID_1_3_6_1_4_1_37476_2_5_2_3_2, /* modifyContent */
28
                   INTF_OID_1_3_6_1_4_1_37476_2_5_2_3_3, /* beforeObject*, afterObject* */
1180 daniel-mar 29
                   INTF_OID_1_3_6_1_4_1_37476_2_5_2_3_4, /* whois*Attributes */
30
                   INTF_OID_1_3_6_1_4_1_37476_2_5_2_3_8  /* getNotifications */
1131 daniel-mar 31
{
635 daniel-mar 32
 
1130 daniel-mar 33
        /**
34
         * @param string $dir
1116 daniel-mar 35
         * @return void
36
         * @throws OIDplusException
37
         */
1130 daniel-mar 38
        private static function checkUploadDir(string $dir) {
635 daniel-mar 39
                if (!is_dir($dir)) {
40
                        throw new OIDplusException(_L('The attachment directory "%1" is not existing.', $dir));
41
                }
42
 
43
                $realdir = realpath($dir);
44
                if ($realdir === false) {
45
                        throw new OIDplusException(_L('The attachment directory "%1" cannot be resolved (realpath).', $dir));
46
                }
47
 
1175 daniel-mar 48
                // Check for critical directories
635 daniel-mar 49
                if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') {
50
                        if (self::isCriticalLinuxDirectory($realdir)) {
51
                                throw new OIDplusException(_L('The attachment directory must not be inside a critical system directory!'));
52
                        }
53
                } else {
54
                        if (self::isCriticalWindowsDirectory($realdir)) {
55
                                throw new OIDplusException(_L('The attachment directory must not be inside a critical system directory!'));
56
                        }
57
                }
58
        }
59
 
1116 daniel-mar 60
        /**
1130 daniel-mar 61
         * @param string $dir
1116 daniel-mar 62
         * @return bool
63
         */
1130 daniel-mar 64
        private static function isCriticalWindowsDirectory(string $dir): bool {
1175 daniel-mar 65
                $dir = rtrim(str_replace('/', '\\', $dir),'\\').'\\';
66
                $windir = isset($_SERVER['SystemRoot']) ? rtrim($_SERVER['SystemRoot'],'\\').'\\' : 'C:\\Windows\\';
635 daniel-mar 67
                if (stripos($dir,$windir) === 0) return true;
68
                return false;
69
        }
70
 
1116 daniel-mar 71
        /**
1130 daniel-mar 72
         * @param string $dir
1116 daniel-mar 73
         * @return bool
74
         */
1130 daniel-mar 75
        private static function isCriticalLinuxDirectory(string $dir): bool {
635 daniel-mar 76
                if ($dir == '/') return true;
1175 daniel-mar 77
                $dir = rtrim($dir,'/').'/';
635 daniel-mar 78
                if (strpos($dir,'/bin/') === 0) return true;
79
                if (strpos($dir,'/boot/') === 0) return true;
80
                if (strpos($dir,'/dev/') === 0) return true;
81
                if (strpos($dir,'/etc/') === 0) return true;
82
                if (strpos($dir,'/lib') === 0) return true;
83
                if (strpos($dir,'/opt/') === 0) return true;
84
                if (strpos($dir,'/proc/') === 0) return true;
85
                if (strpos($dir,'/root/') === 0) return true;
86
                if (strpos($dir,'/run/') === 0) return true;
87
                if (strpos($dir,'/sbin/') === 0) return true;
88
                if (strpos($dir,'/sys/') === 0) return true;
89
                if (strpos($dir,'/tmp/') === 0) return true;
90
                if (strpos($dir,'/usr/bin/') === 0) return true;
91
                if (strpos($dir,'/usr/include/') === 0) return true;
92
                if (strpos($dir,'/usr/lib') === 0) return true;
93
                if (strpos($dir,'/usr/sbin/') === 0) return true;
94
                if (strpos($dir,'/usr/src/') === 0) return true;
95
                if (strpos($dir,'/var/cache/') === 0) return true;
96
                if (strpos($dir,'/var/lib') === 0) return true;
97
                if (strpos($dir,'/var/lock/') === 0) return true;
98
                if (strpos($dir,'/var/log/') === 0) return true;
99
                if (strpos($dir,'/var/mail/') === 0) return true;
100
                if (strpos($dir,'/var/opt/') === 0) return true;
101
                if (strpos($dir,'/var/run/') === 0) return true;
102
                if (strpos($dir,'/var/spool/') === 0) return true;
103
                if (strpos($dir,'/var/tmp/') === 0) return true;
104
                return false;
105
        }
106
 
1116 daniel-mar 107
        /**
108
         * @return string
109
         * @throws OIDplusException
110
         */
1180 daniel-mar 111
        protected static function getUploadBaseDir(): string {
635 daniel-mar 112
                // Get base path
113
                $cfg = OIDplus::config()->getValue('attachment_upload_dir', '');
114
                $cfg = trim($cfg);
115
                if ($cfg === '') {
116
                        $basepath = OIDplus::localpath() . 'userdata' . DIRECTORY_SEPARATOR . 'attachments';
117
                } else {
118
                        $basepath = $cfg;
119
                }
1180 daniel-mar 120
                return $basepath;
121
        }
635 daniel-mar 122
 
1180 daniel-mar 123
        /**
124
         * @param string|null $id
125
         * @return string
126
         * @throws OIDplusException
127
         */
128
        public static function getUploadDir(string $id=null): string {
129
                $basepath = self::getUploadBaseDir();
130
 
635 daniel-mar 131
                try {
132
                        self::checkUploadDir($basepath);
1050 daniel-mar 133
                } catch (\Exception $e) {
635 daniel-mar 134
                        $error = _L('This functionality is not available due to a misconfiguration');
135
                        if (OIDplus::authUtils()->isAdminLoggedIn()) {
136
                                $error .= ': '.$e->getMessage();
137
                        } else {
138
                                $error .= '. '._L('Please notify the system administrator. After they log-in, they can see the reason at this place.');
139
                        }
140
                        throw new OIDplusException($error);
141
                }
142
 
143
                // Get object-specific path
144
                if (!is_null($id)) {
145
                        $obj = OIDplusObject::parse($id);
1116 daniel-mar 146
                        if (!$obj) throw new OIDplusException(_L('Invalid object "%1"',$id));
635 daniel-mar 147
 
148
                        $path_v1 = $basepath . DIRECTORY_SEPARATOR . $obj->getLegacyDirectoryName();
149
                        $path_v1_bug = $basepath . $obj->getLegacyDirectoryName();
150
                        $path_v2 = $basepath . DIRECTORY_SEPARATOR . $obj->getDirectoryName();
151
 
152
                        if (is_dir($path_v1)) return $path_v1; // backwards compatibility
153
                        if (is_dir($path_v1_bug)) return $path_v1_bug; // backwards compatibility
154
                        return $path_v2;
155
                } else {
156
                        return $basepath;
157
                }
158
        }
159
 
1116 daniel-mar 160
        /**
161
         * @return mixed|null
162
         * @throws OIDplusException
163
         */
635 daniel-mar 164
        private function raMayDelete() {
165
                return OIDplus::config()->getValue('attachments_allow_ra_delete', 0);
166
        }
167
 
1116 daniel-mar 168
        /**
169
         * @return mixed|null
170
         * @throws OIDplusException
171
         */
635 daniel-mar 172
        private function raMayUpload() {
173
                return OIDplus::config()->getValue('attachments_allow_ra_upload', 0);
174
        }
175
 
1116 daniel-mar 176
        /**
177
         * @param string $actionID
178
         * @param array $params
1143 daniel-mar 179
         * @return array
1116 daniel-mar 180
         * @throws OIDplusException
181
         */
182
        public function action(string $actionID, array $params): array {
635 daniel-mar 183
 
184
                if ($actionID == 'deleteAttachment') {
185
                        _CheckParamExists($params, 'id');
186
                        $id = $params['id'];
187
                        $obj = OIDplusObject::parse($id);
1116 daniel-mar 188
                        if (!$obj) throw new OIDplusException(_L('Invalid object "%1"',$id));
635 daniel-mar 189
                        if (!$obj->userHasWriteRights()) throw new OIDplusException(_L('Authentication error. Please log in as admin, or as the RA of "%1" to upload an attachment.',$id));
190
 
191
                        if (!OIDplus::authUtils()->isAdminLoggedIn() && !$this->raMayDelete()) {
192
                                throw new OIDplusException(_L('The administrator has disabled deleting attachments by RAs.'));
193
                        }
194
 
195
                        _CheckParamExists($params, 'filename');
196
                        $req_filename = $params['filename'];
197
                        if (strpos($req_filename, '/') !== false) throw new OIDplusException(_L('Illegal file name'));
198
                        if (strpos($req_filename, '\\') !== false) throw new OIDplusException(_L('Illegal file name'));
199
                        if (strpos($req_filename, '..') !== false) throw new OIDplusException(_L('Illegal file name'));
200
                        if (strpos($req_filename, chr(0)) !== false) throw new OIDplusException(_L('Illegal file name'));
201
 
202
                        $uploaddir = self::getUploadDir($id);
203
                        $uploadfile = $uploaddir . DIRECTORY_SEPARATOR . basename($req_filename);
204
 
205
                        if (!file_exists($uploadfile)) throw new OIDplusException(_L('File does not exist'));
206
                        @unlink($uploadfile);
207
                        if (file_exists($uploadfile)) {
208
                                OIDplus::logger()->log("[ERR]OID($id)+[ERR]A!", "Attachment file '".basename($uploadfile)."' could not be deleted from object '$id' (problem with permissions?)");
209
                                $msg = _L('Attachment file "%1" could not be deleted from object "%2" (problem with permissions?)',basename($uploadfile),$id);
210
                                if (OIDplus::authUtils()->isAdminLoggedIn()) {
211
                                        throw new OIDplusException($msg);
212
                                } else {
213
                                        throw new OIDplusException($msg.'. '._L('Please contact the system administrator.'));
214
                                }
215
                        } else {
216
                                // If it was the last file, delete the empty directory
719 daniel-mar 217
                                $ary = @glob($uploaddir . DIRECTORY_SEPARATOR . '*');
218
                                if (is_array($ary) && (count($ary) == 0)) @rmdir($uploaddir);
635 daniel-mar 219
                        }
220
 
221
                        OIDplus::logger()->log("[OK]OID($id)+[?INFO/!OK]OIDRA($id)?/[?INFO/!OK]A?", "Deleted attachment '".basename($uploadfile)."' from object '$id'");
222
 
223
                        return array("status" => 0);
224
 
225
                } else if ($actionID == 'uploadAttachment') {
226
                        _CheckParamExists($params, 'id');
227
                        $id = $params['id'];
228
                        $obj = OIDplusObject::parse($id);
1116 daniel-mar 229
                        if (!$obj) throw new OIDplusException(_L('Invalid object "%1"',$id));
635 daniel-mar 230
                        if (!$obj->userHasWriteRights()) throw new OIDplusException(_L('Authentication error. Please log in as admin, or as the RA of "%1" to upload an attachment.',$id));
231
 
232
                        if (!OIDplus::authUtils()->isAdminLoggedIn() && !$this->raMayUpload()) {
233
                                throw new OIDplusException(_L('The administrator has disabled uploading attachments by RAs.'));
234
                        }
235
 
236
                        if (!isset($_FILES['userfile'])) {
237
                                throw new OIDplusException(_L('Please choose a file.'));
238
                        }
239
 
240
                        if (!OIDplus::authUtils()->isAdminLoggedIn()) {
836 daniel-mar 241
                                $fname = basename($_FILES['userfile']['name']);
242
 
834 daniel-mar 243
                                // 1. If something is on the blacklist, we always block it, even if it is on the whitelist, too
635 daniel-mar 244
                                $banned = explode(',', OIDplus::config()->getValue('attachments_block_extensions', ''));
245
                                foreach ($banned as $ext) {
246
                                        $ext = trim($ext);
247
                                        if ($ext == '') continue;
836 daniel-mar 248
                                        if (strtolower(substr($fname, -strlen($ext)-1)) == strtolower('.'.$ext)) {
635 daniel-mar 249
                                                throw new OIDplusException(_L('The file extension "%1" is banned by the administrator (it can be uploaded by the administrator though)',$ext));
250
                                        }
251
                                }
834 daniel-mar 252
 
253
                                // 2. Something on the whitelist is always OK
254
                                $allowed = explode(',', OIDplus::config()->getValue('attachments_allow_extensions', ''));
255
                                $is_whitelisted = false;
256
                                foreach ($allowed as $ext) {
257
                                        $ext = trim($ext);
258
                                        if ($ext == '') continue;
836 daniel-mar 259
                                        if (strtolower(substr($fname, -strlen($ext)-1)) == strtolower('.'.$ext)) {
834 daniel-mar 260
                                                $is_whitelisted = true;
261
                                                break;
262
                                        }
263
                                }
264
 
265
                                // 3. For everything that is neither whitelisted, nor blacklisted, the admin can decide if these grey zone is allowed or blocked
266
                                if (!$is_whitelisted) {
267
                                        if (!OIDplus::config()->getValue('attachments_allow_grey_extensions', '1')) {
836 daniel-mar 268
                                                $tmp = explode('.', $fname);
269
                                                $ext = array_pop($tmp);
834 daniel-mar 270
                                                throw new OIDplusException(_L('The file extension "%1" is not on the whitelist (it can be uploaded by the administrator though)',$ext));
271
                                        }
272
                                }
635 daniel-mar 273
                        }
274
 
275
                        $req_filename = $_FILES['userfile']['name'];
276
                        if (strpos($req_filename, '/') !== false) throw new OIDplusException(_L('Illegal file name'));
277
                        if (strpos($req_filename, '\\') !== false) throw new OIDplusException(_L('Illegal file name'));
278
                        if (strpos($req_filename, '..') !== false) throw new OIDplusException(_L('Illegal file name'));
279
                        if (strpos($req_filename, chr(0)) !== false) throw new OIDplusException(_L('Illegal file name'));
280
 
281
                        $uploaddir = self::getUploadDir($id);
282
                        $uploadfile = $uploaddir . DIRECTORY_SEPARATOR . basename($req_filename);
283
 
284
                        if (!is_dir($uploaddir)) {
285
                                @mkdir($uploaddir, 0777, true);
286
                                if (!is_dir($uploaddir)) {
287
                                        OIDplus::logger()->log("[ERR]OID($id)+[ERR]A!", "Upload attachment '".basename($uploadfile)."' to object '$id' failed: Cannot create directory '".basename($uploaddir)."' (problem with permissions?)");
288
                                        $msg = _L('Upload attachment "%1" to object "%2" failed',basename($uploadfile),$id).': '._L('Cannot create directory "%1" (problem with permissions?)',basename($uploaddir));
289
                                        if (OIDplus::authUtils()->isAdminLoggedIn()) {
290
                                                throw new OIDplusException($msg);
291
                                        } else {
292
                                                throw new OIDplusException($msg.'. '._L('Please contact the system administrator.'));
293
                                        }
294
                                }
295
                        }
296
 
297
                        if (!@move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
298
                                OIDplus::logger()->log("[ERR]OID($id)+[ERR]A!", "Upload attachment '".basename($uploadfile)."' to object '$id' failed: Cannot move uploaded file into directory (problem with permissions?)");
299
                                $msg = _L('Upload attachment "%1" to object "%2" failed',basename($uploadfile),$id).': '._L('Cannot move uploaded file into directory (problem with permissions?)');
300
                                if (OIDplus::authUtils()->isAdminLoggedIn()) {
301
                                        throw new OIDplusException($msg);
302
                                } else {
303
                                        throw new OIDplusException($msg.'. '._L('Please contact the system administrator.'));
304
                                }
305
                        }
306
 
307
                        OIDplus::logger()->log("[OK]OID($id)+[?INFO/!OK]OIDRA($id)?/[?INFO/!OK]A?", "Uploaded attachment '".basename($uploadfile)."' to object '$id'");
308
 
309
                        return array("status" => 0);
310
                } else {
1116 daniel-mar 311
                        return parent::action($actionID, $params);
635 daniel-mar 312
                }
313
        }
314
 
1116 daniel-mar 315
        /**
316
         * @param bool $html
317
         * @return void
318
         * @throws OIDplusException
319
         */
320
        public function init(bool $html=true) {
635 daniel-mar 321
                OIDplus::config()->prepareConfigKey('attachments_block_extensions', 'Block file name extensions being used in file attachments (comma separated)', 'exe,scr,pif,bat,com,vbs,cmd', OIDplusConfig::PROTECTION_EDITABLE, function($value) {
834 daniel-mar 322
                        // TODO: check if a blacklist entry is also on the whitelist (which is not allowed)
635 daniel-mar 323
                });
834 daniel-mar 324
                OIDplus::config()->prepareConfigKey('attachments_allow_extensions', 'Allow (whitelist) file name extensions being used in file attachments (comma separated)', '', OIDplusConfig::PROTECTION_EDITABLE, function($value) {
325
                        // TODO: check if a whitelist entry is also on the blacklist (which is not allowed)
326
                });
327
                OIDplus::config()->prepareConfigKey('attachments_allow_grey_extensions', 'Should file-extensions which are neither be on the whitelist, nor be at the blacklist, be allowed? (1=Yes, 0=No)', '1', OIDplusConfig::PROTECTION_EDITABLE, function($value) {
328
                        if (!is_numeric($value) || ($value < 0) || ($value > 1)) {
329
                                throw new OIDplusException(_L('Please enter a valid value (0=no, 1=yes).'));
330
                        }
331
                });
635 daniel-mar 332
                OIDplus::config()->prepareConfigKey('attachments_allow_ra_delete', 'Allow that RAs delete file attachments? (0=no, 1=yes)', '0', OIDplusConfig::PROTECTION_EDITABLE, function($value) {
333
                        if (!is_numeric($value) || ($value < 0) || ($value > 1)) {
334
                                throw new OIDplusException(_L('Please enter a valid value (0=no, 1=yes).'));
335
                        }
336
                });
337
                OIDplus::config()->prepareConfigKey('attachments_allow_ra_upload', 'Allow that RAs upload file attachments? (0=no, 1=yes)', '0', OIDplusConfig::PROTECTION_EDITABLE, function($value) {
338
                        if (!is_numeric($value) || ($value < 0) || ($value > 1)) {
339
                                throw new OIDplusException(_L('Please enter a valid value (0=no, 1=yes).'));
340
                        }
341
                });
1175 daniel-mar 342
                OIDplus::config()->prepareConfigKey('attachment_upload_dir', 'Alternative directory for attachments. If this setting is empty, then the userdata directory is used.', '', OIDplusConfig::PROTECTION_EDITABLE, function($value) {
635 daniel-mar 343
                        if (trim($value) !== '') {
344
                                self::checkUploadDir($value);
345
                        }
346
                });
347
        }
348
 
1116 daniel-mar 349
        /**
350
         * @param string $id
351
         * @param array $out
352
         * @param bool $handled
353
         * @return void
354
         */
355
        public function gui(string $id, array &$out, bool &$handled) {
635 daniel-mar 356
                // Nothing
357
        }
358
 
1116 daniel-mar 359
        /**
360
         * @param array $out
361
         * @return void
362
         */
363
        public function publicSitemap(array &$out) {
635 daniel-mar 364
                // Nothing
365
        }
366
 
1116 daniel-mar 367
        /**
368
         * @param array $json
369
         * @param string|null $ra_email
370
         * @param bool $nonjs
371
         * @param string $req_goto
372
         * @return bool
373
         */
374
        public function tree(array &$json, string $ra_email=null, bool $nonjs=false, string $req_goto=''): bool {
635 daniel-mar 375
                return false;
376
        }
377
 
1116 daniel-mar 378
        /**
379
         * Convert amount of bytes to human-friendly name
1175 daniel-mar 380
         *
1116 daniel-mar 381
         * @param int $bytes
382
         * @param int $decimals
383
         * @return string
1175 daniel-mar 384
         * @throws OIDplusConfigInitializationException
385
         * @throws OIDplusException
1116 daniel-mar 386
         */
387
        private static function convert_filesize(int $bytes, int $decimals = 2): string {
635 daniel-mar 388
                $size = array(_L('Bytes'),_L('KiB'),_L('MiB'),_L('GiB'),_L('TiB'),_L('PiB'),_L('EiB'),_L('ZiB'),_L('YiB'));
1116 daniel-mar 389
                $factor = floor((strlen("$bytes") - 1) / 3);
635 daniel-mar 390
                return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . ' ' . @$size[$factor];
391
        }
392
 
1116 daniel-mar 393
        /**
1131 daniel-mar 394
         * Implements interface INTF_OID_1_3_6_1_4_1_37476_2_5_2_3_2
1175 daniel-mar 395
         *
1116 daniel-mar 396
         * @param string $id
397
         * @param string $title
398
         * @param string $icon
399
         * @param string $text
400
         * @return void
1175 daniel-mar 401
         * @throws OIDplusConfigInitializationException
402
         * @throws OIDplusException
1116 daniel-mar 403
         */
404
        public function modifyContent(string $id, string &$title, string &$icon, string &$text) {
635 daniel-mar 405
                $output = '';
406
                $doshow = false;
407
 
408
                try {
409
                        $upload_dir = self::getUploadDir($id);
719 daniel-mar 410
                        $files = @glob($upload_dir . DIRECTORY_SEPARATOR . '*');
635 daniel-mar 411
                        $found_files = false;
412
 
413
                        $obj = OIDplusObject::parse($id);
1116 daniel-mar 414
                        if (!$obj) throw new OIDplusException(_L('Invalid object "%1"',$id));
635 daniel-mar 415
                        $can_upload = OIDplus::authUtils()->isAdminLoggedIn() || ($this->raMayUpload() && $obj->userHasWriteRights());
416
                        $can_delete = OIDplus::authUtils()->isAdminLoggedIn() || ($this->raMayDelete() && $obj->userHasWriteRights());
417
 
418
                        if (OIDplus::authUtils()->isAdminLoggedIn()) {
419
                                $output .= '<p>'._L('Admin info: The directory is %1','<b>'.htmlentities($upload_dir).'</b>').'</p>';
420
                                $doshow = true;
421
                        }
422
 
423
                        $output .= '<div id="fileattachments_table" class="table-responsive">';
424
                        $output .= '<table class="table table-bordered table-striped">';
1138 daniel-mar 425
                        $output .= '<thead>';
635 daniel-mar 426
                        $output .= '<tr>';
427
                        $output .= '<th>'._L('Filename').'</th>';
428
                        $output .= '<th>'._L('Size').'</th>';
429
                        $output .= '<th>'._L('File type').'</th>';
430
                        $output .= '<th>'._L('Download').'</th>';
431
                        if ($can_delete) $output .= '<th>'._L('Delete').'</th>';
432
                        $output .= '</tr>';
1138 daniel-mar 433
                        $output .= '</thead>';
434
                        $output .= '<tbody>';
719 daniel-mar 435
                        if ($files) foreach ($files as $file) {
635 daniel-mar 436
                                if (is_dir($file)) continue;
437
 
438
                                $output .= '<tr>';
439
                                $output .= '<td>'.htmlentities(basename($file)).'</td>';
440
                                $output .= '<td>'.htmlentities(self::convert_filesize(filesize($file), 0)).'</td>';
441
                                $lookup_files = array(
442
                                        OIDplus::localpath().'userdata/attachments/filetypes$'.OIDplus::getCurrentLang().'.conf',
443
                                        OIDplus::localpath().'userdata/attachments/filetypes.conf',
444
                                        OIDplus::localpath().'vendor/danielmarschall/fileformats/filetypes$'.OIDplus::getCurrentLang().'.local', // not recommended
445
                                        OIDplus::localpath().'vendor/danielmarschall/fileformats/filetypes.local', // not recommended
446
                                        OIDplus::localpath().'vendor/danielmarschall/fileformats/filetypes$'.OIDplus::getCurrentLang().'.conf',
447
                                        OIDplus::localpath().'vendor/danielmarschall/fileformats/filetypes.conf'
448
                                );
1050 daniel-mar 449
                                $output .= '<td>'.htmlentities(\VtsFileTypeDetect::getDescription($file, $lookup_files)).'</td>';
635 daniel-mar 450
 
801 daniel-mar 451
                                $output .= '     <td><button type="button" name="download_'.md5($file).'" id="download_'.md5($file).'" class="btn btn-success btn-xs download" onclick="OIDplusPagePublicAttachments.downloadAttachment('.js_escape(OIDplus::webpath(__DIR__,OIDplus::PATH_RELATIVE)).', current_node,'.js_escape(basename($file)).')">'._L('Download').'</button></td>';
635 daniel-mar 452
                                if ($can_delete) {
453
                                        $output .= '     <td><button type="button" name="delete_'.md5($file).'" id="delete_'.md5($file).'" class="btn btn-danger btn-xs delete" onclick="OIDplusPagePublicAttachments.deleteAttachment(current_node,'.js_escape(basename($file)).')">'._L('Delete').'</button></td>';
454
                                }
455
 
456
                                $output .= '</tr>';
457
                                $doshow = true;
458
                                $found_files = true;
459
                        }
1138 daniel-mar 460
                        $output .= '</tbody>';
635 daniel-mar 461
 
1138 daniel-mar 462
                        if (!$found_files) {
463
                                $output .= '<tfoor>';
464
                                $output .= '<tr><td colspan="' . ($can_delete ? 5 : 4) . '"><i>' . _L('No attachments') . '</i></td></tr>';
465
                                $output .= '</tfoot>';
466
                        }
635 daniel-mar 467
 
468
                        $output .= '</table></div>';
469
 
470
                        if ($can_upload) {
471
                                $output .= '<form action="javascript:void(0);" onsubmit="return OIDplusPagePublicAttachments.uploadAttachmentOnSubmit(this);" enctype="multipart/form-data" id="uploadAttachmentForm">';
472
                                $output .= '<input type="hidden" name="id" value="'.htmlentities($id).'">';
473
                                $output .= '<div>'._L('Add a file attachment').':<input type="file" name="userfile" value="" id="fileAttachment">';
474
                                $output .= '<br><input type="submit" value="'._L('Upload').'"></div>';
475
                                $output .= '</form>';
476
                                $doshow = true;
477
                        }
1050 daniel-mar 478
                } catch (\Exception $e) {
635 daniel-mar 479
                        $doshow = true;
480
                        $output = '<p>'.$e->getMessage().'</p>';
481
                }
482
 
483
                $output = '<h2>'._L('File attachments').'</h2>' .
484
                          '<div class="container box">' .
485
                          $output .
486
                          '</div>';
487
                if ($doshow) $text .= $output;
488
        }
489
 
1116 daniel-mar 490
        /**
1131 daniel-mar 491
         * Implements interface INTF_OID_1_3_6_1_4_1_37476_2_5_2_3_3
1130 daniel-mar 492
         * @param string $id
1116 daniel-mar 493
         * @return void
494
         */
1130 daniel-mar 495
        public function beforeObjectDelete(string $id) {}
1116 daniel-mar 496
 
497
        /**
1131 daniel-mar 498
         * Implements interface INTF_OID_1_3_6_1_4_1_37476_2_5_2_3_3
1130 daniel-mar 499
         * @param string $id
1116 daniel-mar 500
         * @return void
501
         * @throws OIDplusException
502
         */
1130 daniel-mar 503
        public function afterObjectDelete(string $id) {
1131 daniel-mar 504
                // Delete the attachment folder including all files in it (note: Subfolders are not possible)
635 daniel-mar 505
                $uploaddir = self::getUploadDir($id);
506
                if ($uploaddir != '') {
719 daniel-mar 507
                        $ary = @glob($uploaddir . DIRECTORY_SEPARATOR . '*');
508
                        if ($ary) foreach ($ary as $a) @unlink($a);
635 daniel-mar 509
                        @rmdir($uploaddir);
510
                        if (is_dir($uploaddir)) {
511
                                OIDplus::logger()->log("[WARN]OID($id)+[WARN]A!", "Attachment directory '$uploaddir' could not be deleted during the deletion of the OID");
512
                        }
513
                }
514
        }
515
 
1116 daniel-mar 516
        /**
1131 daniel-mar 517
         * Implements interface INTF_OID_1_3_6_1_4_1_37476_2_5_2_3_3
1130 daniel-mar 518
         * @param string $id
519
         * @param array $params
1116 daniel-mar 520
         * @return void
521
         */
1130 daniel-mar 522
        public function beforeObjectUpdateSuperior(string $id, array &$params) {}
1116 daniel-mar 523
 
524
        /**
1131 daniel-mar 525
         * Implements interface INTF_OID_1_3_6_1_4_1_37476_2_5_2_3_3
1130 daniel-mar 526
         * @param string $id
527
         * @param array $params
1116 daniel-mar 528
         * @return void
529
         */
1130 daniel-mar 530
        public function afterObjectUpdateSuperior(string $id, array &$params) {}
1116 daniel-mar 531
 
532
        /**
1131 daniel-mar 533
         * Implements interface INTF_OID_1_3_6_1_4_1_37476_2_5_2_3_3
1130 daniel-mar 534
         * @param string $id
535
         * @param array $params
1116 daniel-mar 536
         * @return void
537
         */
1130 daniel-mar 538
        public function beforeObjectUpdateSelf(string $id, array &$params) {}
1116 daniel-mar 539
 
540
        /**
1131 daniel-mar 541
         * Implements interface INTF_OID_1_3_6_1_4_1_37476_2_5_2_3_3
1130 daniel-mar 542
         * @param string $id
543
         * @param array $params
1116 daniel-mar 544
         * @return void
545
         */
1130 daniel-mar 546
        public function afterObjectUpdateSelf(string $id, array &$params) {}
1116 daniel-mar 547
 
548
        /**
1131 daniel-mar 549
         * Implements interface INTF_OID_1_3_6_1_4_1_37476_2_5_2_3_3
1130 daniel-mar 550
         * @param string $id
551
         * @param array $params
1116 daniel-mar 552
         * @return void
553
         */
1130 daniel-mar 554
        public function beforeObjectInsert(string $id, array &$params) {}
1116 daniel-mar 555
 
556
        /**
1131 daniel-mar 557
         * Implements interface INTF_OID_1_3_6_1_4_1_37476_2_5_2_3_3
1130 daniel-mar 558
         * @param string $id
559
         * @param array $params
1116 daniel-mar 560
         * @return void
561
         */
1130 daniel-mar 562
        public function afterObjectInsert(string $id, array &$params) {}
1116 daniel-mar 563
 
564
        /**
565
         * @param string $request
566
         * @return array|false
567
         */
568
        public function tree_search(string $request) {
635 daniel-mar 569
                return false;
570
        }
571
 
1116 daniel-mar 572
        /**
1131 daniel-mar 573
         * Implements interface INTF_OID_1_3_6_1_4_1_37476_2_5_2_3_4
1130 daniel-mar 574
         * @param string $id
575
         * @param array $out
1116 daniel-mar 576
         * @return void
577
         * @throws OIDplusException
578
         */
1130 daniel-mar 579
        public function whoisObjectAttributes(string $id, array &$out) {
899 daniel-mar 580
                $xmlns = 'oidplus-attachment-plugin';
581
                $xmlschema = 'urn:oid:1.3.6.1.4.1.37476.2.5.2.4.1.95.1';
582
                $xmlschemauri = OIDplus::webpath(__DIR__.'/attachments.xsd',OIDplus::PATH_ABSOLUTE);
583
 
719 daniel-mar 584
                $files = @glob(self::getUploadDir($id) . DIRECTORY_SEPARATOR . '*');
585
                if ($files) foreach ($files as $file) {
899 daniel-mar 586
                        $url = OIDplus::webpath(__DIR__,OIDplus::PATH_ABSOLUTE).'download.php?id='.urlencode($id).'&filename='.urlencode(basename($file));
587
 
588
                        $out[] = array(
589
                                'xmlns' => $xmlns,
590
                                'xmlschema' => $xmlschema,
591
                                'xmlschemauri' => $xmlschemauri,
592
                                'name' => 'attachment-name',
593
                                'value' => basename($file)
594
                        );
595
 
596
                        $out[] = array(
597
                                'xmlns' => $xmlns,
598
                                'xmlschema' => $xmlschema,
599
                                'xmlschemauri' => $xmlschemauri,
600
                                'name' => 'attachment-url',
601
                                'value' => $url
602
                        );
635 daniel-mar 603
                }
604
 
605
        }
1116 daniel-mar 606
 
607
        /**
1131 daniel-mar 608
         * Implements interface INTF_OID_1_3_6_1_4_1_37476_2_5_2_3_4
1130 daniel-mar 609
         * @param string $email
610
         * @param array $out
1116 daniel-mar 611
         * @return void
612
         */
1130 daniel-mar 613
        public function whoisRaAttributes(string $email, array &$out) {}
1180 daniel-mar 614
 
615
        /**
616
         * Implements interface INTF_OID_1_3_6_1_4_1_37476_2_5_2_3_8
617
         * @param string|null $user
618
         * @return array  returns array of array($severity, $htmlMessage)
619
         */
620
        public function getNotifications(string $user=null): array {
621
                $notifications = array();
622
                if ((!$user || ($user == 'admin')) && OIDplus::authUtils()->isAdminLoggedIn()) {
623
                        $error = '';
624
                        try {
625
                                $basepath = self::getUploadBaseDir();
626
                                if (!is_dir($basepath)) {
627
                                        throw new OIDplusException(_L('Directory %1 does not exist', $basepath));
628
                                } else {
629
                                        self::checkUploadDir($basepath);
630
                                        if (!isFileOrPathWritable($basepath)) {
631
                                                throw new OIDplusException(_L('Directory %1 is not writeable. Please check the permissions!', $basepath));
632
                                        }
633
                                }
634
                        } catch (\Exception $e) {
635
                                $error = _L('The file attachments feature is not available due to a misconfiguration');
636
                                $error .= ': ' . $e->getMessage();
637
                        }
638
                        if ($error) {
1189 daniel-mar 639
                                $notifications[] = new OIDplusNotification('WARN', $error);
1180 daniel-mar 640
                        }
641
                }
642
                return $notifications;
643
        }
635 daniel-mar 644
}