Subversion Repositories oidplus

Rev

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

Rev Author Line No. Line
310 daniel-mar 1
<?php
2
 
3
/*
4
 * OIDplus 2.0
5
 * Copyright 2019 Daniel Marschall, ViaThinkSoft
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
 
20
class OIDplusPagePublicAttachments extends OIDplusPagePluginPublic {
21
 
22
        public static function getUploadDir($id) {
23
                $path = realpath(__DIR__.'/../../../').'/userdata/attachments/';
24
 
25
                $obj = OIDplusObject::parse($id);
26
                if ($obj === null) throw new OIDplusException("Invalid object '$id'");
27
                if ($obj::ns() == 'oid') {
28
                        $oid = $obj->nodeId(false);
29
                } else {
30
                        $oid = null;
31
                        $alt_ids = $obj->getAltIds();
32
                        foreach ($alt_ids as $alt_id) {
33
                                if ($alt_id->getNamespace() == 'oid') {
34
                                        $oid = $alt_id->getId();
35
                                        break; // we prefer the first OID (for GUIDs, the first OID is the OIDplus-OID, and the second OID is the UUID OID)
36
                                }
37
                        }
38
                }
39
 
40
                if (!is_null($oid)) {
41
                        // For OIDs, it is the OID, for other identifiers
42
                        // it it the OID alt ID (generated using the SystemID)
43
                        $path .= str_replace('.', '_', $oid);
44
 
45
                } else {
46
                        // Can happen if you don't have a system ID (due to missing OpenSSL plugin)
47
                        $path .= md5($obj->nodeId(true)); // we don't use $id, because $obj->nodeId(true) is possibly more canonical than $id
48
                }
49
 
50
                return $path;
51
        }
52
 
53
        private function raMayDelete() {
54
                return OIDplus::config()->getValue('attachments_allow_ra_delete', 0);
55
        }
56
 
57
        private function raMayUpload() {
58
                return OIDplus::config()->getValue('attachments_allow_ra_upload', 0);
59
        }
60
 
321 daniel-mar 61
        public function action($actionID, $params) {
317 daniel-mar 62
 
321 daniel-mar 63
                if ($actionID == 'deleteAttachment') {
64
                        $id = $params['id'];
317 daniel-mar 65
                        $obj = OIDplusObject::parse($id);
310 daniel-mar 66
                        if ($obj === null) throw new OIDplusException("Invalid object '$id'");
67
                        if (!$obj->userHasWriteRights()) throw new OIDplusException("Authentication error. Please log in as the RA of '$id' to upload an attachment.");
68
 
69
                        if (!OIDplus::authUtils()::isAdminLoggedIn() && !$this->raMayDelete()) {
70
                                throw new OIDplusException("The administrator has disabled deleting attachments by RAs.");
71
                        }
72
 
321 daniel-mar 73
                        $req_filename = $params['filename'];
310 daniel-mar 74
                        if (strpos($req_filename, '/') !== false) throw new OIDplusException("Illegal file name");
75
                        if (strpos($req_filename, '\\') !== false) throw new OIDplusException("Illegal file name");
76
                        if (strpos($req_filename, '..') !== false) throw new OIDplusException("Illegal file name");
77
                        if (strpos($req_filename, chr(0)) !== false) throw new OIDplusException("Illegal file name");
78
 
79
                        $uploaddir = self::getUploadDir($id);
80
                        $uploadfile = $uploaddir . '/' . basename($req_filename);
81
 
82
                        if (!file_exists($uploadfile)) throw new OIDplusException("File does not exist");
83
                        @unlink($uploadfile);
84
                        if (file_exists($uploadfile)) {
85
                                $msg = "Attachment file '".basename($uploadfile)."' could not be deleted from object '$oid' (problem with permissions?)";
86
                                OIDplus::logger()->log("[ERR]OID($id)+[ERR]A!", $msg);
87
                                if (OIDplus::authUtils()::isAdminLoggedIn()) {
88
                                        throw new OIDplusException($msg);
89
                                } else {
90
                                        throw new OIDplusException("$msg. Please contact the system administrator.");
91
                                }
317 daniel-mar 92
                        } else {
93
                                // If it was the last file, delete the empty directory
94
                                $ary = glob($uploaddir . '/' . '*');
95
                                if (count($ary) == 0) @rmdir($uploaddir);
310 daniel-mar 96
                        }
97
 
98
                        OIDplus::logger()->log("[OK]OID($id)+[?INFO/!OK]OIDRA($id)?/[?INFO/!OK]A?", "Deleted attachment '".basename($uploadfile)."' from object '$id'");
99
 
100
                        echo json_encode(array("status" => 0));
322 daniel-mar 101
 
321 daniel-mar 102
                } else if ($actionID == 'uploadAttachment') {
322 daniel-mar 103
 
321 daniel-mar 104
                        $id = $params['id'];
310 daniel-mar 105
                        $obj = OIDplusObject::parse($id);
106
                        if ($obj === null) throw new OIDplusException("Invalid object '$id'");
107
                        if (!$obj->userHasWriteRights()) throw new OIDplusException("Authentication error. Please log in as the RA of '$id' to upload an attachment.");
108
 
109
                        if (!OIDplus::authUtils()::isAdminLoggedIn() && !$this->raMayUpload()) {
110
                                throw new OIDplusException("The administrator has disabled uploading attachments by RAs.");
111
                        }
112
 
113
                        if (!OIDplus::authUtils()::isAdminLoggedIn()) {
114
                                $banned = explode(',', OIDplus::config()->getValue('attachments_block_extensions', ''));
115
                                foreach ($banned as $ext) {
116
                                        $ext = trim($ext);
117
                                        if ($ext == '') continue;
118
                                        if (strtolower(substr(basename($_FILES['userfile']['name']), -strlen($ext)-1)) == strtolower('.'.$ext)) {
119
                                                throw new OIDplusException("The file extension '.$ext' is banned by the administrator (it can be uploaded by the administrator though)");
120
                                        }
121
                                }
122
                        }
123
 
124
                        $req_filename = $_FILES['userfile']['name'];
125
                        if (strpos($req_filename, '/') !== false) throw new OIDplusException("Illegal file name");
126
                        if (strpos($req_filename, '\\') !== false) throw new OIDplusException("Illegal file name");
127
                        if (strpos($req_filename, '..') !== false) throw new OIDplusException("Illegal file name");
128
                        if (strpos($req_filename, chr(0)) !== false) throw new OIDplusException("Illegal file name");
129
 
130
                        $uploaddir = self::getUploadDir($id);
131
                        $uploadfile = $uploaddir . '/' . basename($req_filename);
132
 
133
                        if (!is_dir($uploaddir)) {
134
                                @mkdir($uploaddir, 0777, true);
135
                                if (!is_dir($uploaddir)) {
136
                                        $msg = "Upload attachment '".basename($uploadfile)."' to object '$id' failed: Cannot create directory '".basename($uploaddir)."' (problem with permissions?)";
137
                                        OIDplus::logger()->log("[ERR]OID($id)+[ERR]A!", $msg);
138
                                        if (OIDplus::authUtils()::isAdminLoggedIn()) {
139
                                                throw new OIDplusException($msg);
140
                                        } else {
141
                                                throw new OIDplusException("$msg. Please contact the system administrator.");
142
                                        }
143
                                }
144
                        }
145
 
146
                        if (!@move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
147
                                $msg = "Upload attachment '".basename($uploadfile)."' to object '$id' failed: Cannot move uploaded file into directory (problem with permissions?)";
148
                                OIDplus::logger()->log("[ERR]OID($id)+[ERR]A!", $msg);
149
                                if (OIDplus::authUtils()::isAdminLoggedIn()) {
150
                                        throw new OIDplusException($msg);
151
                                } else {
152
                                        throw new OIDplusException("$msg. Please contact the system administrator.");
153
                                }
154
                        }
155
 
156
                        OIDplus::logger()->log("[OK]OID($id)+[?INFO/!OK]OIDRA($id)?/[?INFO/!OK]A?", "Uploaded attachment '".basename($uploadfile)."' to object '$id'");
157
 
158
                        echo json_encode(array("status" => 0));
321 daniel-mar 159
                } else {
160
                        throw new OIDplusException("Unknown action ID");
310 daniel-mar 161
                }
162
        }
163
 
164
        public function init($html=true) {
165
                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) {
166
                });
167
                OIDplus::config()->prepareConfigKey('attachments_allow_ra_delete', 'Allow that RAs delete file attachments? (0=no, 1=yes)', '0', OIDplusConfig::PROTECTION_EDITABLE, function($value) {
168
                        if (!is_numeric($value) || ($value < 0) || ($value > 1)) {
169
                                throw new OIDplusException("Please enter a valid value (0 or 1).");
170
                        }
171
                });
172
                OIDplus::config()->prepareConfigKey('attachments_allow_ra_upload', 'Allow that RAs upload file attachments? (0=no, 1=yes)', '0', OIDplusConfig::PROTECTION_EDITABLE, function($value) {
173
                        if (!is_numeric($value) || ($value < 0) || ($value > 1)) {
174
                                throw new OIDplusException("Please enter a valid value (0 or 1).");
175
                        }
176
                });
177
        }
178
 
179
        public function gui($id, &$out, &$handled) {
180
                // Nothing
181
        }
182
 
183
        public function publicSitemap(&$out) {
184
                // Nothing
185
        }
186
 
187
        public function tree(&$json, $ra_email=null, $nonjs=false, $req_goto='') {
188
                return false;
189
        }
190
 
191
        private static function convert_filesize($bytes, $decimals = 2){
192
                $size = array('Bytes','KiB','MiB','GiB','TiB','PiB','EiB','ZiB','YiB');
193
                $factor = floor((strlen($bytes) - 1) / 3);
194
                return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . ' ' . @$size[$factor];
195
        }
196
 
197
        public function implementsFeature($id) {
198
                if (strtolower($id) == '1.3.6.1.4.1.37476.2.5.2.3.2') return true; // modifyContent
321 daniel-mar 199
                if (strtolower($id) == '1.3.6.1.4.1.37476.2.5.2.3.3') return true; // beforeObject*, afterObject*
322 daniel-mar 200
                if (strtolower($id) == '1.3.6.1.4.1.37476.2.5.2.3.4') return true; // whois*Attributes
310 daniel-mar 201
                return false;
202
        }
203
 
204
        public function modifyContent($id, &$title, &$icon, &$text) {
205
                // Interface 1.3.6.1.4.1.37476.2.5.2.3.2
206
 
207
                $files = glob(self::getUploadDir($id).'/'.'*');
208
                $doshow = false;
209
                $output = '';
314 daniel-mar 210
                $found_files = false;
310 daniel-mar 211
 
212
                $obj = OIDplusObject::parse($id);
213
                if ($obj === null) throw new OIDplusException("Invalid object '$id'");
214
                $can_upload = OIDplus::authUtils()::isAdminLoggedIn() || ($this->raMayUpload() && $obj->userHasWriteRights());
215
                $can_delete = OIDplus::authUtils()::isAdminLoggedIn() || ($this->raMayDelete() && $obj->userHasWriteRights());
216
 
217
                $output .= '<h2>File attachments</h2>';
218
                $output .= '<div class="container box">';
219
 
220
                if (OIDplus::authUtils()::isAdminLoggedIn()) {
221
                        $output .= '<p>Admin info: The directory is <b>'.htmlentities(self::getUploadDir($id)).'</b></p>';
222
                        $doshow = true;
223
                }
224
 
225
                $output .= '<div id="fileattachments_table" class="table-responsive">';
226
                $output .= '<table class="table table-bordered table-striped">';
227
                $output .= '<tr>';
228
                $output .= '<th>Filename</th>';
229
                $output .= '<th>Size</th>';
230
                $output .= '<th>File type</th>';
231
                $output .= '<th>Download</th>';
232
                if ($can_delete) $output .= '<th>Delete</th>';
233
                $output .= '</tr>';
234
                foreach ($files as $file) {
314 daniel-mar 235
                        if (is_dir($file)) continue;
236
 
310 daniel-mar 237
                        $output .= '<tr>';
238
                        $output .= '<td>'.htmlentities(basename($file)).'</td>';
239
                        $output .= '<td>'.htmlentities(self::convert_filesize(filesize($file), 0)).'</td>';
240
                        $lookup_files = array(__DIR__.'/../../../userdata/attachments/filetypes.conf', __DIR__.'/../../../3p/vts_fileformats/filetypes.local', __DIR__.'/../../../3p/vts_fileformats/filetypes.conf');
241
                        $output .= '<td>'.htmlentities(VtsFileTypeDetect::getDescription($file, $lookup_files)).'</td>';
242
 
243
                        $output .= '     <td><button type="button" name="download_'.md5($file).'" id="download_'.md5($file).'" class="btn btn-success btn-xs download" onclick="downloadAttachment('.js_escape(OIDplus::webpath(__DIR__)).', current_node,'.js_escape(basename($file)).')">Download</button></td>';
244
                        if ($can_delete) {
245
                                $output .= '     <td><button type="button" name="delete_'.md5($file).'" id="delete_'.md5($file).'" class="btn btn-danger btn-xs delete" onclick="deleteAttachment(current_node,'.js_escape(basename($file)).')">Delete</button></td>';
246
                        }
247
 
248
                        $output .= '</tr>';
249
                        $doshow = true;
314 daniel-mar 250
                        $found_files = true;
310 daniel-mar 251
                }
252
 
314 daniel-mar 253
                if (!$found_files) $output .= '<tr><td colspan="'.($can_delete ? 5 : 4).'"><i>No attachments</i></td></tr>';
310 daniel-mar 254
 
255
                $output .= '</table></div>';
256
 
257
                if ($can_upload) {
258
                        $output .= '<form onsubmit="return uploadAttachmentOnSubmit(this);" enctype="multipart/form-data" id="uploadAttachmentForm">';
259
                        $output .= '<input type="hidden" name="id" value="'.htmlentities($id).'">';
260
                        $output .= '<input type="hidden" name="action" value="uploadAttachment">';
261
                        $output .= '<div>Add a file attachment:<input type="file" name="userfile" value="" id="fileAttachment">';
262
                        $output .= '<br><input type="submit" value="Upload"></div>';
263
                        $output .= '</form>';
264
                        $doshow = true;
265
                }
266
 
267
                $output .= '</div>';
268
 
269
                if ($doshow) $text .= $output;
270
        }
271
 
321 daniel-mar 272
        public function beforeObjectDelete($id) {} // Interface 1.3.6.1.4.1.37476.2.5.2.3.3
273
        public function afterObjectDelete($id) {
274
                // Interface 1.3.6.1.4.1.37476.2.5.2.3.3
275
                // Delete the attachment folder including all files in it (note: Subfolders are not possible)
276
                $uploaddir = self::getUploadDir($id);
277
                if ($uploaddir != '') {
278
                        $ary = glob($uploaddir . '/' . '*');
279
                        foreach ($ary as $a) @unlink($a);
280
                        @rmdir($uploaddir);
281
                        if (is_dir($uploaddir)) {
282
                                OIDplus::logger()->log("[WARN]OID($id)+[WARN]A!", "Attachment directory '$uploaddir' could not be deleted during the deletion of the OID");
283
                        }
284
                }
285
        }
286
        public function beforeObjectUpdateSuperior($id, &$params) {} // Interface 1.3.6.1.4.1.37476.2.5.2.3.3
287
        public function afterObjectUpdateSuperior($id, &$params) {} // Interface 1.3.6.1.4.1.37476.2.5.2.3.3
288
        public function beforeObjectUpdateSelf($id, &$params) {} // Interface 1.3.6.1.4.1.37476.2.5.2.3.3
289
        public function afterObjectUpdateSelf($id, &$params) {} // Interface 1.3.6.1.4.1.37476.2.5.2.3.3
290
        public function beforeObjectInsert($id, &$params) {} // Interface 1.3.6.1.4.1.37476.2.5.2.3.3
291
        public function afterObjectInsert($id, &$params) {} // Interface 1.3.6.1.4.1.37476.2.5.2.3.3
292
 
310 daniel-mar 293
        public function tree_search($request) {
294
                return false;
295
        }
322 daniel-mar 296
 
297
        public function whoisObjectAttributes($id, &$out) {
298
                // Interface 1.3.6.1.4.1.37476.2.5.2.3.4
299
 
300
                $files = glob(self::getUploadDir($id).'/'.'*');
301
                foreach ($files as $file) {
302
                        $out[] = 'attachment-name: '.basename($file);
303
                        $out[] = 'attachment-url: '.OIDplus::getSystemUrl().OIDplus::webpath(__DIR__).'download.php?id='.urlencode($id).'&filename='.urlencode(basename($file));
304
                }
305
 
306
        }
307
        public function whoisRaAttributes($email, &$out) {} // Interface 1.3.6.1.4.1.37476.2.5.2.3.4
310 daniel-mar 308
}