599f38f9 |
1 | <?php //$Id$ |
2 | |
edc0c493 |
3 | /////////////////////////////////////////////////////////////////////////// |
4 | // // |
5 | // NOTICE OF COPYRIGHT // |
6 | // // |
7 | // Moodle - Modular Object-Oriented Dynamic Learning Environment // |
8 | // http://moodle.org // |
9 | // // |
10 | // Copyright (C) 1999 onwards Martin Dougiamas http://dougiamas.com // |
11 | // // |
12 | // This program is free software; you can redistribute it and/or modify // |
13 | // it under the terms of the GNU General Public License as published by // |
14 | // the Free Software Foundation; either version 2 of the License, or // |
15 | // (at your option) any later version. // |
16 | // // |
17 | // This program is distributed in the hope that it will be useful, // |
18 | // but WITHOUT ANY WARRANTY; without even the implied warranty of // |
19 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // |
20 | // GNU General Public License for more details: // |
21 | // // |
22 | // http://www.gnu.org/copyleft/gpl.html // |
23 | // // |
24 | /////////////////////////////////////////////////////////////////////////// |
25 | |
26 | /** |
27 | * Functions for file handling. |
28 | * |
29 | * @license http://www.gnu.org/copyleft/gpl.html GNU Public License |
30 | * @package files |
31 | */ |
32 | |
33 | /** @var string unique string constant. */ |
34 | define('BYTESERVING_BOUNDARY', 's1k2o3d4a5k6s7'); |
4c8c65ec |
35 | |
172dd12c |
36 | require_once("$CFG->libdir/file/file_exceptions.php"); |
37 | require_once("$CFG->libdir/file/file_storage.php"); |
38 | require_once("$CFG->libdir/file/file_browser.php"); |
0b0bfa93 |
39 | |
40 | require_once("$CFG->libdir/packer/zip_packer.php"); |
172dd12c |
41 | |
509f67e3 |
42 | /** |
43 | * Given a physical path to a file, returns the URL through which it can be reached in Moodle. |
44 | * @param string $path Physical path to a file |
45 | * @param array $options associative array of GET variables to append to the URL |
46 | * @param string $type (questionfile|rssfile|user|usergroup|httpscoursefile|coursefile) |
47 | * @return string URL to file |
48 | */ |
74369ab5 |
49 | function get_file_url($path, $options=null, $type='coursefile') { |
f86eb734 |
50 | global $CFG, $HTTPSPAGEREQUIRED; |
74369ab5 |
51 | |
172dd12c |
52 | $path = str_replace('//', '/', $path); |
74369ab5 |
53 | $path = trim($path, '/'); // no leading and trailing slashes |
54 | |
55 | // type of file |
56 | switch ($type) { |
5a254a29 |
57 | case 'questionfile': |
58 | $url = $CFG->wwwroot."/question/exportfile.php"; |
59 | break; |
60 | case 'rssfile': |
61 | $url = $CFG->wwwroot."/rss/file.php"; |
62 | break; |
63 | case 'user': |
f86eb734 |
64 | if (!empty($HTTPSPAGEREQUIRED)) { |
65 | $wwwroot = $CFG->httpswwwroot; |
66 | } |
67 | else { |
68 | $wwwroot = $CFG->wwwroot; |
69 | } |
70 | $url = $wwwroot."/user/pix.php"; |
5a254a29 |
71 | break; |
72 | case 'usergroup': |
11e7b506 |
73 | $url = $CFG->wwwroot."/user/grouppix.php"; |
5a254a29 |
74 | break; |
75 | case 'httpscoursefile': |
76 | $url = $CFG->httpswwwroot."/file.php"; |
77 | break; |
78 | case 'coursefile': |
74369ab5 |
79 | default: |
5a254a29 |
80 | $url = $CFG->wwwroot."/file.php"; |
74369ab5 |
81 | } |
82 | |
83 | if ($CFG->slasharguments) { |
84 | $parts = explode('/', $path); |
546fef5f |
85 | foreach ($parts as $key => $part) { |
86 | /// anchor dash character should not be encoded |
87 | $subparts = explode('#', $part); |
88 | $subparts = array_map('rawurlencode', $subparts); |
89 | $parts[$key] = implode('#', $subparts); |
90 | } |
74369ab5 |
91 | $path = implode('/', $parts); |
5a254a29 |
92 | $ffurl = $url.'/'.$path; |
74369ab5 |
93 | $separator = '?'; |
94 | } else { |
5a254a29 |
95 | $path = rawurlencode('/'.$path); |
96 | $ffurl = $url.'?file='.$path; |
74369ab5 |
97 | $separator = '&'; |
98 | } |
99 | |
100 | if ($options) { |
101 | foreach ($options as $name=>$value) { |
102 | $ffurl = $ffurl.$separator.$name.'='.$value; |
103 | $separator = '&'; |
104 | } |
105 | } |
106 | |
107 | return $ffurl; |
108 | } |
109 | |
c94882ff |
110 | /** |
111 | * Prepares standardised text field fro editing with Editor formslib element |
112 | * @param object $data $database entry field |
113 | * @param string $field name of data field |
114 | * @param array $options various options |
115 | * @param object $context context, required for existing data |
116 | * @param string $filearea file area name |
117 | * @param int $itemid item id, required if item exists |
118 | * @return object modified data object |
119 | */ |
120 | function file_prepare_standard_editor($data, $field, array $options, $context=null, $filearea=null, $itemid=null) { |
121 | $options = (array)$options; |
122 | if (!isset($options['trusttext'])) { |
123 | $options['trusttext'] = false; |
124 | } |
125 | if (!isset($options['forcehttps'])) { |
126 | $options['forcehttps'] = false; |
127 | } |
128 | if (!isset($options['subdirs'])) { |
129 | $options['subdirs'] = false; |
130 | } |
131 | |
132 | if (empty($data->id) or empty($context)) { |
133 | $contextid = null; |
134 | $data->id = null; |
135 | if (!isset($data->{$field})) { |
136 | $data->{$field} = ''; |
137 | } |
138 | if (!isset($data->{$field.'format'})) { |
139 | $data->{$field.'format'} = FORMAT_HTML; // TODO: use better default |
140 | } |
141 | $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'}); |
142 | |
143 | } else { |
144 | if ($options['trusttext']) { |
145 | if (!isset($data->{$field.'trust'})) { |
146 | $data->{$field.'trust'} = 0; |
147 | } |
148 | $data = trusttext_pre_edit($data, $field, $context); |
149 | } else { |
150 | $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'}); |
151 | } |
152 | $contextid = $context->id; |
153 | } |
154 | |
155 | $draftid_editor = file_get_submitted_draft_itemid($field); |
156 | $currenttext = file_prepare_draft_area($draftid_editor, $contextid, $filearea, $data->id, $options['subdirs'], $data->{$field}, $options['forcehttps']); |
85db95e7 |
157 | $data->{$field.'_editor'} = array('text'=>$currenttext, 'format'=>$data->{$field.'format'}, 'itemid'=>$draftid_editor); |
c94882ff |
158 | |
159 | return $data; |
160 | } |
161 | |
162 | /** |
163 | * Prepares editing with File manager formslib element |
164 | * @param object $data $database entry field |
165 | * @param string $field name of data field |
166 | * @param array $options various options |
167 | * @param object $context context, required for existing data |
168 | * @param string $filearea file area name |
169 | * @param int $itemid item id, required if item exists |
170 | * @return object modified data object |
171 | */ |
172 | function file_postupdate_standard_editor($data, $field, array $options, $context, $filearea, $itemid) { |
173 | $options = (array)$options; |
174 | if (!isset($options['trusttext'])) { |
175 | $options['trusttext'] = false; |
176 | } |
177 | if (!isset($options['forcehttps'])) { |
178 | $options['forcehttps'] = false; |
179 | } |
180 | if (!isset($options['subdirs'])) { |
181 | $options['subdirs'] = false; |
182 | } |
183 | if (!isset($options['maxfiles'])) { |
85db95e7 |
184 | $options['maxfiles'] = 0; // no files by default |
c94882ff |
185 | } |
186 | if (!isset($options['maxbytes'])) { |
187 | $options['maxbytes'] = 0; // unlimited |
188 | } |
189 | |
190 | if ($options['trusttext']) { |
191 | $data->definitiontrust = trusttext_trusted($context); |
192 | } else { |
193 | $data->definitiontrust = 0; |
194 | } |
195 | |
85db95e7 |
196 | $editor = $data->{$field.'_editor'}; |
c94882ff |
197 | |
198 | $data->{$field} = file_save_draft_area_files($editor['itemid'], $context->id, $filearea, $itemid, $options, $editor['text'], $options['forcehttps']); |
199 | $data->{$field.'format'} = $editor['format']; |
200 | |
201 | return $data; |
202 | } |
203 | |
204 | /** |
205 | * Saves text and files modified by Editor formslib element |
206 | * @param object $data $database entry field |
207 | * @param string $field name of data field |
208 | * @param array $options various options |
209 | * @param object $context context - must already exist |
210 | * @param string $filearea file area name |
211 | * @param int $itemid must already exist, usually means data is in db |
212 | * @return object modified data obejct |
213 | */ |
214 | function file_prepare_standard_filemanager($data, $field, array $options, $context=null, $filearea=null, $itemid=null) { |
215 | $options = (array)$options; |
216 | if (!isset($options['subdirs'])) { |
217 | $options['subdirs'] = false; |
218 | } |
219 | if (empty($data->id) or empty($context)) { |
220 | $data->id = null; |
221 | $contextid = null; |
222 | } else { |
223 | $contextid = $context->id; |
224 | } |
225 | |
85db95e7 |
226 | $draftid_editor = file_get_submitted_draft_itemid($field.'_filemanager'); |
c94882ff |
227 | file_prepare_draft_area($draftid_editor, $contextid, $filearea, $data->id, $options['subdirs']); |
85db95e7 |
228 | $data->{$field.'_filemanager'} = $draftid_editor; |
c94882ff |
229 | |
230 | return $data; |
231 | } |
232 | |
233 | /** |
234 | * Saves files modified by File manager formslib element |
235 | * @param object $data $database entry field |
236 | * @param string $field name of data field |
237 | * @param array $options various options |
238 | * @param object $context context - must already exist |
239 | * @param string $filearea file area name |
240 | * @param int $itemid must already exist, usually means data is in db |
241 | * @return object modified data obejct |
242 | */ |
243 | function file_postupdate_standard_filemanager($data, $field, array $options, $context, $filearea, $itemid) { |
244 | $options = (array)$options; |
245 | if (!isset($options['subdirs'])) { |
246 | $options['subdirs'] = false; |
247 | } |
248 | if (!isset($options['maxfiles'])) { |
249 | $options['maxfiles'] = -1; // unlimited |
250 | } |
251 | if (!isset($options['maxbytes'])) { |
252 | $options['maxbytes'] = 0; // unlimited |
253 | } |
254 | |
85db95e7 |
255 | if (empty($data->{$field.'_filemanager'})) { |
c94882ff |
256 | $data->$field = ''; |
257 | |
258 | } else { |
85db95e7 |
259 | file_save_draft_area_files($data->{$field.'_filemanager'}, $context->id, $filearea, $data->id, $options); |
c94882ff |
260 | $fs = get_file_storage(); |
261 | |
262 | if ($fs->get_area_files($context->id, $filearea, $itemid)) { |
263 | $data->$field = '1'; // TODO: this is an ugly hack |
264 | } else { |
265 | $data->$field = ''; |
266 | } |
267 | } |
268 | |
269 | return $data; |
270 | } |
271 | |
8546def3 |
272 | /** |
509f67e3 |
273 | * @return int a random but available draft itemid that can be used to create a new draft |
edc0c493 |
274 | * file area. |
8546def3 |
275 | */ |
edc0c493 |
276 | function file_get_unused_draft_itemid() { |
8546def3 |
277 | global $DB, $USER; |
278 | |
279 | if (isguestuser() or !isloggedin()) { |
85db95e7 |
280 | // guests and not-logged-in users can not be allowed to upload anything!!!!!! |
8546def3 |
281 | print_error('noguest'); |
282 | } |
283 | |
284 | $contextid = get_context_instance(CONTEXT_USER, $USER->id)->id; |
285 | $filearea = 'user_draft'; |
286 | |
287 | $fs = get_file_storage(); |
288 | $draftitemid = rand(1, 999999999); |
289 | while ($files = $fs->get_area_files($contextid, $filearea, $draftitemid)) { |
290 | $draftitemid = rand(1, 999999999); |
291 | } |
292 | |
b933a139 |
293 | return $draftitemid; |
8546def3 |
294 | } |
295 | |
7983d682 |
296 | /** |
edc0c493 |
297 | * Initialise a draft file area from a real one by copying the files. A draft |
298 | * area will be created if one does not already exist. Normally you should |
299 | * get $draftitemid by calling file_get_submitted_draft_itemid('elementname'); |
300 | * @param int &$draftitemid the id of the draft area to use, or 0 to create a new one, in which case this parameter is updated. |
301 | * @param integer $contextid This parameter and the next two identify the file area to copy files from. |
302 | * @param string $filearea helps indentify the file area. |
303 | * @param integer $itemid helps identify the file area. Can be null if there are no files yet. |
304 | * @param boolean $subdirs allow directory structure within the file area. |
305 | * @param string $text some html content that needs to have embedded links rewritten to point to the draft area. |
306 | * @param boolean $forcehttps force https urls. |
307 | * @return string if $text was passed in, the rewritten $text is returned. Otherwise NULL. |
7983d682 |
308 | */ |
edc0c493 |
309 | function file_prepare_draft_area(&$draftitemid, $contextid, $filearea, $itemid, $subdirs=false, $text=null, $forcehttps=false) { |
7983d682 |
310 | global $CFG, $USER; |
311 | |
8546def3 |
312 | $usercontext = get_context_instance(CONTEXT_USER, $USER->id); |
b933a139 |
313 | $fs = get_file_storage(); |
314 | |
315 | if (empty($draftitemid)) { |
316 | // create a new area and copy existing files into |
edc0c493 |
317 | $draftitemid = file_get_unused_draft_itemid(); |
b933a139 |
318 | $file_record = array('contextid'=>$usercontext->id, 'filearea'=>'user_draft', 'itemid'=>$draftitemid); |
12fab708 |
319 | if (!is_null($itemid) and $files = $fs->get_area_files($contextid, $filearea, $itemid)) { |
b933a139 |
320 | foreach ($files as $file) { |
12fab708 |
321 | if (!$subdirs and ($file->is_directory() or $file->get_filepath() !== '/')) { |
b5b188ce |
322 | continue; |
323 | } |
b933a139 |
324 | $fs->create_file_from_storedfile($file_record, $file); |
325 | } |
326 | } |
327 | } else { |
328 | // nothing to do |
329 | } |
330 | |
331 | if (is_null($text)) { |
332 | return null; |
333 | } |
334 | |
edc0c493 |
335 | // relink embedded files - editor can not handle @@PLUGINFILE@@ ! |
336 | return file_rewrite_pluginfile_urls($text, 'draftfile.php', $usercontext->id, 'user_draft', $draftitemid, $forcehttps); |
644d506a |
337 | } |
338 | |
339 | /** |
edc0c493 |
340 | * Convert encoded URLs in $text from the @@PLUGINFILE@@/... form to an actual URL. |
341 | * @param string $text The content that may contain ULRs in need of rewriting. |
342 | * @param string $file The script that should be used to serve these files. pluginfile.php, draftfile.php, etc. |
343 | * @param integer $contextid This parameter and the next two identify the file area to use. |
344 | * @param string $filearea helps indentify the file area. |
345 | * @param integer $itemid helps identify the file area. |
346 | * @param boot $forcehttps if we should output a https URL. |
347 | * @return string the processed text. |
644d506a |
348 | */ |
edc0c493 |
349 | function file_rewrite_pluginfile_urls($text, $file, $contextid, $filearea, $itemid, $forcehttps=false) { |
644d506a |
350 | global $CFG; |
b933a139 |
351 | |
edc0c493 |
352 | if (!$CFG->slasharguments) { |
353 | $file = $file . '?file='; |
b933a139 |
354 | } |
8546def3 |
355 | |
7d2948bd |
356 | $baseurl = "$CFG->wwwroot/$file/$contextid/$filearea/"; |
357 | |
358 | if ($itemid !== null) { |
359 | $baseurl .= "$itemid/"; |
360 | } |
edc0c493 |
361 | |
b933a139 |
362 | if ($forcehttps) { |
edc0c493 |
363 | $baseurl = str_replace('http://', 'https://', $baseurl); |
b933a139 |
364 | } |
365 | |
edc0c493 |
366 | return str_replace('@@PLUGINFILE@@/', $baseurl, $text); |
b933a139 |
367 | } |
368 | |
12fab708 |
369 | /** |
edc0c493 |
370 | * Returns information about files in a draft area. |
371 | * @param integer $draftitemid the draft area item id. |
372 | * @return array with the following entries: |
373 | * 'filecount' => number of files in the draft area. |
374 | * (more information will be added as needed). |
12fab708 |
375 | */ |
edc0c493 |
376 | function file_get_draft_area_info($draftitemid) { |
12fab708 |
377 | global $CFG, $USER; |
378 | |
379 | $usercontext = get_context_instance(CONTEXT_USER, $USER->id); |
380 | $fs = get_file_storage(); |
381 | |
edc0c493 |
382 | $results = array(); |
383 | |
384 | // The number of files |
12fab708 |
385 | $draftfiles = $fs->get_area_files($usercontext->id, 'user_draft', $draftitemid, 'id', false); |
4f5521dd |
386 | $results['filecount'] = count($draftfiles); |
12fab708 |
387 | |
edc0c493 |
388 | return $results; |
12fab708 |
389 | } |
390 | |
3156b8ca |
391 | /** |
edc0c493 |
392 | * Returns draft area itemid for a given element. |
393 | * @param string $elname name of formlib editor element, or a hidden form field that stores the draft area item id, etc. |
394 | * @return inteter the itemid, or 0 if there is not one yet. |
3156b8ca |
395 | */ |
edc0c493 |
396 | function file_get_submitted_draft_itemid($elname) { |
397 | $param = optional_param($elname, 0, PARAM_INT); |
398 | if ($param) { |
399 | confirm_sesskey(); |
400 | } |
401 | if (is_array($param)) { |
402 | $param = $param['itemid']; |
3156b8ca |
403 | } |
edc0c493 |
404 | return $param; |
3156b8ca |
405 | } |
406 | |
b933a139 |
407 | /** |
edc0c493 |
408 | * Saves files from a draft file area to a real one (merging the list of files). |
409 | * Can rewrite URLs in some content at the same time if desired. |
410 | * @param int $draftitemid the id of the draft area to use. Normally obtained |
411 | * from file_get_submitted_draft_itemid('elementname') or similar. |
412 | * @param integer $contextid This parameter and the next two identify the file area to save to. |
a08171c5 |
413 | * @param string $filearea indentifies the file area. |
414 | * @param integer $itemid helps identifies the file area. |
415 | * @param array $optionss area options (subdirs=>false, maxfiles=-1, maxbytes=0) |
edc0c493 |
416 | * @param string $text some html content that needs to have embedded links rewritten |
417 | * to the @@PLUGINFILE@@ form for saving in the database. |
418 | * @param boolean $forcehttps force https urls. |
419 | * @return string if $text was passed in, the rewritten $text is returned. Otherwise NULL. |
b933a139 |
420 | */ |
a08171c5 |
421 | function file_save_draft_area_files($draftitemid, $contextid, $filearea, $itemid, array $options=null, $text=null, $forcehttps=false) { |
b933a139 |
422 | global $CFG, $USER; |
423 | |
424 | $usercontext = get_context_instance(CONTEXT_USER, $USER->id); |
8546def3 |
425 | $fs = get_file_storage(); |
b933a139 |
426 | |
a08171c5 |
427 | $options = (array)$options; |
428 | if (!isset($options['subdirs'])) { |
429 | $options['subdirs'] = false; |
430 | } |
431 | if (!isset($options['maxfiles'])) { |
432 | $options['maxfiles'] = -1; // unlimited |
433 | } |
434 | if (!isset($options['maxbytes'])) { |
435 | $options['maxbytes'] = 0; // unlimited |
436 | } |
437 | |
b933a139 |
438 | $draftfiles = $fs->get_area_files($usercontext->id, 'user_draft', $draftitemid, 'id'); |
439 | $oldfiles = $fs->get_area_files($contextid, $filearea, $itemid, 'id'); |
440 | |
441 | if (count($draftfiles) < 2) { |
442 | // means there are no files - one file means root dir only ;-) |
443 | $fs->delete_area_files($contextid, $filearea, $itemid); |
444 | |
445 | } else if (count($oldfiles) < 2) { |
a08171c5 |
446 | $filecount = 0; |
b933a139 |
447 | // there were no files before - one file means root dir only ;-) |
8546def3 |
448 | $file_record = array('contextid'=>$contextid, 'filearea'=>$filearea, 'itemid'=>$itemid); |
b933a139 |
449 | foreach ($draftfiles as $file) { |
a08171c5 |
450 | if (!$options['subdirs']) { |
451 | if ($file->get_filepath() !== '/' or $file->is_directory()) { |
452 | continue; |
453 | } |
454 | } |
455 | if ($options['maxbytes'] and $options['maxbytes'] < $file->get_filesize()) { |
456 | // oversized file - should not get here at all |
b5b188ce |
457 | continue; |
458 | } |
a08171c5 |
459 | if ($options['maxfiles'] != -1 and $options['maxfiles'] <= $filecount) { |
460 | // more files - should not get here at all |
461 | break; |
462 | } |
463 | if (!$file->is_directory()) { |
464 | $filecount++; |
465 | } |
b933a139 |
466 | $fs->create_file_from_storedfile($file_record, $file); |
467 | } |
468 | |
469 | } else { |
470 | // we have to merge old and new files - we want to keep file ids for files that were not changed |
471 | $file_record = array('contextid'=>$contextid, 'filearea'=>$filearea, 'itemid'=>$itemid); |
a08171c5 |
472 | |
473 | $newhashes = array(); |
b933a139 |
474 | foreach ($draftfiles as $file) { |
475 | $newhash = sha1($contextid.$filearea.$itemid.$file->get_filepath().$file->get_filename()); |
a08171c5 |
476 | $newhashes[$newhash] = $file; |
477 | } |
478 | $filecount = 0; |
479 | foreach ($oldfiles as $file) { |
480 | $oldhash = $file->get_pathnamehash(); |
481 | if (isset($newhashes[$oldhash])) { |
b933a139 |
482 | if (!$file->is_directory()) { |
a08171c5 |
483 | $filecount++; |
b933a139 |
484 | } |
a08171c5 |
485 | // unchanged file already there |
486 | unset($newhashes[$oldhash]); |
487 | } else { |
488 | // delete files not needed any more |
489 | $file->delete(); |
b933a139 |
490 | } |
b933a139 |
491 | } |
a08171c5 |
492 | |
493 | // now add new files |
494 | foreach ($newhashes as $file) { |
495 | if (!$options['subdirs']) { |
496 | if ($file->get_filepath() !== '/' or $file->is_directory()) { |
497 | continue; |
498 | } |
499 | } |
500 | if ($options['maxbytes'] and $options['maxbytes'] < $file->get_filesize()) { |
501 | // oversized file - should not get here at all |
502 | continue; |
503 | } |
504 | if ($options['maxfiles'] != -1 and $options['maxfiles'] <= $filecount) { |
505 | // more files - should not get here at all |
506 | break; |
507 | } |
508 | if (!$file->is_directory()) { |
509 | $filecount++; |
510 | } |
511 | $fs->create_file_from_storedfile($file_record, $file); |
8546def3 |
512 | } |
513 | } |
514 | |
b933a139 |
515 | // purge the draft area |
516 | $fs->delete_area_files($usercontext->id, 'user_draft', $draftitemid); |
517 | |
8546def3 |
518 | if (is_null($text)) { |
519 | return null; |
520 | } |
521 | |
edc0c493 |
522 | // relink embedded files if text submitted - no absolute links allowed in database! |
7983d682 |
523 | if ($CFG->slasharguments) { |
b5b188ce |
524 | $draftbase = "$CFG->wwwroot/draftfile.php/$usercontext->id/user_draft/$draftitemid/"; |
7983d682 |
525 | } else { |
b5b188ce |
526 | $draftbase = "$CFG->wwwroot/draftfile.php?file=/$usercontext->id/user_draft/$draftitemid/"; |
7983d682 |
527 | } |
528 | |
b933a139 |
529 | if ($forcehttps) { |
7983d682 |
530 | $draftbase = str_replace('http://', 'https://', $draftbase); |
531 | } |
532 | |
644d506a |
533 | $text = str_ireplace($draftbase, '@@PLUGINFILE@@/', $text); |
7983d682 |
534 | |
7983d682 |
535 | return $text; |
536 | } |
537 | |
a83ad946 |
538 | /** |
539 | * Returns description of upload error |
540 | * @param int $errorcode found in $_FILES['filename.ext']['error'] |
541 | * @return error description string, '' if ok |
542 | */ |
543 | function file_get_upload_error($errorcode) { |
a08171c5 |
544 | |
a83ad946 |
545 | switch ($errorcode) { |
546 | case 0: // UPLOAD_ERR_OK - no error |
547 | $errmessage = ''; |
548 | break; |
a08171c5 |
549 | |
a83ad946 |
550 | case 1: // UPLOAD_ERR_INI_SIZE |
551 | $errmessage = get_string('uploadserverlimit'); |
552 | break; |
a08171c5 |
553 | |
a83ad946 |
554 | case 2: // UPLOAD_ERR_FORM_SIZE |
555 | $errmessage = get_string('uploadformlimit'); |
556 | break; |
a08171c5 |
557 | |
a83ad946 |
558 | case 3: // UPLOAD_ERR_PARTIAL |
559 | $errmessage = get_string('uploadpartialfile'); |
560 | break; |
a08171c5 |
561 | |
a83ad946 |
562 | case 4: // UPLOAD_ERR_NO_FILE |
563 | $errmessage = get_string('uploadnofilefound'); |
564 | break; |
a08171c5 |
565 | |
a83ad946 |
566 | // Note: there is no error with a value of 5 |
567 | |
568 | case 6: // UPLOAD_ERR_NO_TMP_DIR |
569 | $errmessage = get_string('uploadnotempdir'); |
570 | break; |
571 | |
572 | case 7: // UPLOAD_ERR_CANT_WRITE |
573 | $errmessage = get_string('uploadcantwrite'); |
574 | break; |
575 | |
576 | case 8: // UPLOAD_ERR_EXTENSION |
577 | $errmessage = get_string('uploadextension'); |
578 | break; |
579 | |
580 | default: |
581 | $errmessage = get_string('uploadproblem'); |
582 | } |
583 | |
584 | return $errmessage; |
585 | } |
586 | |
8ee88311 |
587 | /** |
5f8bdc17 |
588 | * Fetches content of file from Internet (using proxy if defined). Uses cURL extension if present. |
599f06cf |
589 | * Due to security concerns only downloads from http(s) sources are supported. |
590 | * |
591 | * @param string $url file url starting with http(s):// |
5ef082df |
592 | * @param array $headers http headers, null if none. If set, should be an |
593 | * associative array of header name => value pairs. |
6bf55889 |
594 | * @param array $postdata array means use POST request with given parameters |
595 | * @param bool $fullresponse return headers, responses, etc in a similar way snoopy does |
5ef082df |
596 | * (if false, just returns content) |
597 | * @param int $timeout timeout for complete download process including all file transfer |
44e02d79 |
598 | * (default 5 minutes) |
599 | * @param int $connecttimeout timeout for connection to server; this is the timeout that |
600 | * usually happens if the remote server is completely down (default 20 seconds); |
601 | * may not work when using proxy |
83947a36 |
602 | * @param bool $skipcertverify If true, the peer's SSL certificate will not be checked. Only use this when already in a trusted location. |
8ee88311 |
603 | * @return mixed false if request failed or content of the file as string if ok. |
604 | */ |
83947a36 |
605 | function download_file_content($url, $headers=null, $postdata=null, $fullresponse=false, $timeout=300, $connecttimeout=20, $skipcertverify=false) { |
e27f0765 |
606 | global $CFG; |
607 | |
599f06cf |
608 | // some extra security |
609 | $newlines = array("\r", "\n"); |
610 | if (is_array($headers) ) { |
611 | foreach ($headers as $key => $value) { |
612 | $headers[$key] = str_replace($newlines, '', $value); |
613 | } |
614 | } |
615 | $url = str_replace($newlines, '', $url); |
616 | if (!preg_match('|^https?://|i', $url)) { |
617 | if ($fullresponse) { |
618 | $response = new object(); |
619 | $response->status = 0; |
620 | $response->headers = array(); |
621 | $response->response_code = 'Invalid protocol specified in url'; |
622 | $response->results = ''; |
623 | $response->error = 'Invalid protocol specified in url'; |
624 | return $response; |
625 | } else { |
626 | return false; |
627 | } |
628 | } |
629 | |
bb2c046d |
630 | // check if proxy (if used) should be bypassed for this url |
aa944588 |
631 | $proxybypass = is_proxybypass($url); |
632 | |
7fb90df0 |
633 | if (!$ch = curl_init($url)) { |
634 | debugging('Can not init curl.'); |
635 | return false; |
636 | } |
599f06cf |
637 | |
599f06cf |
638 | // set extra headers |
6bf55889 |
639 | if (is_array($headers) ) { |
640 | $headers2 = array(); |
641 | foreach ($headers as $key => $value) { |
6bf55889 |
642 | $headers2[] = "$key: $value"; |
643 | } |
644 | curl_setopt($ch, CURLOPT_HTTPHEADER, $headers2); |
645 | } |
646 | |
bb2c046d |
647 | |
83947a36 |
648 | if ($skipcertverify) { |
649 | curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); |
650 | } |
bb2c046d |
651 | |
6bf55889 |
652 | // use POST if requested |
653 | if (is_array($postdata)) { |
654 | foreach ($postdata as $k=>$v) { |
655 | $postdata[$k] = urlencode($k).'='.urlencode($v); |
5f8bdc17 |
656 | } |
6bf55889 |
657 | $postdata = implode('&', $postdata); |
658 | curl_setopt($ch, CURLOPT_POST, true); |
659 | curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata); |
5f8bdc17 |
660 | } |
661 | |
8ee88311 |
662 | curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); |
6bf55889 |
663 | curl_setopt($ch, CURLOPT_HEADER, true); |
44e02d79 |
664 | curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $connecttimeout); |
665 | curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); |
6bf55889 |
666 | if (!ini_get('open_basedir') and !ini_get('safe_mode')) { |
599f06cf |
667 | // TODO: add version test for '7.10.5' |
6bf55889 |
668 | curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); |
669 | curl_setopt($ch, CURLOPT_MAXREDIRS, 5); |
670 | } |
671 | |
15c31560 |
672 | if (!empty($CFG->proxyhost) and !$proxybypass) { |
5f8bdc17 |
673 | // SOCKS supported in PHP5 only |
674 | if (!empty($CFG->proxytype) and ($CFG->proxytype == 'SOCKS5')) { |
675 | if (defined('CURLPROXY_SOCKS5')) { |
676 | curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5); |
677 | } else { |
5f8bdc17 |
678 | curl_close($ch); |
599f06cf |
679 | if ($fullresponse) { |
680 | $response = new object(); |
681 | $response->status = '0'; |
682 | $response->headers = array(); |
683 | $response->response_code = 'SOCKS5 proxy is not supported in PHP4'; |
684 | $response->results = ''; |
685 | $response->error = 'SOCKS5 proxy is not supported in PHP4'; |
686 | return $response; |
687 | } else { |
688 | debugging("SOCKS5 proxy is not supported in PHP4.", DEBUG_ALL); |
689 | return false; |
690 | } |
5f8bdc17 |
691 | } |
692 | } |
693 | |
08ec989f |
694 | curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, false); |
695 | |
8ee88311 |
696 | if (empty($CFG->proxyport)) { |
e27f0765 |
697 | curl_setopt($ch, CURLOPT_PROXY, $CFG->proxyhost); |
8ee88311 |
698 | } else { |
e27f0765 |
699 | curl_setopt($ch, CURLOPT_PROXY, $CFG->proxyhost.':'.$CFG->proxyport); |
8ee88311 |
700 | } |
5f8bdc17 |
701 | |
702 | if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) { |
8ee88311 |
703 | curl_setopt($ch, CURLOPT_PROXYUSERPWD, $CFG->proxyuser.':'.$CFG->proxypassword); |
5f8bdc17 |
704 | if (defined('CURLOPT_PROXYAUTH')) { |
705 | // any proxy authentication if PHP 5.1 |
706 | curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_BASIC | CURLAUTH_NTLM); |
707 | } |
8ee88311 |
708 | } |
709 | } |
6bf55889 |
710 | |
599f06cf |
711 | $data = curl_exec($ch); |
08ec989f |
712 | |
599f06cf |
713 | // try to detect encoding problems |
6bf55889 |
714 | if ((curl_errno($ch) == 23 or curl_errno($ch) == 61) and defined('CURLOPT_ENCODING')) { |
715 | curl_setopt($ch, CURLOPT_ENCODING, 'none'); |
599f06cf |
716 | $data = curl_exec($ch); |
6bf55889 |
717 | } |
718 | |
08ec989f |
719 | if (curl_errno($ch)) { |
6bf55889 |
720 | $error = curl_error($ch); |
721 | $error_no = curl_errno($ch); |
722 | curl_close($ch); |
723 | |
724 | if ($fullresponse) { |
725 | $response = new object(); |
726 | if ($error_no == 28) { |
727 | $response->status = '-100'; // mimic snoopy |
728 | } else { |
729 | $response->status = '0'; |
730 | } |
731 | $response->headers = array(); |
732 | $response->response_code = $error; |
733 | $response->results = ''; |
734 | $response->error = $error; |
735 | return $response; |
736 | } else { |
599f06cf |
737 | debugging("cURL request for \"$url\" failed with: $error ($error_no)", DEBUG_ALL); |
6bf55889 |
738 | return false; |
739 | } |
5f8bdc17 |
740 | |
741 | } else { |
6bf55889 |
742 | $info = curl_getinfo($ch); |
743 | curl_close($ch); |
599f06cf |
744 | |
745 | if (empty($info['http_code'])) { |
746 | // for security reasons we support only true http connections (Location: file:// exploit prevention) |
747 | $response = new object(); |
748 | $response->status = '0'; |
749 | $response->headers = array(); |
750 | $response->response_code = 'Unknown cURL error'; |
751 | $response->results = ''; // do NOT change this! |
752 | $response->error = 'Unknown cURL error'; |
753 | |
754 | } else { |
755 | // strip redirect headers and get headers array and content |
756 | $data = explode("\r\n\r\n", $data, $info['redirect_count'] + 2); |
757 | $results = array_pop($data); |
758 | $headers = array_pop($data); |
759 | $headers = explode("\r\n", trim($headers)); |
760 | |
761 | $response = new object();; |
762 | $response->status = (string)$info['http_code']; |
763 | $response->headers = $headers; |
764 | $response->response_code = $headers[0]; |
765 | $response->results = $results; |
766 | $response->error = ''; |
767 | } |
6bf55889 |
768 | |
769 | if ($fullresponse) { |
770 | return $response; |
771 | } else if ($info['http_code'] != 200) { |
599f06cf |
772 | debugging("cURL request for \"$url\" failed, HTTP response code: ".$response->response_code, DEBUG_ALL); |
6bf55889 |
773 | return false; |
774 | } else { |
775 | return $response->results; |
5f8bdc17 |
776 | } |
08ec989f |
777 | } |
8ee88311 |
778 | } |
779 | |
3ce73b14 |
780 | /** |
76ca1ff1 |
781 | * @return List of information about file types based on extensions. |
3ce73b14 |
782 | * Associative array of extension (lower-case) to associative array |
783 | * from 'element name' to data. Current element names are 'type' and 'icon'. |
76ca1ff1 |
784 | * Unknown types should use the 'xxx' entry which includes defaults. |
3ce73b14 |
785 | */ |
786 | function get_mimetypes_array() { |
172dd12c |
787 | static $mimearray = array ( |
a370c895 |
788 | 'xxx' => array ('type'=>'document/unknown', 'icon'=>'unknown.gif'), |
789 | '3gp' => array ('type'=>'video/quicktime', 'icon'=>'video.gif'), |
790 | 'ai' => array ('type'=>'application/postscript', 'icon'=>'image.gif'), |
791 | 'aif' => array ('type'=>'audio/x-aiff', 'icon'=>'audio.gif'), |
792 | 'aiff' => array ('type'=>'audio/x-aiff', 'icon'=>'audio.gif'), |
793 | 'aifc' => array ('type'=>'audio/x-aiff', 'icon'=>'audio.gif'), |
794 | 'applescript' => array ('type'=>'text/plain', 'icon'=>'text.gif'), |
795 | 'asc' => array ('type'=>'text/plain', 'icon'=>'text.gif'), |
18bf47ef |
796 | 'asm' => array ('type'=>'text/plain', 'icon'=>'text.gif'), |
a370c895 |
797 | 'au' => array ('type'=>'audio/au', 'icon'=>'audio.gif'), |
798 | 'avi' => array ('type'=>'video/x-ms-wm', 'icon'=>'avi.gif'), |
799 | 'bmp' => array ('type'=>'image/bmp', 'icon'=>'image.gif'), |
18bf47ef |
800 | 'c' => array ('type'=>'text/plain', 'icon'=>'text.gif'), |
a370c895 |
801 | 'cct' => array ('type'=>'shockwave/director', 'icon'=>'flash.gif'), |
18bf47ef |
802 | 'cpp' => array ('type'=>'text/plain', 'icon'=>'text.gif'), |
a370c895 |
803 | 'cs' => array ('type'=>'application/x-csh', 'icon'=>'text.gif'), |
76ca1ff1 |
804 | 'css' => array ('type'=>'text/css', 'icon'=>'text.gif'), |
6ae5e482 |
805 | 'csv' => array ('type'=>'text/csv', 'icon'=>'excel.gif'), |
a370c895 |
806 | 'dv' => array ('type'=>'video/x-dv', 'icon'=>'video.gif'), |
609d84e3 |
807 | 'dmg' => array ('type'=>'application/octet-stream', 'icon'=>'dmg.gif'), |
13499032 |
808 | |
a370c895 |
809 | 'doc' => array ('type'=>'application/msword', 'icon'=>'word.gif'), |
13499032 |
810 | 'docx' => array ('type'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'icon'=>'docx.gif'), |
811 | 'docm' => array ('type'=>'application/vnd.ms-word.document.macroEnabled.12', 'icon'=>'docm.gif'), |
812 | 'dotx' => array ('type'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.template', 'icon'=>'dotx.gif'), |
813 | 'dotm' => array ('type'=>'application/vnd.ms-word.template.macroEnabled.12', 'icon'=>'dotm.gif'), |
814 | |
a370c895 |
815 | 'dcr' => array ('type'=>'application/x-director', 'icon'=>'flash.gif'), |
816 | 'dif' => array ('type'=>'video/x-dv', 'icon'=>'video.gif'), |
817 | 'dir' => array ('type'=>'application/x-director', 'icon'=>'flash.gif'), |
818 | 'dxr' => array ('type'=>'application/x-director', 'icon'=>'flash.gif'), |
819 | 'eps' => array ('type'=>'application/postscript', 'icon'=>'pdf.gif'), |
ee7f231d |
820 | 'fdf' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'), |
759bc3c8 |
821 | 'flv' => array ('type'=>'video/x-flv', 'icon'=>'video.gif'), |
a370c895 |
822 | 'gif' => array ('type'=>'image/gif', 'icon'=>'image.gif'), |
823 | 'gtar' => array ('type'=>'application/x-gtar', 'icon'=>'zip.gif'), |
759bc3c8 |
824 | 'tgz' => array ('type'=>'application/g-zip', 'icon'=>'zip.gif'), |
a370c895 |
825 | 'gz' => array ('type'=>'application/g-zip', 'icon'=>'zip.gif'), |
826 | 'gzip' => array ('type'=>'application/g-zip', 'icon'=>'zip.gif'), |
827 | 'h' => array ('type'=>'text/plain', 'icon'=>'text.gif'), |
18bf47ef |
828 | 'hpp' => array ('type'=>'text/plain', 'icon'=>'text.gif'), |
a370c895 |
829 | 'hqx' => array ('type'=>'application/mac-binhex40', 'icon'=>'zip.gif'), |
70ee2841 |
830 | 'htc' => array ('type'=>'text/x-component', 'icon'=>'text.gif'), |
a370c895 |
831 | 'html' => array ('type'=>'text/html', 'icon'=>'html.gif'), |
1659a998 |
832 | 'xhtml'=> array ('type'=>'application/xhtml+xml', 'icon'=>'html.gif'), |
a370c895 |
833 | 'htm' => array ('type'=>'text/html', 'icon'=>'html.gif'), |
08297dcb |
834 | 'ico' => array ('type'=>'image/vnd.microsoft.icon', 'icon'=>'image.gif'), |
4b270c4c |
835 | 'ics' => array ('type'=>'text/calendar', 'icon'=>'text.gif'), |
08297dcb |
836 | 'isf' => array ('type'=>'application/inspiration', 'icon'=>'isf.gif'), |
837 | 'ist' => array ('type'=>'application/inspiration.template', 'icon'=>'isf.gif'), |
18bf47ef |
838 | 'java' => array ('type'=>'text/plain', 'icon'=>'text.gif'), |
a00420fb |
839 | 'jcb' => array ('type'=>'text/xml', 'icon'=>'jcb.gif'), |
840 | 'jcl' => array ('type'=>'text/xml', 'icon'=>'jcl.gif'), |
841 | 'jcw' => array ('type'=>'text/xml', 'icon'=>'jcw.gif'), |
842 | 'jmt' => array ('type'=>'text/xml', 'icon'=>'jmt.gif'), |
843 | 'jmx' => array ('type'=>'text/xml', 'icon'=>'jmx.gif'), |
a370c895 |
844 | 'jpe' => array ('type'=>'image/jpeg', 'icon'=>'image.gif'), |
845 | 'jpeg' => array ('type'=>'image/jpeg', 'icon'=>'image.gif'), |
846 | 'jpg' => array ('type'=>'image/jpeg', 'icon'=>'image.gif'), |
a00420fb |
847 | 'jqz' => array ('type'=>'text/xml', 'icon'=>'jqz.gif'), |
a370c895 |
848 | 'js' => array ('type'=>'application/x-javascript', 'icon'=>'text.gif'), |
849 | 'latex'=> array ('type'=>'application/x-latex', 'icon'=>'text.gif'), |
850 | 'm' => array ('type'=>'text/plain', 'icon'=>'text.gif'), |
851 | 'mov' => array ('type'=>'video/quicktime', 'icon'=>'video.gif'), |
852 | 'movie'=> array ('type'=>'video/x-sgi-movie', 'icon'=>'video.gif'), |
853 | 'm3u' => array ('type'=>'audio/x-mpegurl', 'icon'=>'audio.gif'), |
854 | 'mp3' => array ('type'=>'audio/mp3', 'icon'=>'audio.gif'), |
855 | 'mp4' => array ('type'=>'video/mp4', 'icon'=>'video.gif'), |
856 | 'mpeg' => array ('type'=>'video/mpeg', 'icon'=>'video.gif'), |
857 | 'mpe' => array ('type'=>'video/mpeg', 'icon'=>'video.gif'), |
858 | 'mpg' => array ('type'=>'video/mpeg', 'icon'=>'video.gif'), |
5395334d |
859 | |
860 | 'odt' => array ('type'=>'application/vnd.oasis.opendocument.text', 'icon'=>'odt.gif'), |
861 | 'ott' => array ('type'=>'application/vnd.oasis.opendocument.text-template', 'icon'=>'odt.gif'), |
862 | 'oth' => array ('type'=>'application/vnd.oasis.opendocument.text-web', 'icon'=>'odt.gif'), |
e10bc440 |
863 | 'odm' => array ('type'=>'application/vnd.oasis.opendocument.text-master', 'icon'=>'odm.gif'), |
864 | 'odg' => array ('type'=>'application/vnd.oasis.opendocument.graphics', 'icon'=>'odg.gif'), |
865 | 'otg' => array ('type'=>'application/vnd.oasis.opendocument.graphics-template', 'icon'=>'odg.gif'), |
866 | 'odp' => array ('type'=>'application/vnd.oasis.opendocument.presentation', 'icon'=>'odp.gif'), |
867 | 'otp' => array ('type'=>'application/vnd.oasis.opendocument.presentation-template', 'icon'=>'odp.gif'), |
868 | 'ods' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet', 'icon'=>'ods.gif'), |
869 | 'ots' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet-template', 'icon'=>'ods.gif'), |
870 | 'odc' => array ('type'=>'application/vnd.oasis.opendocument.chart', 'icon'=>'odc.gif'), |
871 | 'odf' => array ('type'=>'application/vnd.oasis.opendocument.formula', 'icon'=>'odf.gif'), |
872 | 'odb' => array ('type'=>'application/vnd.oasis.opendocument.database', 'icon'=>'odb.gif'), |
873 | 'odi' => array ('type'=>'application/vnd.oasis.opendocument.image', 'icon'=>'odi.gif'), |
5395334d |
874 | |
a370c895 |
875 | 'pct' => array ('type'=>'image/pict', 'icon'=>'image.gif'), |
876 | 'pdf' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'), |
877 | 'php' => array ('type'=>'text/plain', 'icon'=>'text.gif'), |
878 | 'pic' => array ('type'=>'image/pict', 'icon'=>'image.gif'), |
879 | 'pict' => array ('type'=>'image/pict', 'icon'=>'image.gif'), |
880 | 'png' => array ('type'=>'image/png', 'icon'=>'image.gif'), |
13499032 |
881 | |
a370c895 |
882 | 'pps' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint.gif'), |
883 | 'ppt' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint.gif'), |
13499032 |
884 | 'pptx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'icon'=>'pptx.gif'), |
885 | 'pptm' => array ('type'=>'application/vnd.ms-powerpoint.presentation.macroEnabled.12', 'icon'=>'pptm.gif'), |
886 | 'potx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.template', 'icon'=>'potx.gif'), |
887 | 'potm' => array ('type'=>'application/vnd.ms-powerpoint.template.macroEnabled.12', 'icon'=>'potm.gif'), |
888 | 'ppam' => array ('type'=>'application/vnd.ms-powerpoint.addin.macroEnabled.12', 'icon'=>'ppam.gif'), |
889 | 'ppsx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.slideshow', 'icon'=>'ppsx.gif'), |
890 | 'ppsm' => array ('type'=>'application/vnd.ms-powerpoint.slideshow.macroEnabled.12', 'icon'=>'ppsm.gif'), |
891 | |
a370c895 |
892 | 'ps' => array ('type'=>'application/postscript', 'icon'=>'pdf.gif'), |
893 | 'qt' => array ('type'=>'video/quicktime', 'icon'=>'video.gif'), |
894 | 'ra' => array ('type'=>'audio/x-realaudio', 'icon'=>'audio.gif'), |
895 | 'ram' => array ('type'=>'audio/x-pn-realaudio', 'icon'=>'audio.gif'), |
a00420fb |
896 | 'rhb' => array ('type'=>'text/xml', 'icon'=>'xml.gif'), |
a370c895 |
897 | 'rm' => array ('type'=>'audio/x-pn-realaudio', 'icon'=>'audio.gif'), |
898 | 'rtf' => array ('type'=>'text/rtf', 'icon'=>'text.gif'), |
899 | 'rtx' => array ('type'=>'text/richtext', 'icon'=>'text.gif'), |
900 | 'sh' => array ('type'=>'application/x-sh', 'icon'=>'text.gif'), |
901 | 'sit' => array ('type'=>'application/x-stuffit', 'icon'=>'zip.gif'), |
902 | 'smi' => array ('type'=>'application/smil', 'icon'=>'text.gif'), |
903 | 'smil' => array ('type'=>'application/smil', 'icon'=>'text.gif'), |
a00420fb |
904 | 'sqt' => array ('type'=>'text/xml', 'icon'=>'xml.gif'), |
4db69ffb |
905 | 'svg' => array ('type'=>'image/svg+xml', 'icon'=>'image.gif'), |
906 | 'svgz' => array ('type'=>'image/svg+xml', 'icon'=>'image.gif'), |
a370c895 |
907 | 'swa' => array ('type'=>'application/x-director', 'icon'=>'flash.gif'), |
908 | 'swf' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash.gif'), |
909 | 'swfl' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash.gif'), |
5395334d |
910 | |
911 | 'sxw' => array ('type'=>'application/vnd.sun.xml.writer', 'icon'=>'odt.gif'), |
912 | 'stw' => array ('type'=>'application/vnd.sun.xml.writer.template', 'icon'=>'odt.gif'), |
913 | 'sxc' => array ('type'=>'application/vnd.sun.xml.calc', 'icon'=>'odt.gif'), |
914 | 'stc' => array ('type'=>'application/vnd.sun.xml.calc.template', 'icon'=>'odt.gif'), |
915 | 'sxd' => array ('type'=>'application/vnd.sun.xml.draw', 'icon'=>'odt.gif'), |
916 | 'std' => array ('type'=>'application/vnd.sun.xml.draw.template', 'icon'=>'odt.gif'), |
917 | 'sxi' => array ('type'=>'application/vnd.sun.xml.impress', 'icon'=>'odt.gif'), |
918 | 'sti' => array ('type'=>'application/vnd.sun.xml.impress.template', 'icon'=>'odt.gif'), |
919 | 'sxg' => array ('type'=>'application/vnd.sun.xml.writer.global', 'icon'=>'odt.gif'), |
920 | 'sxm' => array ('type'=>'application/vnd.sun.xml.math', 'icon'=>'odt.gif'), |
921 | |
a370c895 |
922 | 'tar' => array ('type'=>'application/x-tar', 'icon'=>'zip.gif'), |
923 | 'tif' => array ('type'=>'image/tiff', 'icon'=>'image.gif'), |
924 | 'tiff' => array ('type'=>'image/tiff', 'icon'=>'image.gif'), |
925 | 'tex' => array ('type'=>'application/x-tex', 'icon'=>'text.gif'), |
926 | 'texi' => array ('type'=>'application/x-texinfo', 'icon'=>'text.gif'), |
927 | 'texinfo' => array ('type'=>'application/x-texinfo', 'icon'=>'text.gif'), |
928 | 'tsv' => array ('type'=>'text/tab-separated-values', 'icon'=>'text.gif'), |
929 | 'txt' => array ('type'=>'text/plain', 'icon'=>'text.gif'), |
930 | 'wav' => array ('type'=>'audio/wav', 'icon'=>'audio.gif'), |
931 | 'wmv' => array ('type'=>'video/x-ms-wmv', 'icon'=>'avi.gif'), |
932 | 'asf' => array ('type'=>'video/x-ms-asf', 'icon'=>'avi.gif'), |
ee7f231d |
933 | 'xdp' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'), |
934 | 'xfd' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'), |
935 | 'xfdf' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'), |
13499032 |
936 | |
a370c895 |
937 | 'xls' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'excel.gif'), |
13499032 |
938 | 'xlsx' => array ('type'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'icon'=>'xlsx.gif'), |
939 | 'xlsm' => array ('type'=>'application/vnd.ms-excel.sheet.macroEnabled.12', 'icon'=>'xlsm.gif'), |
940 | 'xltx' => array ('type'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.template', 'icon'=>'xltx.gif'), |
941 | 'xltm' => array ('type'=>'application/vnd.ms-excel.template.macroEnabled.12', 'icon'=>'xltm.gif'), |
942 | 'xlsb' => array ('type'=>'application/vnd.ms-excel.sheet.binary.macroEnabled.12', 'icon'=>'xlsb.gif'), |
943 | 'xlam' => array ('type'=>'application/vnd.ms-excel.addin.macroEnabled.12', 'icon'=>'xlam.gif'), |
944 | |
a370c895 |
945 | 'xml' => array ('type'=>'application/xml', 'icon'=>'xml.gif'), |
946 | 'xsl' => array ('type'=>'text/xml', 'icon'=>'xml.gif'), |
947 | 'zip' => array ('type'=>'application/zip', 'icon'=>'zip.gif') |
f1e0649c |
948 | ); |
172dd12c |
949 | return $mimearray; |
3ce73b14 |
950 | } |
951 | |
76ca1ff1 |
952 | /** |
3ce73b14 |
953 | * Obtains information about a filetype based on its extension. Will |
954 | * use a default if no information is present about that particular |
955 | * extension. |
76ca1ff1 |
956 | * @param string $element Desired information (usually 'icon' |
3ce73b14 |
957 | * for icon filename or 'type' for MIME type) |
76ca1ff1 |
958 | * @param string $filename Filename we're looking up |
3ce73b14 |
959 | * @return string Requested piece of information from array |
960 | */ |
961 | function mimeinfo($element, $filename) { |
0ef98843 |
962 | global $CFG; |
172dd12c |
963 | $mimeinfo = get_mimetypes_array(); |
f1e0649c |
964 | |
a370c895 |
965 | if (eregi('\.([a-z0-9]+)$', $filename, $match)) { |
f1e0649c |
966 | if (isset($mimeinfo[strtolower($match[1])][$element])) { |
967 | return $mimeinfo[strtolower($match[1])][$element]; |
968 | } else { |
72aa74ce |
969 | if ($element == 'icon32') { |
970 | if (isset($mimeinfo[strtolower($match[1])]['icon'])) { |
971 | $filename = substr($mimeinfo[strtolower($match[1])]['icon'], 0, -4); |
972 | } else { |
973 | $filename = 'unknown'; |
974 | } |
0ef98843 |
975 | $filename .= '-32.png'; |
976 | if (file_exists($CFG->dirroot.'/pix/f/'.$filename)) { |
977 | return $filename; |
978 | } else { |
7a34d20d |
979 | return 'unknown-32.png'; |
0ef98843 |
980 | } |
981 | } else { |
982 | return $mimeinfo['xxx'][$element]; // By default |
983 | } |
f1e0649c |
984 | } |
985 | } else { |
7a34d20d |
986 | if ($element == 'icon32') { |
987 | return 'unknown-32.png'; |
988 | } |
a370c895 |
989 | return $mimeinfo['xxx'][$element]; // By default |
f1e0649c |
990 | } |
991 | } |
992 | |
76ca1ff1 |
993 | /** |
3ce73b14 |
994 | * Obtains information about a filetype based on the MIME type rather than |
995 | * the other way around. |
996 | * @param string $element Desired information (usually 'icon') |
76ca1ff1 |
997 | * @param string $mimetype MIME type we're looking up |
3ce73b14 |
998 | * @return string Requested piece of information from array |
999 | */ |
1000 | function mimeinfo_from_type($element, $mimetype) { |
172dd12c |
1001 | $mimeinfo = get_mimetypes_array(); |
76ca1ff1 |
1002 | |
3ce73b14 |
1003 | foreach($mimeinfo as $values) { |
1004 | if($values['type']==$mimetype) { |
1005 | if(isset($values[$element])) { |
1006 | return $values[$element]; |
1007 | } |
1008 | break; |
1009 | } |
1010 | } |
1011 | return $mimeinfo['xxx'][$element]; // Default |
1012 | } |
b9709b76 |
1013 | |
42ead7d7 |
1014 | /** |
1015 | * Get information about a filetype based on the icon file. |
1016 | * @param string $element Desired information (usually 'icon') |
1017 | * @param string $icon Icon file path. |
0b46f19e |
1018 | * @param boolean $all return all matching entries (defaults to false - last match) |
42ead7d7 |
1019 | * @return string Requested piece of information from array |
1020 | */ |
0b46f19e |
1021 | function mimeinfo_from_icon($element, $icon, $all=false) { |
172dd12c |
1022 | $mimeinfo = get_mimetypes_array(); |
42ead7d7 |
1023 | |
1024 | if (preg_match("/\/(.*)/", $icon, $matches)) { |
1025 | $icon = $matches[1]; |
1026 | } |
0b46f19e |
1027 | $info = array($mimeinfo['xxx'][$element]); // Default |
42ead7d7 |
1028 | foreach($mimeinfo as $values) { |
1029 | if($values['icon']==$icon) { |
1030 | if(isset($values[$element])) { |
0b46f19e |
1031 | $info[] = $values[$element]; |
42ead7d7 |
1032 | } |
1033 | //No break, for example for 'excel.gif' we don't want 'csv'! |
1034 | } |
1035 | } |
0b46f19e |
1036 | if ($all) { |
1037 | return $info; |
1038 | } |
1039 | return array_pop($info); // Return last match (mimicking behaviour/comment inside foreach loop) |
42ead7d7 |
1040 | } |
1041 | |
c0381e22 |
1042 | /** |
76ca1ff1 |
1043 | * Obtains descriptions for file types (e.g. 'Microsoft Word document') from the |
1044 | * mimetypes.php language file. |
c0381e22 |
1045 | * @param string $mimetype MIME type (can be obtained using the mimeinfo function) |
1046 | * @param bool $capitalise If true, capitalises first character of result |
76ca1ff1 |
1047 | * @return string Text description |
c0381e22 |
1048 | */ |
1049 | function get_mimetype_description($mimetype,$capitalise=false) { |
1050 | $result=get_string($mimetype,'mimetypes'); |
1051 | // Surrounded by square brackets indicates that there isn't a string for that |
1052 | // (maybe there is a better way to find this out?) |
1053 | if(strpos($result,'[')===0) { |
1054 | $result=get_string('document/unknown','mimetypes'); |
76ca1ff1 |
1055 | } |
c0381e22 |
1056 | if($capitalise) { |
1057 | $result=ucfirst($result); |
1058 | } |
1059 | return $result; |
1060 | } |
1061 | |
9e5fa330 |
1062 | /** |
1063 | * Reprot file is not found or not accessible |
1064 | * @return does not return, terminates script |
1065 | */ |
1066 | function send_file_not_found() { |
1067 | global $CFG, $COURSE; |
1068 | header('HTTP/1.0 404 not found'); |
1069 | print_error('filenotfound', 'error', $CFG->wwwroot.'/course/view.php?id='.$COURSE->id); //this is not displayed on IIS?? |
1070 | } |
1071 | |
c87c428e |
1072 | /** |
1073 | * Handles the sending of temporary file to user, download is forced. |
1074 | * File is deleted after abort or succesful sending. |
1075 | * @param string $path path to file, preferably from moodledata/temp/something; or content of file itself |
1076 | * @param string $filename proposed file name when saving file |
1077 | * @param bool $path is content of file |
45c0d224 |
1078 | * @return does not return, script terminated |
c87c428e |
1079 | */ |
45c0d224 |
1080 | function send_temp_file($path, $filename, $pathisstring=false) { |
c87c428e |
1081 | global $CFG; |
1082 | |
1083 | // close session - not needed anymore |
56949c17 |
1084 | @session_get_instance()->write_close(); |
c87c428e |
1085 | |
1086 | if (!$pathisstring) { |
1087 | if (!file_exists($path)) { |
1088 | header('HTTP/1.0 404 not found'); |
45c0d224 |
1089 | print_error('filenotfound', 'error', $CFG->wwwroot.'/'); |
c87c428e |
1090 | } |
1091 | // executed after normal finish or abort |
1092 | @register_shutdown_function('send_temp_file_finished', $path); |
1093 | } |
1094 | |
1095 | //IE compatibiltiy HACK! |
1096 | if (ini_get('zlib.output_compression')) { |
1097 | ini_set('zlib.output_compression', 'Off'); |
1098 | } |
1099 | |
1100 | // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup |
1101 | if (check_browser_version('MSIE')) { |
1102 | $filename = urlencode($filename); |
1103 | } |
1104 | |
1105 | $filesize = $pathisstring ? strlen($path) : filesize($path); |
1106 | |
1107 | @header('Content-Disposition: attachment; filename='.$filename); |
1108 | @header('Content-Length: '.$filesize); |
1109 | if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431 |
1110 | @header('Cache-Control: max-age=10'); |
1111 | @header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT'); |
1112 | @header('Pragma: '); |
1113 | } else { //normal http - prevent caching at all cost |
1114 | @header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0'); |
1115 | @header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT'); |
1116 | @header('Pragma: no-cache'); |
1117 | } |
1118 | @header('Accept-Ranges: none'); // Do not allow byteserving |
1119 | |
1120 | while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite |
1121 | if ($pathisstring) { |
1122 | echo $path; |
1123 | } else { |
29e3d7e2 |
1124 | @readfile($path); |
c87c428e |
1125 | } |
1126 | |
1127 | die; //no more chars to output |
1128 | } |
1129 | |
1130 | /** |
1131 | * Internal callnack function used by send_temp_file() |
1132 | */ |
1133 | function send_temp_file_finished($path) { |
1134 | if (file_exists($path)) { |
1135 | @unlink($path); |
1136 | } |
1137 | } |
1138 | |
76ca1ff1 |
1139 | /** |
1140 | * Handles the sending of file data to the user's browser, including support for |
1141 | * byteranges etc. |
ba75ad94 |
1142 | * @param string $path Path of file on disk (including real filename), or actual content of file as string |
1143 | * @param string $filename Filename to send |
1144 | * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours) |
1145 | * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only |
1146 | * @param bool $pathisstring If true (default false), $path is the content to send and not the pathname |
1147 | * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin |
1148 | * @param string $mimetype Include to specify the MIME type; leave blank to have it guess the type from $filename |
b379f7d9 |
1149 | * @param bool $dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks. |
1150 | * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel, |
29e3d7e2 |
1151 | * you must detect this case when control is returned using connection_aborted. Please not that session is closed |
1152 | * and should not be reopened. |
1153 | * @return no return or void, script execution stopped unless $dontdie is true |
b9709b76 |
1154 | */ |
b379f7d9 |
1155 | function send_file($path, $filename, $lifetime = 'default' , $filter=0, $pathisstring=false, $forcedownload=false, $mimetype='', $dontdie=false) { |
6800d78e |
1156 | global $CFG, $COURSE, $SESSION; |
f1e0649c |
1157 | |
b379f7d9 |
1158 | if ($dontdie) { |
15325f55 |
1159 | ignore_user_abort(true); |
b379f7d9 |
1160 | } |
1161 | |
c8a5c6a4 |
1162 | // MDL-11789, apply $CFG->filelifetime here |
1163 | if ($lifetime === 'default') { |
1164 | if (!empty($CFG->filelifetime)) { |
0cde3ede |
1165 | $lifetime = $CFG->filelifetime; |
c8a5c6a4 |
1166 | } else { |
0cde3ede |
1167 | $lifetime = 86400; |
c8a5c6a4 |
1168 | } |
1169 | } |
1170 | |
56949c17 |
1171 | session_get_instance()->write_close(); // unlock session during fileserving |
172dd12c |
1172 | |
ba4e0b05 |
1173 | // Use given MIME type if specified, otherwise guess it using mimeinfo. |
1174 | // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O |
1175 | // only Firefox saves all files locally before opening when content-disposition: attachment stated |
1176 | $isFF = check_browser_version('Firefox', '1.5'); // only FF > 1.5 properly tested |
76ca1ff1 |
1177 | $mimetype = ($forcedownload and !$isFF) ? 'application/x-forcedownload' : |
ba4e0b05 |
1178 | ($mimetype ? $mimetype : mimeinfo('type', $filename)); |
f1e0649c |
1179 | $lastmodified = $pathisstring ? time() : filemtime($path); |
1180 | $filesize = $pathisstring ? strlen($path) : filesize($path); |
1181 | |
36bddcf5 |
1182 | /* - MDL-13949 |
ee7f231d |
1183 | //Adobe Acrobat Reader XSS prevention |
1184 | if ($mimetype=='application/pdf' or mimeinfo('type', $filename)=='application/pdf') { |
1185 | //please note that it prevents opening of pdfs in browser when http referer disabled |
1186 | //or file linked from another site; browser caching of pdfs is now disabled too |
c57d8874 |
1187 | if (!empty($_SERVER['HTTP_RANGE'])) { |
1188 | //already byteserving |
76ca1ff1 |
1189 | $lifetime = 1; // >0 needed for byteserving |
c57d8874 |
1190 | } else if (empty($_SERVER['HTTP_REFERER']) or strpos($_SERVER['HTTP_REFERER'], $CFG->wwwroot)!==0) { |
ee7f231d |
1191 | $mimetype = 'application/x-forcedownload'; |
1192 | $forcedownload = true; |
1193 | $lifetime = 0; |
1194 | } else { |
76ca1ff1 |
1195 | $lifetime = 1; // >0 needed for byteserving |
ee7f231d |
1196 | } |
b8806ccc |
1197 | } |
36bddcf5 |
1198 | */ |
f3f7610c |
1199 | |
69faecce |
1200 | //IE compatibiltiy HACK! |
4c8c65ec |
1201 | if (ini_get('zlib.output_compression')) { |
69faecce |
1202 | ini_set('zlib.output_compression', 'Off'); |
1203 | } |
1204 | |
4c8c65ec |
1205 | //try to disable automatic sid rewrite in cookieless mode |
8914cb82 |
1206 | @ini_set("session.use_trans_sid", "false"); |
4c8c65ec |
1207 | |
1208 | //do not put '@' before the next header to detect incorrect moodle configurations, |
1209 | //error should be better than "weird" empty lines for admins/users |
1210 | //TODO: should we remove all those @ before the header()? Are all of the values supported on all servers? |
1211 | header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT'); |
1212 | |
4f047de2 |
1213 | // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup |
1214 | if (check_browser_version('MSIE')) { |
4638009b |
1215 | $filename = rawurlencode($filename); |
4f047de2 |
1216 | } |
1217 | |
4c8c65ec |
1218 | if ($forcedownload) { |
4638009b |
1219 | @header('Content-Disposition: attachment; filename="'.$filename.'"'); |
4c8c65ec |
1220 | } else { |
4638009b |
1221 | @header('Content-Disposition: inline; filename="'.$filename.'"'); |
4c8c65ec |
1222 | } |
1223 | |
f1e0649c |
1224 | if ($lifetime > 0) { |
4c8c65ec |
1225 | @header('Cache-Control: max-age='.$lifetime); |
1226 | @header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT'); |
f1e0649c |
1227 | @header('Pragma: '); |
4c8c65ec |
1228 | |
1229 | if (empty($CFG->disablebyteserving) && !$pathisstring && $mimetype != 'text/plain' && $mimetype != 'text/html') { |
1230 | |
1231 | @header('Accept-Ranges: bytes'); |
1232 | |
1233 | if (!empty($_SERVER['HTTP_RANGE']) && strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) { |
1234 | // byteserving stuff - for acrobat reader and download accelerators |
1235 | // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35 |
1236 | // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php |
1237 | $ranges = false; |
1238 | if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) { |
1239 | foreach ($ranges as $key=>$value) { |
1240 | if ($ranges[$key][1] == '') { |
1241 | //suffix case |
1242 | $ranges[$key][1] = $filesize - $ranges[$key][2]; |
1243 | $ranges[$key][2] = $filesize - 1; |
1244 | } else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) { |
1245 | //fix range length |
1246 | $ranges[$key][2] = $filesize - 1; |
1247 | } |
1248 | if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) { |
1249 | //invalid byte-range ==> ignore header |
1250 | $ranges = false; |
1251 | break; |
1252 | } |
1253 | //prepare multipart header |
1254 | $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY."\r\nContent-Type: $mimetype\r\n"; |
1255 | $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n"; |
1256 | } |
1257 | } else { |
1258 | $ranges = false; |
1259 | } |
1260 | if ($ranges) { |
172dd12c |
1261 | $handle = fopen($filename, 'rb'); |
1262 | byteserving_send_file($handle, $mimetype, $ranges, $filesize); |
4c8c65ec |
1263 | } |
1264 | } |
1265 | } else { |
1266 | /// Do not byteserve (disabled, strings, text and html files). |
1267 | @header('Accept-Ranges: none'); |
1268 | } |
1269 | } else { // Do not cache files in proxies and browsers |
85e00626 |
1270 | if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431 |
1271 | @header('Cache-Control: max-age=10'); |
4c8c65ec |
1272 | @header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT'); |
85e00626 |
1273 | @header('Pragma: '); |
1274 | } else { //normal http - prevent caching at all cost |
1275 | @header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0'); |
4c8c65ec |
1276 | @header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT'); |
85e00626 |
1277 | @header('Pragma: no-cache'); |
1278 | } |
4c8c65ec |
1279 | @header('Accept-Ranges: none'); // Do not allow byteserving when caching disabled |
69faecce |
1280 | } |
f1e0649c |
1281 | |
b9709b76 |
1282 | if (empty($filter)) { |
0a2092a3 |
1283 | if ($mimetype == 'text/html' && !empty($CFG->usesid)) { |
4c8c65ec |
1284 | //cookieless mode - rewrite links |
1285 | @header('Content-Type: text/html'); |
1286 | $path = $pathisstring ? $path : implode('', file($path)); |
0ad6b20c |
1287 | $path = sid_ob_rewrite($path); |
4c8c65ec |
1288 | $filesize = strlen($path); |
1289 | $pathisstring = true; |
1290 | } else if ($mimetype == 'text/plain') { |
810944af |
1291 | @header('Content-Type: Text/plain; charset=utf-8'); //add encoding |
f1e0649c |
1292 | } else { |
4c8c65ec |
1293 | @header('Content-Type: '.$mimetype); |
f1e0649c |
1294 | } |
4c8c65ec |
1295 | @header('Content-Length: '.$filesize); |
1296 | while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite |
f1e0649c |
1297 | if ($pathisstring) { |
1298 | echo $path; |
4c8c65ec |
1299 | } else { |
29e3d7e2 |
1300 | @readfile($path); |
f1e0649c |
1301 | } |
1302 | } else { // Try to put the file through filters |
f1e0649c |
1303 | if ($mimetype == 'text/html') { |
a17c57b5 |
1304 | $options = new object(); |
f1e0649c |
1305 | $options->noclean = true; |
a17c57b5 |
1306 | $options->nocache = true; // temporary workaround for MDL-5136 |
f1e0649c |
1307 | $text = $pathisstring ? $path : implode('', file($path)); |
76ca1ff1 |
1308 | |
3ace5ee4 |
1309 | $text = file_modify_html_header($text); |
60f9e36e |
1310 | $output = format_text($text, FORMAT_HTML, $options, $COURSE->id); |
0a2092a3 |
1311 | if (!empty($CFG->usesid)) { |
4c8c65ec |
1312 | //cookieless mode - rewrite links |
0ad6b20c |
1313 | $output = sid_ob_rewrite($output); |
4c8c65ec |
1314 | } |
f1e0649c |
1315 | |
4c8c65ec |
1316 | @header('Content-Length: '.strlen($output)); |
1317 | @header('Content-Type: text/html'); |
1318 | while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite |
f1e0649c |
1319 | echo $output; |
b9709b76 |
1320 | // only filter text if filter all files is selected |
1321 | } else if (($mimetype == 'text/plain') and ($filter == 1)) { |
60f9e36e |
1322 | $options = new object(); |
f1e0649c |
1323 | $options->newlines = false; |
1324 | $options->noclean = true; |
1325 | $text = htmlentities($pathisstring ? $path : implode('', file($path))); |
60f9e36e |
1326 | $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>'; |
0a2092a3 |
1327 | if (!empty($CFG->usesid)) { |
4c8c65ec |
1328 | //cookieless mode - rewrite links |
0ad6b20c |
1329 | $output = sid_ob_rewrite($output); |
4c8c65ec |
1330 | } |
f1e0649c |
1331 | |
4c8c65ec |
1332 | @header('Content-Length: '.strlen($output)); |
810944af |
1333 | @header('Content-Type: text/html; charset=utf-8'); //add encoding |
4c8c65ec |
1334 | while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite |
f1e0649c |
1335 | echo $output; |
1336 | } else { // Just send it out raw |
4c8c65ec |
1337 | @header('Content-Length: '.$filesize); |
1338 | @header('Content-Type: '.$mimetype); |
1339 | while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite |
f1e0649c |
1340 | if ($pathisstring) { |
1341 | echo $path; |
1342 | }else { |
29e3d7e2 |
1343 | @readfile($path); |
f1e0649c |
1344 | } |
1345 | } |
1346 | } |
b379f7d9 |
1347 | if ($dontdie) { |
1348 | return; |
1349 | } |
f1e0649c |
1350 | die; //no more chars to output!!! |
1351 | } |
1352 | |
172dd12c |
1353 | /** |
1354 | * Handles the sending of file data to the user's browser, including support for |
1355 | * byteranges etc. |
1356 | * @param object $stored_file local file object |
1357 | * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours) |
1358 | * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only |
1359 | * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin |
1360 | * @param string $filename Override filename |
1361 | * @param string $mimetype Include to specify the MIME type; leave blank to have it guess the type from $filename |
b379f7d9 |
1362 | * @param bool $dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks. |
1363 | * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel, |
29e3d7e2 |
1364 | * you must detect this case when control is returned using connection_aborted. Please not that session is closed |
1365 | * and should not be reopened. |
1366 | * @return no return or void, script execution stopped unless $dontdie is true |
172dd12c |
1367 | */ |
b379f7d9 |
1368 | function send_stored_file($stored_file, $lifetime=86400 , $filter=0, $forcedownload=false, $filename=null, $dontdie=false) { |
172dd12c |
1369 | global $CFG, $COURSE, $SESSION; |
1370 | |
b379f7d9 |
1371 | if ($dontdie) { |
15325f55 |
1372 | ignore_user_abort(true); |
b379f7d9 |
1373 | } |
1374 | |
56949c17 |
1375 | session_get_instance()->write_close(); // unlock session during fileserving |
172dd12c |
1376 | |
1377 | // Use given MIME type if specified, otherwise guess it using mimeinfo. |
1378 | // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O |
1379 | // only Firefox saves all files locally before opening when content-disposition: attachment stated |
1380 | $filename = is_null($filename) ? $stored_file->get_filename() : $filename; |
1381 | $isFF = check_browser_version('Firefox', '1.5'); // only FF > 1.5 properly tested |
1382 | $mimetype = ($forcedownload and !$isFF) ? 'application/x-forcedownload' : |
1383 | ($stored_file->get_mimetype() ? $stored_file->get_mimetype() : mimeinfo('type', $filename)); |
1384 | $lastmodified = $stored_file->get_timemodified(); |
1385 | $filesize = $stored_file->get_filesize(); |
1386 | |
1387 | //IE compatibiltiy HACK! |
1388 | if (ini_get('zlib.output_compression')) { |
1389 | ini_set('zlib.output_compression', 'Off'); |
1390 | } |
1391 | |
1392 | //try to disable automatic sid rewrite in cookieless mode |
1393 | @ini_set("session.use_trans_sid", "false"); |
1394 | |
1395 | //do not put '@' before the next header to detect incorrect moodle configurations, |
1396 | //error should be better than "weird" empty lines for admins/users |
1397 | //TODO: should we remove all those @ before the header()? Are all of the values supported on all servers? |
1398 | header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT'); |
1399 | |
1400 | // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup |
1401 | if (check_browser_version('MSIE')) { |
1402 | $filename = rawurlencode($filename); |
1403 | } |
1404 | |
1405 | if ($forcedownload) { |
1406 | @header('Content-Disposition: attachment; filename="'.$filename.'"'); |
1407 | } else { |
1408 | @header('Content-Disposition: inline; filename="'.$filename.'"'); |
1409 | } |
1410 | |
1411 | if ($lifetime > 0) { |
1412 | @header('Cache-Control: max-age='.$lifetime); |
1413 | @header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT'); |
1414 | @header('Pragma: '); |
1415 | |
1416 | if (empty($CFG->disablebyteserving) && $mimetype != 'text/plain' && $mimetype != 'text/html') { |
1417 | |
1418 | @header('Accept-Ranges: bytes'); |
1419 | |
1420 | if (!empty($_SERVER['HTTP_RANGE']) && strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) { |
1421 | // byteserving stuff - for acrobat reader and download accelerators |
1422 | // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35 |
1423 | // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php |
1424 | $ranges = false; |
1425 | if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) { |
1426 | foreach ($ranges as $key=>$value) { |
1427 | if ($ranges[$key][1] == '') { |
1428 | //suffix case |
1429 | $ranges[$key][1] = $filesize - $ranges[$key][2]; |
1430 | $ranges[$key][2] = $filesize - 1; |
1431 | } else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) { |
1432 | //fix range length |
1433 | $ranges[$key][2] = $filesize - 1; |
1434 | } |
1435 | if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) { |
1436 | //invalid byte-range ==> ignore header |
1437 | $ranges = false; |
1438 | break; |
1439 | } |
1440 | //prepare multipart header |
1441 | $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY."\r\nContent-Type: $mimetype\r\n"; |
1442 | $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n"; |
1443 | } |
1444 | } else { |
1445 | $ranges = false; |
1446 | } |
1447 | if ($ranges) { |
1448 | byteserving_send_file($stored_file->get_content_file_handle(), $mimetype, $ranges, $filesize); |
1449 | } |
1450 | } |
1451 | } else { |
1452 | /// Do not byteserve (disabled, strings, text and html files). |
1453 | @header('Accept-Ranges: none'); |
1454 | } |
1455 | } else { // Do not cache files in proxies and browsers |
1456 | if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431 |
1457 | @header('Cache-Control: max-age=10'); |
1458 | @header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT'); |
1459 | @header('Pragma: '); |
1460 | } else { //normal http - prevent caching at all cost |
1461 | @header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0'); |
1462 | @header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT'); |
1463 | @header('Pragma: no-cache'); |
1464 | } |
1465 | @header('Accept-Ranges: none'); // Do not allow byteserving when caching disabled |
1466 | } |
1467 | |
1468 | if (empty($filter)) { |
1469 | $filtered = false; |
0a2092a3 |
1470 | if ($mimetype == 'text/html' && !empty($CFG->usesid)) { |
172dd12c |
1471 | //cookieless mode - rewrite links |
1472 | @header('Content-Type: text/html'); |
1473 | $text = $stored_file->get_content(); |
0ad6b20c |
1474 | $text = sid_ob_rewrite($text); |
172dd12c |
1475 | $filesize = strlen($text); |
1476 | $filtered = true; |
1477 | } else if ($mimetype == 'text/plain') { |
1478 | @header('Content-Type: Text/plain; charset=utf-8'); //add encoding |
1479 | } else { |
1480 | @header('Content-Type: '.$mimetype); |
1481 | } |
1482 | @header('Content-Length: '.$filesize); |
1483 | while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite |
1484 | if ($filtered) { |
1485 | echo $text; |
1486 | } else { |
1487 | $stored_file->readfile(); |
1488 | } |
1489 | |
1490 | } else { // Try to put the file through filters |
1491 | if ($mimetype == 'text/html') { |
1492 | $options = new object(); |
1493 | $options->noclean = true; |
1494 | $options->nocache = true; // temporary workaround for MDL-5136 |
1495 | $text = $stored_file->get_content(); |
1496 | $text = file_modify_html_header($text); |
1497 | $output = format_text($text, FORMAT_HTML, $options, $COURSE->id); |
0a2092a3 |
1498 | if (!empty($CFG->usesid)) { |
172dd12c |
1499 | //cookieless mode - rewrite links |
0ad6b20c |
1500 | $output = sid_ob_rewrite($output); |
172dd12c |
1501 | } |
1502 | |
1503 | @header('Content-Length: '.strlen($output)); |
1504 | @header('Content-Type: text/html'); |
1505 | while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite |
1506 | echo $output; |
1507 | // only filter text if filter all files is selected |
1508 | } else if (($mimetype == 'text/plain') and ($filter == 1)) { |
1509 | $options = new object(); |
1510 | $options->newlines = false; |
1511 | $options->noclean = true; |
1512 | $text = $stored_file->get_content(); |
1513 | $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>'; |
0a2092a3 |
1514 | if (!empty($CFG->usesid)) { |
172dd12c |
1515 | //cookieless mode - rewrite links |
0ad6b20c |
1516 | $output = sid_ob_rewrite($output); |
172dd12c |
1517 | } |
1518 | |
1519 | @header('Content-Length: '.strlen($output)); |
1520 | @header('Content-Type: text/html; charset=utf-8'); //add encoding |
1521 | while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite |
1522 | echo $output; |
1523 | } else { // Just send it out raw |
1524 | @header('Content-Length: '.$filesize); |
1525 | @header('Content-Type: '.$mimetype); |
1526 | while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite |
1527 | $stored_file->readfile(); |
1528 | } |
1529 | } |
b379f7d9 |
1530 | if ($dontdie) { |
1531 | return; |
1532 | } |
172dd12c |
1533 | die; //no more chars to output!!! |
1534 | } |
1535 | |
a43b5308 |
1536 | function get_records_csv($file, $table) { |
f33e1ed4 |
1537 | global $CFG, $DB; |
599f38f9 |
1538 | |
f33e1ed4 |
1539 | if (!$metacolumns = $DB->get_columns($table)) { |
599f38f9 |
1540 | return false; |
1541 | } |
1542 | |
a77b98eb |
1543 | if(!($handle = @fopen($file, 'r'))) { |
5a2a5331 |
1544 | print_error('get_records_csv failed to open '.$file); |
599f38f9 |
1545 | } |
1546 | |
1547 | $fieldnames = fgetcsv($handle, 4096); |
1548 | if(empty($fieldnames)) { |
1549 | fclose($handle); |
1550 | return false; |
1551 | } |
1552 | |
1553 | $columns = array(); |
1554 | |
1555 | foreach($metacolumns as $metacolumn) { |
1556 | $ord = array_search($metacolumn->name, $fieldnames); |
1557 | if(is_int($ord)) { |
1558 | $columns[$metacolumn->name] = $ord; |
1559 | } |
1560 | } |
1561 | |
1562 | $rows = array(); |
1563 | |
1564 | while (($data = fgetcsv($handle, 4096)) !== false) { |
1565 | $item = new stdClass; |
1566 | foreach($columns as $name => $ord) { |
1567 | $item->$name = $data[$ord]; |
1568 | } |
1569 | $rows[] = $item; |
1570 | } |
1571 | |
1572 | fclose($handle); |
1573 | return $rows; |
1574 | } |
1575 | |
a77b98eb |
1576 | function put_records_csv($file, $records, $table = NULL) { |
f33e1ed4 |
1577 | global $CFG, $DB; |
a77b98eb |
1578 | |
a1e93da2 |
1579 | if (empty($records)) { |
a77b98eb |
1580 | return true; |
1581 | } |
1582 | |
1583 | $metacolumns = NULL; |
f33e1ed4 |
1584 | if ($table !== NULL && !$metacolumns = $DB->get_columns($table)) { |
a77b98eb |
1585 | return false; |
1586 | } |
1587 | |
a1e93da2 |
1588 | echo "x"; |
1589 | |
a77b98eb |
1590 | if(!($fp = @fopen($CFG->dataroot.'/temp/'.$file, 'w'))) { |
5a2a5331 |
1591 | print_error('put_records_csv failed to open '.$file); |
a77b98eb |
1592 | } |
1593 | |
a43b5308 |
1594 | $proto = reset($records); |
1595 | if(is_object($proto)) { |
1596 | $fields_records = array_keys(get_object_vars($proto)); |
1597 | } |
1598 | else if(is_array($proto)) { |
1599 | $fields_records = array_keys($proto); |
1600 | } |
1601 | else { |
1602 | return false; |
1603 | } |
a1e93da2 |
1604 | echo "x"; |
a77b98eb |
1605 | |
1606 | if(!empty($metacolumns)) { |
1607 | $fields_table = array_map(create_function('$a', 'return $a->name;'), $metacolumns); |
1608 | $fields = array_intersect($fields_records, $fields_table); |
1609 | } |
1610 | else { |
1611 | $fields = $fields_records; |
1612 | } |
1613 | |
1614 | fwrite($fp, implode(',', $fields)); |
1615 | fwrite($fp, "\r\n"); |
1616 | |
1617 | foreach($records as $record) { |
a43b5308 |
1618 | $array = (array)$record; |
a77b98eb |
1619 | $values = array(); |
1620 | foreach($fields as $field) { |
a43b5308 |
1621 | if(strpos($array[$field], ',')) { |
1622 | $values[] = '"'.str_replace('"', '\"', $array[$field]).'"'; |
a77b98eb |
1623 | } |
1624 | else { |
a43b5308 |
1625 | $values[] = $array[$field]; |
a77b98eb |
1626 | } |
1627 | } |
1628 | fwrite($fp, implode(',', $values)."\r\n"); |
1629 | } |
1630 | |
1631 | fclose($fp); |
1632 | return true; |
1633 | } |
1634 | |
f401cc97 |
1635 | |
34763a79 |
1636 | /** |
76ca1ff1 |
1637 | * Recursively delete the file or folder with path $location. That is, |
34763a79 |
1638 | * if it is a file delete it. If it is a folder, delete all its content |
db3a0b34 |
1639 | * then delete it. If $location does not exist to start, that is not |
1640 | * considered an error. |
76ca1ff1 |
1641 | * |
34763a79 |
1642 | * @param $location the path to remove. |
1643 | */ |
4c8c65ec |
1644 | function fulldelete($location) { |
f401cc97 |
1645 | if (is_dir($location)) { |
1646 | $currdir = opendir($location); |
1647 | while (false !== ($file = readdir($currdir))) { |
1648 | if ($file <> ".." && $file <> ".") { |
1649 | $fullfile = $location."/".$file; |
4c8c65ec |
1650 | if (is_dir($fullfile)) { |
f401cc97 |
1651 | if (!fulldelete($fullfile)) { |
1652 | return false; |
1653 | } |
1654 | } else { |
1655 | if (!unlink($fullfile)) { |
1656 | return false; |
1657 | } |
4c8c65ec |
1658 | } |
f401cc97 |
1659 | } |
4c8c65ec |
1660 | } |
f401cc97 |
1661 | closedir($currdir); |
1662 | if (! rmdir($location)) { |
1663 | return false; |
1664 | } |
1665 | |
34763a79 |
1666 | } else if (file_exists($location)) { |
f401cc97 |
1667 | if (!unlink($location)) { |
1668 | return false; |
1669 | } |
1670 | } |
1671 | return true; |
1672 | } |
1673 | |
4c8c65ec |
1674 | /** |
1675 | * Send requested byterange of file. |
1676 | */ |
172dd12c |
1677 | function byteserving_send_file($handle, $mimetype, $ranges, $filesize) { |
4c8c65ec |
1678 | $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB! |
4c8c65ec |
1679 | if ($handle === false) { |
1680 | die; |
1681 | } |
1682 | if (count($ranges) == 1) { //only one range requested |
1683 | $length = $ranges[0][2] - $ranges[0][1] + 1; |
1684 | @header('HTTP/1.1 206 Partial content'); |
1685 | @header('Content-Length: '.$length); |
172dd12c |
1686 | @header('Content-Range: bytes '.$ranges[0][1].'-'.$ranges[0][2].'/'.$filesize); |
4c8c65ec |
1687 | @header('Content-Type: '.$mimetype); |
1688 | while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite |
1689 | $buffer = ''; |
1690 | fseek($handle, $ranges[0][1]); |
1691 | while (!feof($handle) && $length > 0) { |
68913aec |
1692 | @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk |
4c8c65ec |
1693 | $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length)); |
1694 | echo $buffer; |
1695 | flush(); |
1696 | $length -= strlen($buffer); |
1697 | } |
1698 | fclose($handle); |
1699 | die; |
1700 | } else { // multiple ranges requested - not tested much |
1701 | $totallength = 0; |
1702 | foreach($ranges as $range) { |
aba588a7 |
1703 | $totallength += strlen($range[0]) + $range[2] - $range[1] + 1; |
4c8c65ec |
1704 | } |
aba588a7 |
1705 | $totallength += strlen("\r\n--".BYTESERVING_BOUNDARY."--\r\n"); |
4c8c65ec |
1706 | @header('HTTP/1.1 206 Partial content'); |
1707 | @header('Content-Length: '.$totallength); |
1708 | @header('Content-Type: multipart/byteranges; boundary='.BYTESERVING_BOUNDARY); |
1709 | //TODO: check if "multipart/x-byteranges" is more compatible with current readers/browsers/servers |
1710 | while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite |
1711 | foreach($ranges as $range) { |
1712 | $length = $range[2] - $range[1] + 1; |
1713 | echo $range[0]; |
1714 | $buffer = ''; |
1715 | fseek($handle, $range[1]); |
1716 | while (!feof($handle) && $length > 0) { |
68913aec |
1717 | @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk |
4c8c65ec |
1718 | $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length)); |
1719 | echo $buffer; |
1720 | flush(); |
1721 | $length -= strlen($buffer); |
1722 | } |
1723 | } |
1724 | echo "\r\n--".BYTESERVING_BOUNDARY."--\r\n"; |
1725 | fclose($handle); |
1726 | die; |
1727 | } |
1728 | } |
f401cc97 |
1729 | |
3ace5ee4 |
1730 | /** |
1731 | * add includes (js and css) into uploaded files |
1732 | * before returning them, useful for themes and utf.js includes |
1733 | * @param string text - text to search and replace |
1734 | * @return string - text with added head includes |
1735 | */ |
1736 | function file_modify_html_header($text) { |
1737 | // first look for <head> tag |
1738 | global $CFG; |
76ca1ff1 |
1739 | |
3ace5ee4 |
1740 | $stylesheetshtml = ''; |
1741 | foreach ($CFG->stylesheets as $stylesheet) { |
1742 | $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n"; |
76ca1ff1 |
1743 | } |
1744 | |
5b8fa09b |
1745 | $ufo = ''; |
1746 | if (filter_is_enabled('filter/mediaplugin')) { |
76ca1ff1 |
1747 | // this script is needed by most media filter plugins. |
7a1f5e93 |
1748 | $ufo = get_require_js_code(array($CFG->wwwroot . '/lib/ufo.js')); |
3ace5ee4 |
1749 | } |
76ca1ff1 |
1750 | |
3ace5ee4 |
1751 | preg_match('/\<head\>|\<HEAD\>/', $text, $matches); |
1752 | if ($matches) { |
1753 | $replacement = '<head>'.$ufo.$stylesheetshtml; |
1754 | $text = preg_replace('/\<head\>|\<HEAD\>/', $replacement, $text, 1); |
76ca1ff1 |
1755 | return $text; |
3ace5ee4 |
1756 | } |
76ca1ff1 |
1757 | |
3ace5ee4 |
1758 | // if not, look for <html> tag, and stick <head> right after |
1759 | preg_match('/\<html\>|\<HTML\>/', $text, $matches); |
1760 | if ($matches) { |
1761 | // replace <html> tag with <html><head>includes</head> |
13534ef7 |
1762 | $replacement = '<html>'."\n".'<head>'.$ufo.$stylesheetshtml.'</head>'; |
3ace5ee4 |
1763 | $text = preg_replace('/\<html\>|\<HTML\>/', $replacement, $text, 1); |
76ca1ff1 |
1764 | return $text; |
3ace5ee4 |
1765 | } |
76ca1ff1 |
1766 | |
3ace5ee4 |
1767 | // if not, look for <body> tag, and stick <head> before body |
1768 | preg_match('/\<body\>|\<BODY\>/', $text, $matches); |
1769 | if ($matches) { |
13534ef7 |
1770 | $replacement = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".'<body>'; |
3ace5ee4 |
1771 | $text = preg_replace('/\<body\>|\<BODY\>/', $replacement, $text, 1); |
76ca1ff1 |
1772 | return $text; |
1773 | } |
1774 | |
3ace5ee4 |
1775 | // if not, just stick a <head> tag at the beginning |
1776 | $text = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".$text; |
1777 | return $text; |
1778 | } |
1779 | |
bb2c046d |
1780 | /** |
1781 | * RESTful cURL class |
1782 | * |
1783 | * This is a wrapper class for curl, it is quite easy to use: |
1784 | * |
1785 | * $c = new curl; |
1786 | * // enable cache |
1787 | * $c = new curl(array('cache'=>true)); |
1788 | * // enable cookie |
1789 | * $c = new curl(array('cookie'=>true)); |
1790 | * // enable proxy |
1791 | * $c = new curl(array('proxy'=>true)); |
1792 | * |
1793 | * // HTTP GET Method |
1794 | * $html = $c->get('http://example.com'); |
1795 | * // HTTP POST Method |
1796 | * $html = $c->post('http://example.com/', array('q'=>'words', 'name'=>'moodle')); |
1797 | * // HTTP PUT Method |
1798 | * $html = $c->put('http://example.com/', array('file'=>'/var/www/test.txt'); |
1799 | * |
1800 | * @author Dongsheng Cai <dongsheng@cvs.moodle.org> |
1801 | * @version 0.4 dev |
1802 | * @license http://www.gnu.org/copyleft/gpl.html GNU Public License |
1803 | */ |
1804 | |
1805 | class curl { |
1806 | public $cache = false; |
1807 | public $proxy = false; |
1808 | public $version = '0.4 dev'; |
1809 | public $response = array(); |
1810 | public $header = array(); |
1811 | public $info; |
1812 | public $error; |
1813 | |
1814 | private $options; |
1815 | private $proxy_host = ''; |
1816 | private $proxy_auth = ''; |
1817 | private $proxy_type = ''; |
1818 | private $debug = false; |
1819 | private $cookie = false; |
1820 | |
1821 | public function __construct($options = array()){ |
1822 | global $CFG; |
1823 | if (!function_exists('curl_init')) { |
1824 | $this->error = 'cURL module must be enabled!'; |
1825 | trigger_error($this->error, E_USER_ERROR); |
1826 | return false; |
1827 | } |
1828 | // the options of curl should be init here. |
1829 | $this->resetopt(); |
1830 | if (!empty($options['debug'])) { |
1831 | $this->debug = true; |
1832 | } |
1833 | if(!empty($options['cookie'])) { |
1834 | if($options['cookie'] === true) { |
1835 | $this->cookie = $CFG->dataroot.'/curl_cookie.txt'; |
1836 | } else { |
1837 | $this->cookie = $options['cookie']; |
1838 | } |
1839 | } |
1840 | if (!empty($options['cache'])) { |
1841 | if (class_exists('curl_cache')) { |
5430f05b |
1842 | if (!empty($options['module_cache'])) { |
1843 | $this->cache = new curl_cache($options['module_cache']); |
1844 | } else { |
1845 | $this->cache = new curl_cache('misc'); |
1846 | } |
bb2c046d |
1847 | } |
1848 | } |
d04ce87f |
1849 | if (!empty($CFG->proxyhost)) { |
1850 | if (empty($CFG->proxyport)) { |
1851 | $this->proxy_host = $CFG->proxyhost; |
1852 | } else { |
1853 | $this->proxy_host = $CFG->proxyhost.':'.$CFG->proxyport; |
1854 | } |
1855 | if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) { |
1856 | $this->proxy_auth = $CFG->proxyuser.':'.$CFG->proxypassword; |
1857 | $this->setopt(array( |
1858 | 'proxyauth'=> CURLAUTH_BASIC | CURLAUTH_NTLM, |
1859 | 'proxyuserpwd'=>$this->proxy_auth)); |
1860 | } |
1861 | if (!empty($CFG->proxytype)) { |
1862 | if ($CFG->proxytype == 'SOCKS5') { |
1863 | $this->proxy_type = CURLPROXY_SOCKS5; |
bb2c046d |
1864 | } else { |
d04ce87f |
1865 | $this->proxy_type = CURLPROXY_HTTP; |
f6d3e2c4 |
1866 | $this->setopt(array('httpproxytunnel'=>false)); |
bb2c046d |
1867 | } |
d04ce87f |
1868 | $this->setopt(array('proxytype'=>$this->proxy_type)); |
bb2c046d |
1869 | } |
d04ce87f |
1870 | } |
1871 | if (!empty($this->proxy_host)) { |
1872 | $this->proxy = array('proxy'=>$this->proxy_host); |
bb2c046d |
1873 | } |
1874 | } |
1875 | public function resetopt(){ |
1876 | $this->options = array(); |
1877 | $this->options['CURLOPT_USERAGENT'] = 'MoodleBot/1.0'; |
1878 | // True to include the header in the output |
1879 | $this->options['CURLOPT_HEADER'] = 0; |
1880 | // True to Exclude the body from the output |
1881 | $this->options['CURLOPT_NOBODY'] = 0; |
1882 | // TRUE to follow any "Location: " header that the server |
1883 | // sends as part of the HTTP header (note this is recursive, |
1884 | // PHP will follow as many "Location: " headers that it is sent, |
1885 | // unless CURLOPT_MAXREDIRS is set). |
1886 | $this->options['CURLOPT_FOLLOWLOCATION'] = 1; |
1887 | $this->options['CURLOPT_MAXREDIRS'] = 10; |
1888 | $this->options['CURLOPT_ENCODING'] = ''; |
1889 | // TRUE to return the transfer as a string of the return |
1890 | // value of curl_exec() instead of outputting it out directly. |
1891 | $this->options['CURLOPT_RETURNTRANSFER'] = 1; |
1892 | $this->options['CURLOPT_BINARYTRANSFER'] = 0; |
1893 | $this->options['CURLOPT_SSL_VERIFYPEER'] = 0; |
1894 | $this->options['CURLOPT_SSL_VERIFYHOST'] = 2; |
6135bd45 |
1895 | $this->options['CURLOPT_CONNECTTIMEOUT'] = 30; |
bb2c046d |
1896 | } |
1897 | |
1898 | /** |
1899 | * Reset Cookie |
1900 | * |
1901 | * @param array $options If array is null, this function will |
1902 | * reset the options to default value. |
1903 | * |
1904 | */ |
1905 | public function resetcookie() { |
1906 | if (!empty($this->cookie)) { |
1907 | if (is_file($this->cookie)) { |
1908 | $fp = fopen($this->cookie, 'w'); |
1909 | if (!empty($fp)) { |
1910 | fwrite($fp, ''); |
1911 | fclose($fp); |
1912 | } |
1913 | } |
1914 | } |
1915 | } |
1916 | |
1917 | /** |
1918 | * Set curl options |
1919 | * |
1920 | * @param array $options If array is null, this function will |
1921 | * reset the options to default value. |
1922 | * |
1923 | */ |
1924 | public function setopt($options = array()) { |
1925 | if (is_array($options)) { |
1926 | foreach($options as $name => $val){ |
1927 | if (stripos($name, 'CURLOPT_') === false) { |
1928 | $name = strtoupper('CURLOPT_'.$name); |
1929 | } |
1930 | $this->options[$name] = $val; |
1931 | } |
1932 | } |
1933 | } |
1934 | /** |
1935 | * Reset http method |
1936 | * |
1937 | */ |
1938 | public function cleanopt(){ |
1939 | unset($this->options['CURLOPT_HTTPGET']); |
1940 | unset($this->options['CURLOPT_POST']); |
1941 | unset($this->options['CURLOPT_POSTFIELDS']); |
1942 | unset($this->options['CURLOPT_PUT']); |
1943 | unset($this->options['CURLOPT_INFILE']); |
1944 | unset($this->options['CURLOPT_INFILESIZE']); |
1945 | unset($this->options['CURLOPT_CUSTOMREQUEST']); |
1946 | } |
1947 | |
1948 | /** |
1949 | * Set HTTP Request Header |
1950 | * |
1951 | * @param array $headers |
1952 | * |
1953 | */ |
1954 | public function setHeader($header) { |
1955 | if (is_array($header)){ |
1956 | foreach ($header as $v) { |
1957 | $this->setHeader($v); |
1958 | } |
1959 | } else { |
1960 | $this->header[] = $header; |
1961 | } |
1962 | } |
1963 | /** |
1964 | * Set HTTP Response Header |
1965 | * |
1966 | */ |
1967 | public function getResponse(){ |
1968 | return $this->response; |
1969 | } |
1970 | /** |
1971 | * private callback function |
1972 | * Formatting HTTP Response Header |
1973 | * |
1974 | */ |
1975 | private function formatHeader($ch, $header) |
1976 | { |
1977 | $this->count++; |
1978 | if (strlen($header) > 2) { |
1979 | list($key, $value) = explode(" ", rtrim($header, "\r\n"), 2); |
1980 | $key = rtrim($key, ':'); |
1981 | if (!empty($this->response[$key])) { |
1982 | if (is_array($this->response[$key])){ |
1983 | $this->response[$key][] = $value; |
1984 | } else { |
1985 | $tmp = $this->response[$key]; |
1986 | $this->response[$key] = array(); |
1987 | $this->response[$key][] = $tmp; |
1988 | $this->response[$key][] = $value; |
1989 | |
1990 | } |
1991 | } else { |
1992 | $this->response[$key] = $value; |
1993 | } |
1994 | } |
1995 | return strlen($header); |
1996 | } |
1997 | |
1998 | /** |
1999 | * Set options for individual curl instance |
2000 | */ |
2001 | private function apply_opt($curl, $options) { |
2002 | // Clean up |
2003 | $this->cleanopt(); |
2004 | // set cookie |
2005 | if (!empty($this->cookie) || !empty($options['cookie'])) { |
2006 | $this->setopt(array('cookiejar'=>$this->cookie, |
2007 | 'cookiefile'=>$this->cookie |
2008 | )); |
2009 | } |
2010 | |
2011 | // set proxy |
2012 | if (!empty($this->proxy) || !empty($options['proxy'])) { |
2013 | $this->setopt($this->proxy); |
2014 | } |
2015 | $this->setopt($options); |
2016 | // reset before set options |
2017 | curl_setopt($curl, CURLOPT_HEADERFUNCTION, array(&$this,'formatHeader')); |
2018 | // set headers |
2019 | if (empty($this->header)){ |
2020 | $this->setHeader(array( |
2021 | 'User-Agent: MoodleBot/1.0', |
2022 | 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7', |
2023 | 'Connection: keep-alive' |
2024 | )); |
2025 | } |
2026 | curl_setopt($curl, CURLOPT_HTTPHEADER, $this->header); |
2027 | |
2028 | if ($this->debug){ |
2029 | echo '<h1>Options</h1>'; |
2030 | var_dump($this->options); |
2031 | echo '<h1>Header</h1>'; |
2032 | var_dump($this->header); |
2033 | } |
2034 | |
2035 | // set options |
2036 | foreach($this->options as $name => $val) { |
2037 | if (is_string($name)) { |
2038 | $name = constant(strtoupper($name)); |
2039 | } |
2040 | curl_setopt($curl, $name, $val); |
2041 | } |
2042 | return $curl; |
2043 | } |
2044 | /* |
2045 | * Download multiple files in parallel |
2046 | * $c = new curl; |
2047 | * $c->download(array( |
172dd12c |
2048 | * array('url'=>'http://localhost/', 'file'=>fopen('a', 'wb')), |
bb2c046d |
2049 | * array('url'=>'http://localhost/20/', 'file'=>fopen('b', 'wb')) |
2050 | * )); |
2051 | */ |
2052 | public function download($requests, $options = array()) { |
2053 | $options['CURLOPT_BINARYTRANSFER'] = 1; |
2054 | $options['RETURNTRANSFER'] = false; |
2055 | return $this->multi($requests, $options); |
2056 | } |
2057 | /* |
2058 | * Mulit HTTP Requests |
2059 | * This function could run multi-requests in parallel. |
2060 | */ |
2061 | protected function multi($requests, $options = array()) { |
2062 | $count = count($requests); |
2063 | $handles = array(); |
2064 | $results = array(); |
2065 | $main = curl_multi_init(); |
2066 | for ($i = 0; $i < $count; $i++) { |
2067 | $url = $requests[$i]; |
2068 | foreach($url as $n=>$v){ |
2069 | $options[$n] = $url[$n]; |
2070 | } |
2071 | $handles[$i] = curl_init($url['url']); |
2072 | $this->apply_opt($handles[$i], $options); |
2073 | curl_multi_add_handle($main, $handles[$i]); |
2074 | } |
2075 | $running = 0; |
2076 | do { |
2077 | curl_multi_exec($main, $running); |
2078 | } while($running > 0); |
2079 | for ($i = 0; $i < $count; $i++) { |
2080 | if (!empty($optins['CURLOPT_RETURNTRANSFER'])) { |
2081 | $results[] = true; |
2082 | } else { |
2083 | $results[] = curl_multi_getcontent($handles[$i]); |
2084 | } |
2085 | curl_multi_remove_handle($main, $handles[$i]); |
2086 | } |
2087 | curl_multi_close($main); |
2088 | return $results; |
2089 | } |
2090 | /** |
2091 | * Single HTTP Request |
2092 | */ |
2093 | protected function request($url, $options = array()){ |
2094 | // create curl instance |
2095 | $curl = curl_init($url); |
2096 | $options['url'] = $url; |
2097 | $this->apply_opt($curl, $options); |
2098 | if ($this->cache && $ret = $this->cache->get($this->options)) { |
2099 | return $ret; |
2100 | } else { |
6135bd45 |
2101 | $ret = curl_exec($curl); |
bb2c046d |
2102 | if ($this->cache) { |
2103 | $this->cache->set($this->options, $ret); |
2104 | } |
2105 | } |
2106 | |
2107 | $this->info = curl_getinfo($curl); |
2108 | $this->error = curl_error($curl); |
2109 | |
2110 | if ($this->debug){ |
2111 | echo '<h1>Return Data</h1>'; |
2112 | var_dump($ret); |
2113 | echo '<h1>Info</h1>'; |
2114 | var_dump($this->info); |
2115 | echo '<h1>Error</h1>'; |
2116 | var_dump($this->error); |
2117 | } |
2118 | |
2119 | curl_close($curl); |
2120 | |
6135bd45 |
2121 | if (empty($this->error)){ |
bb2c046d |
2122 | return $ret; |
2123 | } else { |
6135bd45 |
2124 | throw new moodle_exception($this->error, 'curl'); |
bb2c046d |
2125 | } |
2126 | } |
2127 | |
2128 | /** |
2129 | * HTTP HEAD method |
2130 | */ |
2131 | public function head($url, $options = array()){ |
2132 | $options['CURLOPT_HTTPGET'] = 0; |
2133 | $options['CURLOPT_HEADER'] = 1; |
2134 | $options['CURLOPT_NOBODY'] = 1; |
2135 | return $this->request($url, $options); |
2136 | } |
2137 | |
2138 | /** |
2139 | * HTTP POST method |
2140 | */ |
28c58294 |
2141 | public function post($url, $params = '', $options = array()){ |
bb2c046d |
2142 | $options['CURLOPT_POST'] = 1; |
28c58294 |
2143 | if (is_array($params)) { |
2144 | $this->_tmp_file_post_params = array(); |
2145 | foreach ($params as $key => $value) { |
2146 | if ($value instanceof stored_file) { |
2147 | $value->add_to_curl_request($this, $key); |
2148 | } else { |
2149 | $this->_tmp_file_post_params[$key] = $value; |
2150 | } |
5035a8b4 |
2151 | } |
28c58294 |
2152 | $options['CURLOPT_POSTFIELDS'] = $this->_tmp_file_post_params; |
2153 | unset($this->_tmp_file_post_params); |
2154 | } else { |
2155 | // $params is the raw post data |
2156 | $options['CURLOPT_POSTFIELDS'] = $params; |
5035a8b4 |
2157 | } |
bb2c046d |
2158 | return $this->request($url, $options); |
2159 | } |
2160 | |
2161 | /** |
2162 | * HTTP GET method |
2163 | */ |
2164 | public function get($url, $params = array(), $options = array()){ |
2165 | $options['CURLOPT_HTTPGET'] = 1; |
2166 | |
2167 | if (!empty($params)){ |
2168 | $url .= (stripos($url, '?') !== false) ? '&' : '?'; |
2169 | $url .= http_build_query($params, '', '&'); |
2170 | } |
2171 | return $this->request($url, $options); |
2172 | } |
2173 | |
2174 | /** |
2175 | * HTTP PUT method |
2176 | */ |
2177 | public function put($url, $params = array(), $options = array()){ |
2178 | $file = $params['file']; |
2179 | if (!is_file($file)){ |
2180 | return null; |
2181 | } |
2182 | $fp = fopen($file, 'r'); |
2183 | $size = filesize($file); |
2184 | $options['CURLOPT_PUT'] = 1; |
2185 | $options['CURLOPT_INFILESIZE'] = $size; |
2186 | $options['CURLOPT_INFILE'] = $fp; |
2187 | if (!isset($this->options['CURLOPT_USERPWD'])){ |
2188 | $this->setopt(array('CURLOPT_USERPWD'=>'anonymous: noreply@moodle.org')); |
2189 | } |
2190 | $ret = $this->request($url, $options); |
2191 | fclose($fp); |
2192 | return $ret; |
2193 | } |
2194 | |
2195 | /** |
2196 | * HTTP DELETE method |
2197 | */ |
2198 | public function delete($url, $param = array(), $options = array()){ |
2199 | $options['CURLOPT_CUSTOMREQUEST'] = 'DELETE'; |
2200 | if (!isset($options['CURLOPT_USERPWD'])) { |
2201 | $options['CURLOPT_USERPWD'] = 'anonymous: noreply@moodle.org'; |
2202 | } |
2203 | $ret = $this->request($url, $options); |
2204 | return $ret; |
2205 | } |
2206 | /** |
2207 | * HTTP TRACE method |
2208 | */ |
2209 | public function trace($url, $options = array()){ |
2210 | $options['CURLOPT_CUSTOMREQUEST'] = 'TRACE'; |
2211 | $ret = $this->request($url, $options); |
2212 | return $ret; |
2213 | } |
2214 | /** |
2215 | * HTTP OPTIONS method |
2216 | */ |
2217 | public function options($url, $options = array()){ |
2218 | $options['CURLOPT_CUSTOMREQUEST'] = 'OPTIONS'; |
2219 | $ret = $this->request($url, $options); |
2220 | return $ret; |
2221 | } |
2222 | } |
2223 | |
2224 | /** |
2225 | * This class is used by cURL class, use case: |
2226 | * |
5430f05b |
2227 | * $CFG->repositorycacheexpire = 120; |
2228 | * $CFG->curlcache = 120; |
2229 | * |
2230 | * $c = new curl(array('cache'=>true), 'module_cache'=>'repository'); |
bb2c046d |
2231 | * $ret = $c->get('http://www.google.com'); |
2232 | * |
2233 | */ |
2234 | class curl_cache { |
2235 | public $dir = ''; |
5430f05b |
2236 | /** |
2237 | * |
2238 | * @global $CFG |
2239 | * @param string @module, which module is using curl_cache |
2240 | * |
2241 | */ |
37051e58 |
2242 | function __construct($module = 'repository'){ |
bb2c046d |
2243 | global $CFG; |
5430f05b |
2244 | if (!empty($module)) { |
2245 | $this->dir = $CFG->dataroot.'/cache/'.$module.'/'; |
2246 | } else { |
2247 | $this->dir = $CFG->dataroot.'/cache/misc/'; |
bb2c046d |
2248 | } |
5430f05b |
2249 | if (!file_exists($this->dir)) { |
2250 | mkdir($this->dir, 0700, true); |
bb2c046d |
2251 | } |
5430f05b |
2252 | if ($module == 'repository') { |
2253 | if (empty($CFG->repositorycacheexpire)) { |
2254 | $CFG->repositorycacheexpire = 120; |
2255 | } |
2256 | $this->ttl = $CFG->repositorycacheexpire; |
2257 | } else { |
2258 | if (empty($CFG->curlcache)) { |
2259 | $CFG->curlcache = 120; |
2260 | } |
2261 | $this->ttl = $CFG->curlcache; |
b933a139 |
2262 | } |
bb2c046d |
2263 | } |
a08171c5 |
2264 | |
509f67e3 |
2265 | /** |
2266 | * TODO Document |
2267 | */ |
bb2c046d |
2268 | public function get($param){ |
aae85978 |
2269 | global $CFG, $USER; |
5430f05b |
2270 | $this->cleanup($this->ttl); |
aae85978 |
2271 | $filename = 'u'.$USER->id.'_'.md5(serialize($param)); |
bb2c046d |
2272 | if(file_exists($this->dir.$filename)) { |
2273 | $lasttime = filemtime($this->dir.$filename); |
5430f05b |
2274 | if(time()-$lasttime > $this->ttl) |
d7e122d6 |
2275 | { |
bb2c046d |
2276 | return false; |
2277 | } else { |
2278 | $fp = fopen($this->dir.$filename, 'r'); |
2279 | $size = filesize($this->dir.$filename); |
2280 | $content = fread($fp, $size); |
2281 | return unserialize($content); |
2282 | } |
2283 | } |
2284 | return false; |
2285 | } |
a08171c5 |
2286 | |
509f67e3 |
2287 | /** |
2288 | * TODO Document |
2289 | */ |
bb2c046d |
2290 | public function set($param, $val){ |
aae85978 |
2291 | global $CFG, $USER; |
2292 | $filename = 'u'.$USER->id.'_'.md5(serialize($param)); |
bb2c046d |
2293 | $fp = fopen($this->dir.$filename, 'w'); |
2294 | fwrite($fp, serialize($val)); |
2295 | fclose($fp); |
2296 | } |
a08171c5 |
2297 | |
509f67e3 |
2298 | /** |
2299 | * TODO Document |
2300 | */ |
bb2c046d |
2301 | public function cleanup($expire){ |
2302 | if($dir = opendir($this->dir)){ |
2303 | while (false !== ($file = readdir($dir))) { |
2304 | if(!is_dir($file) && $file != '.' && $file != '..') { |
2305 | $lasttime = @filemtime($this->dir.$file); |
2306 | if(time() - $lasttime > $expire){ |
2307 | @unlink($this->dir.$file); |
2308 | } |
2309 | } |
2310 | } |
2311 | } |
2312 | } |
aae85978 |
2313 | /** |
2314 | * delete current user's cache file |
2315 | * |
2316 | * @return null |
2317 | */ |
2318 | public function refresh(){ |
2319 | global $CFG, $USER; |
2320 | if($dir = opendir($this->dir)){ |
2321 | while (false !== ($file = readdir($dir))) { |
2322 | if(!is_dir($file) && $file != '.' && $file != '..') { |
2323 | if(strpos($file, 'u'.$USER->id.'_')!==false){ |
2324 | @unlink($this->dir.$file); |
2325 | } |
2326 | } |
2327 | } |
2328 | } |
2329 | } |
bb2c046d |
2330 | } |
509f67e3 |
2331 | |
2332 | /** |
2333 | * TODO Document |
2334 | */ |
014c1ca0 |
2335 | class file_type_to_ext { |
2336 | public function __construct($file = '') { |
2337 | global $CFG; |
2338 | if (empty($file)) { |
2339 | $this->file = $CFG->libdir.'/file/file_types.mm'; |
2340 | } else { |
2341 | $this->file = $file; |
2342 | } |
2343 | $this->tree = array(); |
2344 | $this->result = array(); |
2345 | } |
a08171c5 |
2346 | |
509f67e3 |
2347 | /** |
2348 | * TODO Document |
2349 | */ |
014c1ca0 |
2350 | private function _browse_nodes($parent, $types) { |
2351 | $key = (string)$parent['TEXT']; |
2352 | if(isset($parent->node)) { |
2353 | $this->tree[$key] = array(); |
2354 | if (in_array((string)$parent['TEXT'], $types)) { |
2355 | $this->_select_nodes($parent, $this->result); |
2356 | } else { |
2357 | foreach($parent->node as $v){ |
2358 | $this->_browse_nodes($v, $types); |
2359 | } |
2360 | } |
2361 | } else { |
2362 | $this->tree[] = $key; |
2363 | } |
2364 | } |
a08171c5 |
2365 | |
509f67e3 |
2366 | /** |
2367 | * TODO Document |
2368 | */ |
014c1ca0 |
2369 | private function _select_nodes($parent){ |
2370 | if(isset($parent->node)) { |
2371 | foreach($parent->node as $v){ |
2372 | $this->_select_nodes($v, $this->result); |
2373 | } |
2374 | } else { |
2375 | $this->result[] = (string)$parent['TEXT']; |
2376 | } |
2377 | } |
2378 | |
a08171c5 |
2379 | |
509f67e3 |
2380 | /** |
2381 | * TODO Document |
2382 | */ |
014c1ca0 |
2383 | public function get_file_ext($types) { |
2384 | $this->result = array(); |
fc11edbf |
2385 | if ((is_array($types) && in_array('*', $types)) || |
b933b378 |
2386 | $types == '*' || empty($types)) { |
2387 | return array('*'); |
014c1ca0 |
2388 | } |
2389 | foreach ($types as $key=>$value){ |
2390 | if (strpos($value, '.') !== false) { |
2391 | $this->result[] = $value; |
2392 | unset($types[$key]); |
2393 | } |
2394 | } |
2395 | if (file_exists($this->file)) { |
2396 | $xml = simplexml_load_file($this->file); |
2397 | foreach($xml->node->node as $v){ |
2398 | if (in_array((string)$v['TEXT'], $types)) { |
2399 | $this->_select_nodes($v); |
2400 | } else { |
2401 | $this->_browse_nodes($v, $types); |
2402 | } |
2403 | } |
2404 | } else { |
2405 | exit('Failed to open test.xml.'); |
2406 | } |
2407 | return $this->result; |
2408 | } |
2409 | } |