25c8e721b8fe3fb1b5c63de9de2bf5ae15b3e2dc
[moodle.git] / lib / resourcelib.php
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 // GNU General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
18 /**
19  * Recourse module like helper functions
20  *
21  * @package    core
22  * @subpackage lib
23  * @copyright  2009 Petr Skoda (http://skodak.org)
24  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25  */
27 defined('MOODLE_INTERNAL') || die();
29 /** Try the best way */
30 define('RESOURCELIB_DISPLAY_AUTO', 0);
31 /** Display using object tag */
32 define('RESOURCELIB_DISPLAY_EMBED', 1);
33 /** Display inside frame */
34 define('RESOURCELIB_DISPLAY_FRAME', 2);
35 /** Display normal link in new window */
36 define('RESOURCELIB_DISPLAY_NEW', 3);
37 /** Force download of file instead of display */
38 define('RESOURCELIB_DISPLAY_DOWNLOAD', 4);
39 /** Open directly */
40 define('RESOURCELIB_DISPLAY_OPEN', 5);
41 /** Open in "emulated" pop-up without navigation */
42 define('RESOURCELIB_DISPLAY_POPUP', 6);
44 /** Legacy files not needed or new resource */
45 define('RESOURCELIB_LEGACYFILES_NO', 0);
46 /** Legacy files conversion marked as completed */
47 define('RESOURCELIB_LEGACYFILES_DONE', 1);
48 /** Legacy files conversion in progress*/
49 define('RESOURCELIB_LEGACYFILES_ACTIVE', 2);
52 /**
53  * Try on demand migration of file from old course files
54  * @param string $filepath old file path
55  * @param int $cmid migrated course module if
56  * @param int $courseid
57  * @param string $component
58  * @param string $filearea new file area
59  * @param int $itemid migrated file item id
60  * @return mixed, false if not found, stored_file instance if migrated to new area
61  */
62 function resourcelib_try_file_migration($filepath, $cmid, $courseid, $component, $filearea, $itemid) {
63     $fs = get_file_storage();
65     if (stripos($filepath, '/backupdata/') === 0 or stripos($filepath, '/moddata/') === 0) {
66         // do not steal protected files!
67         return false;
68     }
70     if (!$context = get_context_instance(CONTEXT_MODULE, $cmid)) {
71         return false;
72     }
73     if (!$coursecontext = get_context_instance(CONTEXT_COURSE, $courseid)) {
74         return false;
75     }
77     $fullpath = rtrim("/$coursecontext->id/course/legacy/0".$filepath, '/');
78     do {
79         if (!$file = $fs->get_file_by_hash(sha1($fullpath))) {
80             if ($file = $fs->get_file_by_hash(sha1("$fullpath/.")) and $file->is_directory()) {
81                 if ($file = $fs->get_file_by_hash(sha1("$fullpath/index.htm"))) {
82                     break;
83                 }
84                 if ($file = $fs->get_file_by_hash(sha1("$fullpath/index.html"))) {
85                     break;
86                 }
87                 if ($file = $fs->get_file_by_hash(sha1("$fullpath/Default.htm"))) {
88                     break;
89                 }
90             }
91             return false;
92         }
93     } while (false);
95     // copy and keep the same path, name, etc.
96     $file_record = array('contextid'=>$context->id, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid);
97     try {
98         return $fs->create_file_from_storedfile($file_record, $file);
99     } catch (Exception $e) {
100         // file may exist - highly unlikely, we do not want upgrades to stop here
101         return false;
102     }
105 /**
106  * Returns list of available display options
107  * @param array $enabled list of options enabled in module configuration
108  * @param int $current current display options for existing instances
109  * @return array of key=>name pairs
110  */
111 function resourcelib_get_displayoptions(array $enabled, $current=null) {
112     if (is_number($current)) {
113         $enabled[] = $current;
114     }
116     $options = array(RESOURCELIB_DISPLAY_AUTO     => get_string('resourcedisplayauto'),
117                      RESOURCELIB_DISPLAY_EMBED    => get_string('resourcedisplayembed'),
118                      RESOURCELIB_DISPLAY_FRAME    => get_string('resourcedisplayframe'),
119                      RESOURCELIB_DISPLAY_NEW      => get_string('resourcedisplaynew'),
120                      RESOURCELIB_DISPLAY_DOWNLOAD => get_string('resourcedisplaydownload'),
121                      RESOURCELIB_DISPLAY_OPEN     => get_string('resourcedisplayopen'),
122                      RESOURCELIB_DISPLAY_POPUP    => get_string('resourcedisplaypopup'));
124     $result = array();
126     foreach ($options as $key=>$value) {
127         if (in_array($key, $enabled)) {
128             $result[$key] = $value;
129         }
130     }
132     if (empty($result)) {
133         // there should be always something in case admin misconfigures module
134         $result[RESOURCELIB_DISPLAY_OPEN] = $options[RESOURCELIB_DISPLAY_OPEN];
135     }
137     return $result;
140 /**
141  * Tries to guess correct mimetype for arbitrary URL
142  * @param string $fullurl
143  * @return string mimetype
144  */
145 function resourcelib_guess_url_mimetype($fullurl) {
146     global $CFG;
147     require_once("$CFG->libdir/filelib.php");
149     if ($fullurl instanceof moodle_url) {
150         $fullurl = $fullurl->out(false);
151     }
153     $matches = null;
154     if (preg_match("|^(.*)/[a-z]*file.php(\?file=)?(/[^&\?#]*)|", $fullurl, $matches)) {
155         // remove the special moodle file serving hacks so that the *file.php is ignored
156         $fullurl = $matches[1].$matches[3];
157     }
159     if (preg_match("|^(.*)#.*|", $fullurl, $matches)) {
160         // ignore all anchors
161         $fullurl = $matches[1];
162     }
164     if (strpos($fullurl, '.php')){
165         // we do not really know what is in general php script
166         return 'text/html';
168     } else if (substr($fullurl, -1) === '/') {
169         // directory index (http://example.com/smaples/)
170         return 'text/html';
172     } else if (strpos($fullurl, '//') !== false and substr_count($fullurl, '/') == 2) {
173         // just a host name (http://example.com), solves Australian servers "audio" problem too
174         return 'text/html';
176     } else {
177         // ok, this finally looks like a real file
178         $parts = explode('?', $fullurl);
179         $url = reset($parts);
180         return mimeinfo('type', $url);
181     }
184 /**
185  * Looks for the extension.
186  *
187  * @param string $fullurl
188  * @return string file extension
189  */
190 function resourcelib_get_extension($fullurl) {
192     if ($fullurl instanceof moodle_url) {
193         $fullurl = $fullurl->out(false);
194     }
196     $matches = null;
197     if (preg_match("|^(.*)/[a-z]*file.php(\?file=)?(/.*)|", $fullurl, $matches)) {
198         // remove the special moodle file serving hacks so that the *file.php is ignored
199         $fullurl = $matches[1].$matches[3];
200     }
202     $matches = null;
203     if (preg_match('/^[^#\?]+\.([a-z0-9]+)([#\?].*)?$/i', $fullurl, $matches)) {
204         return strtolower($matches[1]);
205     }
207     return '';
210 /**
211  * Returns image embedding html.
212  * @param string $fullurl
213  * @param string $title
214  * @return string html
215  */
216 function resourcelib_embed_image($fullurl, $title) {
217     $code = '';
218     $code .= '<div class="resourcecontent resourceimg">';
219     $code .= "<img title=\"".strip_tags(format_string($title))."\" class=\"resourceimage\" src=\"$fullurl\" alt=\"\" />";
220     $code .= '</div>';
222     return $code;
225 /**
226  * Returns mp3 embedding html.
227  * @param string $fullurl
228  * @param string $title
229  * @param string $clicktoopen
230  * @return string html
231  */
232 function resourcelib_embed_mp3($fullurl, $title, $clicktoopen) {
234     if ($fullurl instanceof moodle_url) {
235         $fullurl = $fullurl->out(false);
236     }
238     $id = 'resource_mp3_'.time(); //we need something unique because it might be stored in text cache
240     // note: size is specified in theme, it can be made as wide as necessary, but the height can not be changed
242     $output = '<div class="resourcecontent resourcemp3">';
243     $output .= html_writer::tag('span', $clicktoopen, array('id'=>$id, 'class'=>'resourcemediaplugin resourcemediaplugin_mp3', 'title'=>$title));
244     $output .= html_writer::script(js_writer::function_call('M.util.add_audio_player', array($id, $fullurl, false)));
245     $output .= '</div>';
247     return $output;
250 /**
251  * Returns flash video embedding html.
252  * @param string $fullurl
253  * @param string $title
254  * @param string $clicktoopen
255  * @return string html
256  */
257 function resourcelib_embed_flashvideo($fullurl, $title, $clicktoopen) {
258     global $CFG, $PAGE;
260     if ($fullurl instanceof moodle_url) {
261         $fullurl = $fullurl->out(false);
262     }
264     $id = 'resource_flv_'.time(); //we need something unique because it might be stored in text cache
266     //note: nobody should be adding any dimensions to themes!!!
268     if (preg_match('/\?d=([\d]{1,4}%?)x([\d]{1,4}%?)/', $fullurl, $matches)) {
269         $width    = $matches[1];
270         $height   = $matches[2];
271         $autosize = false;
272     } else {
273         $width    = 400;
274         $height   = 300;
275         $autosize = true;
276     }
277     $output = '<div class="resourcecontent resourceflv">';
278     $output .= html_writer::tag('span', $clicktoopen, array('id'=>$id, 'class'=>'resourcemediaplugin resourcemediaplugin_flv', 'title'=>$title));
279     $output .= html_writer::script(js_writer::function_call('M.util.add_video_player', array($id, $fullurl, $width, $height, $autosize)));
280     $output .= '</div>';
282     return $output;
285 /**
286  * Returns flash embedding html.
287  * @param string $fullurl
288  * @param string $title
289  * @param string $clicktoopen
290  * @return string html
291  */
292 function resourcelib_embed_flash($fullurl, $title, $clicktoopen) {
293     if (preg_match('/[#\?]d=([\d]{1,4}%?)x([\d]{1,4}%?)/', $fullurl, $matches)) {
294         $width    = $matches[1];
295         $height   = $matches[2];
296     } else {
297         $width    = 400;
298         $height   = 300;
299     }
301     $code = <<<EOT
302 <div class="resourcecontent resourceswf">
303   <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="$width" height="$height">
304     <param name="movie" value="$fullurl" />
305     <param name="autoplay" value="true" />
306     <param name="loop" value="true" />
307     <param name="controller" value="true" />
308     <param name="scale" value="aspect" />
309     <param name="base" value="." />
310 <!--[if !IE]>-->
311     <object type="application/x-shockwave-flash" data="$fullurl" width="$width" height="$height">
312       <param name="controller" value="true" />
313       <param name="autoplay" value="true" />
314       <param name="loop" value="true" />
315       <param name="scale" value="aspect" />
316       <param name="base" value="." />
317 <!--<![endif]-->
318 $clicktoopen
319 <!--[if !IE]>-->
320     </object>
321 <!--<![endif]-->
322   </object>
323 </div>
324 EOT;
326     return $code;
329 /**
330  * Returns ms media embedding html.
331  * @param string $fullurl
332  * @param string $title
333  * @param string $clicktoopen
334  * @return string html
335  */
336 function resourcelib_embed_mediaplayer($fullurl, $title, $clicktoopen) {
337     $code = <<<EOT
338 <div class="resourcecontent resourcewmv">
339   <object type="video/x-ms-wmv" data="$fullurl">
340     <param name="controller" value="true" />
341     <param name="autostart" value="true" />
342     <param name="src" value="$fullurl" />
343     <param name="scale" value="noScale" />
344     $clicktoopen
345   </object>
346 </div>
347 EOT;
349     return $code;
352 /**
353  * Returns quicktime embedding html.
354  * @param string $fullurl
355  * @param string $title
356  * @param string $clicktoopen
357  * @return string html
358  */
359 function resourcelib_embed_quicktime($fullurl, $title, $clicktoopen) {
360     $code = <<<EOT
361 <div class="resourcecontent resourceqt">
362   <object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" codebase="http://www.apple.com/qtactivex/qtplugin.cab">
363     <param name="src" value="$fullurl" />
364     <param name="autoplay" value="true" />
365     <param name="loop" value="true" />
366     <param name="controller" value="true" />
367     <param name="scale" value="aspect" />
368 <!--[if !IE]>-->
369     <object type="video/quicktime" data="$fullurl">
370       <param name="controller" value="true" />
371       <param name="autoplay" value="true" />
372       <param name="loop" value="true" />
373       <param name="scale" value="aspect" />
374 <!--<![endif]-->
375 $clicktoopen
376 <!--[if !IE]>-->
377     </object>
378 <!--<![endif]-->
379   </object>
380 </div>
381 EOT;
383     return $code;
386 /**
387  * Returns mpeg embedding html.
388  * @param string $fullurl
389  * @param string $title
390  * @param string $clicktoopen
391  * @return string html
392  */
393 function resourcelib_embed_mpeg($fullurl, $title, $clicktoopen) {
394     $code = <<<EOT
395 <div class="resourcecontent resourcempeg">
396   <object classid="CLSID:22d6f312-b0f6-11d0-94ab-0080c74c7e95" codebase="http://activex.microsoft.com/activex/controls/mplayer/en/nsm p2inf.cab#Version=5,1,52,701" type="application/x-oleobject">
397     <param name="fileName" value="$fullurl" />
398     <param name="autoStart" value="true" />
399     <param name="animationatStart" value="true" />
400     <param name="transparentatStart" value="true" />
401     <param name="showControls" value="true" />
402     <param name="Volume" value="-450" />
403 <!--[if !IE]>-->
404     <object type="video/mpeg" data="$fullurl">
405       <param name="controller" value="true" />
406       <param name="autostart" value="true" />
407       <param name="src" value="$fullurl" />
408 <!--<![endif]-->
409 $clicktoopen
410 <!--[if !IE]>-->
411     </object>
412 <!--<![endif]-->
413   </object>
414 </div>
415 EOT;
417     return $code;
420 /**
421  * Returns real media embedding html.
422  * @param string $fullurl
423  * @param string $title
424  * @param string $clicktoopen
425  * @return string html
426  */
427 function resourcelib_embed_real($fullurl, $title, $clicktoopen) {
428     $code = <<<EOT
429 <div class="resourcecontent resourcerm">
430   <object classid="clsid:CFCDAA03-8BE4-11cf-B84B-0020AFBBCCFA" data="$fullurl" width="320" height="240">
431     <param name="src" value="$fullurl" />
432     <param name="controls" value="All" />
433 <!--[if !IE]>-->
434     <object type="audio/x-pn-realaudio-plugin" data="$fullurl" width="320" height="240">
435     <param name="src" value="$fullurl" />
436       <param name="controls" value="All" />
437 <!--<![endif]-->
438 $clicktoopen
439 <!--[if !IE]>-->
440     </object>
441 <!--<![endif]-->
442   </object>
443 </div>
444 EOT;
446     return $code;
449 /**
450  * Returns general link or pdf embedding html.
451  * @param string $fullurl
452  * @param string $title
453  * @param string $clicktoopen
454  * @return string html
455  */
456 function resourcelib_embed_pdf($fullurl, $title, $clicktoopen) {
457     global $CFG, $PAGE;
459     $code = <<<EOT
460 <div class="resourcecontent resourcepdf">
461   <object id="resourceobject" data="$fullurl" type="application/pdf" width="800" height="600">
462     <param name="src" value="$fullurl" />
463     $clicktoopen
464   </object>
465 </div>
466 EOT;
468     // the size is hardcoded in the boject obove intentionally because it is adjusted by the following function on-the-fly
469     $PAGE->requires->js_init_call('M.util.init_maximised_embed', array('resourceobject'), true);
471     return $code;
475 /**
476  * Returns general link or file embedding html.
477  * @param string $fullurl
478  * @param string $title
479  * @param string $clicktoopen
480  * @param string $mimetype
481  * @return string html
482  */
483 function resourcelib_embed_general($fullurl, $title, $clicktoopen, $mimetype) {
484     global $CFG, $PAGE;
486     if ($fullurl instanceof moodle_url) {
487         $fullurl = $fullurl->out();
488     }
490     $iframe = false;
492     $param = '<param name="src" value="'.$fullurl.'" />';
494     // IE can not embed stuff properly, that is why we use iframe instead.
495     // Unfortunately this tag does not validate in xhtml strict mode,
496     // but in any case it is undeprecated in HTML 5 - we will use it everywhere soon!
497     if ($mimetype === 'text/html' and check_browser_version('MSIE', 5)) {
498         $iframe = true;
499     }
501     if ($iframe) {
502         $code = <<<EOT
503 <div class="resourcecontent resourcegeneral">
504   <iframe id="resourceobject" src="$fullurl">
505     $clicktoopen
506   </iframe>
507 </div>
508 EOT;
509     } else {
510         $code = <<<EOT
511 <div class="resourcecontent resourcegeneral">
512   <object id="resourceobject" data="$fullurl" type="$mimetype"  width="800" height="600">
513     $param
514     $clicktoopen
515   </object>
516 </div>
517 EOT;
518     }
520     // the size is hardcoded in the boject obove intentionally because it is adjusted by the following function on-the-fly
521     $PAGE->requires->js_init_call('M.util.init_maximised_embed', array('resourceobject'), true);
523     return $code;