-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathDocument.php
More file actions
227 lines (205 loc) · 7.44 KB
/
Document.php
File metadata and controls
227 lines (205 loc) · 7.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
<?php
/**
* -------------------------------------------------------------------------
* Example plugin for GLPI
* -------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of Example.
*
* Example is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Example is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Example. If not, see <http://www.gnu.org/licenses/>.
* -------------------------------------------------------------------------
* @copyright Copyright (C) 2006-2022 by Example plugin team.
* @license GPLv2 https://www.gnu.org/licenses/gpl-2.0.html
* @link https://github.com/pluginsGLPI/example
* -------------------------------------------------------------------------
*/
/**
* Show how to dowload a file (or any stream) from the REST API
* as well as metatadata stored in DB
*
* This itemtype is designed to be the same as Document in GLPI Core
* to focus on the file dowload and upload features
*
* Example to download a file with cURL
*
* $ curl -X GET \
* -H 'Content-Type: application/json' \
* -H 'Session-Token: s6f3jik227ttrsat7d8ap9laal' \
* -H 'Accept: application/octet-stream' \
* 'http://path/to/glpi/apirest.php/PluginExampleDocument/1' \
* --output /tmp/test_download
*
* Example to upload a file with cURL
*
* $ curl -X POST \
* -H 'Content-Type: multipart/form-data' \
* -H "Session-Token: s6f3jik227ttrsat7d8ap9laal" \
* -F 'uploadManifest={"input": {"name": "Uploaded document", "_filename" : ["file.txt"]}}' \
* -F 'file[]=@/tmp/test.txt' \
* 'http://path/to/glpi/apirest.php/PluginExampleDocument/'
*
*/
namespace GlpiPlugin\Example;
use Glpi\Exception\Http\NotFoundHttpException;
use Glpi\Exception\Http\HttpException;
use Document as GlpiDocument;
use function Safe\filemtime;
use function Safe\filesize;
use function Safe\fopen;
use function Safe\fread;
use function Safe\preg_match;
use function Safe\set_time_limit;
class Document extends GlpiDocument
{
/**
* Return the table used to store this object. Overloads the implementation in CommonDBTM
*
* @param string $classname Force class (to avoid late_binding on inheritance)
*
* @return string
**/
public static function getTable($classname = null)
{
if ($classname === null) {
$classname = static::class;
}
if ($classname == static::class) {
return parent::getTable(Document::class);
}
return parent::getTable($classname);
}
/**
* Prepare creation of an item
*
* @param array $input
* @return array|false
*/
public function prepareInputForAdd($input)
{
$input['_only_if_upload_succeed'] = true;
if (!isset($_FILES['file'])) {
return false;
}
// Move the uploaded file to GLPi's tmp dir
while (count($_FILES['file']['name']) > 0) {
$source = array_pop($_FILES['file']['name']);
$destination = GLPI_TMP_DIR . '/' . $source;
move_uploaded_file($source, $destination);
$input['_filename'][] = $source;
}
return parent::prepareInputForAdd($input);
}
/**
* Prepare update of an item
*
* @param array $input
* @return array|false
*/
public function prepareInputForUpdate($input)
{
// Do not allow update of document
return false;
}
/**
* Process required after loading an object from DB
* In this example, a file is sent as a byte strem then stops execution.
*
* @return void
*/
public function post_getFromDB()
{
// Check the user can view this itemtype and can view this item
if ($this->canView() && $this->canViewItem() && (isset($_SERVER['HTTP_ACCEPT']) && $_SERVER['HTTP_ACCEPT'] == 'application/octet-stream' || isset($_GET['alt']) && $_GET['alt'] == 'media')) {
$this->sendFile();
// and terminate script
}
}
/**
* Send a byte stream to the HTTP client and stops execution
*
* @return void
*/
protected function sendFile()
{
$streamSource = GLPI_DOC_DIR . '/' . $this->fields['filepath'];
// Ensure the file exists
if (!file_exists($streamSource) || !is_file($streamSource)) {
throw new NotFoundHttpException();
}
// Download range defaults to the full file
// get file metadata
$size = filesize($streamSource);
$begin = 0;
$end = $size - 1;
$mimeType = 'application/octet-stream';
$time = date('r', filemtime($streamSource));
// Open the file
$fileHandle = @fopen($streamSource, 'rb');
if (!$fileHandle) {
throw new HttpException(500, 'Internal Server Error');
}
// set range if specified by the client
if (isset($_SERVER['HTTP_RANGE']) && preg_match('/bytes=\h*(\d+)?-(\d*)[\D.*]?/i', $_SERVER['HTTP_RANGE'], $matches)) {
if (!empty($matches[1])) {
$begin = intval($matches[1]);
}
if (!empty($matches[2])) {
$end = min(intval($matches[2]), $end);
}
}
// seek to the begining of the range
$currentPosition = $begin;
if (fseek($fileHandle, $begin, SEEK_SET) < 0) {
throw new HttpException(500, 'Internal Server Error');
}
// send headers to ensure the client is able to detect a corrupted download
// example : less bytes than the expected range
// send meta data
// setup client's cache behavior
header('Expires: Mon, 26 Nov 1962 00:00:00 GMT');
header('Pragma: private'); /// IE BUG + SSL
header('Cache-control: private, must-revalidate'); /// IE BUG + SSL
header('Content-disposition: attachment; filename="' . $this->fields['filename'] . '"');
header("Content-type: $mimeType");
header("Last-Modified: $time");
header('Accept-Ranges: bytes');
header('Content-Length:' . ($end - $begin + 1));
header("Content-Range: bytes $begin-$end/$size");
header("Content-Transfer-Encoding: binary\n");
header('Connection: close');
// Prepare HTTP response
if ($begin > 0 || $end < $size - 1) {
header('HTTP/1.0 206 Partial Content');
} else {
header('HTTP/1.0 200 OK');
}
// Sends bytes until the end of the range or connection closed
while (!feof($fileHandle) && $currentPosition < $end && (connection_status() == 0)) {
// allow a few seconds to send a few KB.
set_time_limit(10);
$content = fread($fileHandle, min(1024 * 16, $end - $currentPosition + 1));
if (empty($content)) {
throw new HttpException(500, 'Internal Server Error');
} else {
print $content;
}
flush();
$currentPosition += 1024 * 16;
}
// End now to prevent any unwanted bytes
return;
}
}