Passed
Pull Request — 1.11.x (#5783)
by Yannick
08:32
created

DocumentManager::generateAudioTempFile()   A

Complexity

Conditions 5
Paths 12

Size

Total Lines 37
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 20
nc 12
nop 2
dl 0
loc 37
rs 9.2888
c 0
b 0
f 0
1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
use ChamiloSession as Session;
6
7
/**
8
 *  Class DocumentManager
9
 *  This is the document library for Chamilo.
10
 *  It is / will be used to provide a service layer to all document-using tools.
11
 *  and eliminate code duplication fro group documents, scorm documents, main documents.
12
 *  Include/require it in your code to use its functionality.
13
 */
14
class DocumentManager
15
{
16
    /**
17
     * Construct.
18
     */
19
    private function __construct()
20
    {
21
    }
22
23
    /**
24
     * @param string $course_code
25
     *
26
     * @return int the document folder quota for the current course in bytes
27
     *             or the default quota
28
     */
29
    public static function get_course_quota($course_code = null)
30
    {
31
        if (empty($course_code)) {
32
            $course_info = api_get_course_info();
33
        } else {
34
            $course_info = api_get_course_info($course_code);
35
        }
36
37
        $course_quota = null;
38
        if (empty($course_info)) {
39
            return DEFAULT_DOCUMENT_QUOTA;
40
        } else {
41
            $course_quota = $course_info['disk_quota'];
42
        }
43
        if (is_null($course_quota) || empty($course_quota)) {
44
            // Course table entry for quota was null, then use default value
45
            $course_quota = DEFAULT_DOCUMENT_QUOTA;
46
        }
47
48
        return $course_quota;
49
    }
50
51
    /**
52
     * Get the content type of a file by checking the extension
53
     * We could use mime_content_type() with php-versions > 4.3,
54
     * but this doesn't work as it should on Windows installations.
55
     *
56
     * @param string $filename or boolean TRUE to return complete array
57
     *
58
     * @author ? first version
59
     * @author Bert Vanderkimpen
60
     *
61
     * @return string
62
     */
63
    public static function file_get_mime_type($filename)
64
    {
65
        // All MIME types in an array (from 1.6, this is the authorative source)
66
        // Please, keep this alphabetical if you add something to this list!
67
        $mimeTypes = [
68
            'ai' => 'application/postscript',
69
            'aif' => 'audio/x-aiff',
70
            'aifc' => 'audio/x-aiff',
71
            'aiff' => 'audio/x-aiff',
72
            'asf' => 'video/x-ms-asf',
73
            'asc' => 'text/plain',
74
            'au' => 'audio/basic',
75
            'avi' => 'video/x-msvideo',
76
            'bcpio' => 'application/x-bcpio',
77
            'bin' => 'application/octet-stream',
78
            'bmp' => 'image/bmp',
79
            'cdf' => 'application/x-netcdf',
80
            'class' => 'application/octet-stream',
81
            'cpio' => 'application/x-cpio',
82
            'cpt' => 'application/mac-compactpro',
83
            'csh' => 'application/x-csh',
84
            'css' => 'text/css',
85
            'dcr' => 'application/x-director',
86
            'dir' => 'application/x-director',
87
            'djv' => 'image/vnd.djvu',
88
            'djvu' => 'image/vnd.djvu',
89
            'dll' => 'application/octet-stream',
90
            'dmg' => 'application/x-diskcopy',
91
            'dms' => 'application/octet-stream',
92
            'doc' => 'application/msword',
93
            'docm' => 'application/vnd.ms-word.document.macroEnabled.12',
94
            'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
95
            'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
96
            'dvi' => 'application/x-dvi',
97
            'dwg' => 'application/vnd.dwg',
98
            'dwf' => 'application/vnd.dwf',
99
            'dxf' => 'application/vnd.dxf',
100
            'dxr' => 'application/x-director',
101
            'eps' => 'application/postscript',
102
            'epub' => 'application/epub+zip',
103
            'etx' => 'text/x-setext',
104
            'exe' => 'application/octet-stream',
105
            'ez' => 'application/andrew-inset',
106
            'flv' => 'video/flv',
107
            'gif' => 'image/gif',
108
            'gtar' => 'application/x-gtar',
109
            'gz' => 'application/x-gzip',
110
            'hdf' => 'application/x-hdf',
111
            'hqx' => 'application/mac-binhex40',
112
            'htm' => 'text/html',
113
            'html' => 'text/html',
114
            'ice' => 'x-conference-xcooltalk',
115
            'ief' => 'image/ief',
116
            'iges' => 'model/iges',
117
            'igs' => 'model/iges',
118
            'jar' => 'application/java-archiver',
119
            'jpe' => 'image/jpeg',
120
            'jpeg' => 'image/jpeg',
121
            'jpg' => 'image/jpeg',
122
            'js' => 'application/x-javascript',
123
            'kar' => 'audio/midi',
124
            'lam' => 'application/vnd.ms-excel.addin.macroEnabled.12',
125
            'latex' => 'application/x-latex',
126
            'lha' => 'application/octet-stream',
127
            'log' => 'text/plain',
128
            'lzh' => 'application/octet-stream',
129
            'm1a' => 'audio/mpeg',
130
            'm2a' => 'audio/mpeg',
131
            'm3u' => 'audio/x-mpegurl',
132
            'man' => 'application/x-troff-man',
133
            'me' => 'application/x-troff-me',
134
            'mesh' => 'model/mesh',
135
            'mid' => 'audio/midi',
136
            'midi' => 'audio/midi',
137
            'mov' => 'video/quicktime',
138
            'movie' => 'video/x-sgi-movie',
139
            'mp2' => 'audio/mpeg',
140
            'mp3' => 'audio/mpeg',
141
            'mp4' => 'video/mp4',
142
            'mpa' => 'audio/mpeg',
143
            'mpe' => 'video/mpeg',
144
            'mpeg' => 'video/mpeg',
145
            'mpg' => 'video/mpeg',
146
            'mpga' => 'audio/mpeg',
147
            'ms' => 'application/x-troff-ms',
148
            'msh' => 'model/mesh',
149
            'mxu' => 'video/vnd.mpegurl',
150
            'nc' => 'application/x-netcdf',
151
            'oda' => 'application/oda',
152
            'oga' => 'audio/ogg',
153
            'ogg' => 'application/ogg',
154
            'ogx' => 'application/ogg',
155
            'ogv' => 'video/ogg',
156
            'pbm' => 'image/x-portable-bitmap',
157
            'pct' => 'image/pict',
158
            'pdb' => 'chemical/x-pdb',
159
            'pdf' => 'application/pdf',
160
            'pgm' => 'image/x-portable-graymap',
161
            'pgn' => 'application/x-chess-pgn',
162
            'pict' => 'image/pict',
163
            'png' => 'image/png',
164
            'pnm' => 'image/x-portable-anymap',
165
            'potm' => 'application/vnd.ms-powerpoint.template.macroEnabled.12',
166
            'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template',
167
            'pps' => 'application/vnd.ms-powerpoint',
168
            'ppam' => 'application/vnd.ms-powerpoint.addin.macroEnabled.12',
169
            'ppsm' => 'application/vnd.ms-powerpoint.slideshow.macroEnabled.12',
170
            'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
171
            'pptm' => 'application/vnd.ms-powerpoint.presentation.macroEnabled.12',
172
            'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
173
            'ppm' => 'image/x-portable-pixmap',
174
            'ppt' => 'application/vnd.ms-powerpoint',
175
            'ps' => 'application/postscript',
176
            'qt' => 'video/quicktime',
177
            'ra' => 'audio/x-realaudio',
178
            'ram' => 'audio/x-pn-realaudio',
179
            'rar' => 'image/x-rar-compressed',
180
            'ras' => 'image/x-cmu-raster',
181
            'rgb' => 'image/x-rgb',
182
            'rm' => 'audio/x-pn-realaudio',
183
            'roff' => 'application/x-troff',
184
            'rpm' => 'audio/x-pn-realaudio-plugin',
185
            'rtf' => 'text/rtf',
186
            'rtx' => 'text/richtext',
187
            'sgm' => 'text/sgml',
188
            'sgml' => 'text/sgml',
189
            'sh' => 'application/x-sh',
190
            'shar' => 'application/x-shar',
191
            'silo' => 'model/mesh',
192
            'sib' => 'application/X-Sibelius-Score',
193
            'sit' => 'application/x-stuffit',
194
            'skd' => 'application/x-koan',
195
            'skm' => 'application/x-koan',
196
            'skp' => 'application/x-koan',
197
            'skt' => 'application/x-koan',
198
            'smi' => 'application/smil',
199
            'smil' => 'application/smil',
200
            'snd' => 'audio/basic',
201
            'so' => 'application/octet-stream',
202
            'spl' => 'application/x-futuresplash',
203
            'src' => 'application/x-wais-source',
204
            'sv4cpio' => 'application/x-sv4cpio',
205
            'sv4crc' => 'application/x-sv4crc',
206
            'svf' => 'application/vnd.svf',
207
            'svg' => 'image/svg+xml',
208
            //'svgz' => 'image/svg+xml',
209
            'swf' => 'application/x-shockwave-flash',
210
            'sxc' => 'application/vnd.sun.xml.calc',
211
            'sxi' => 'application/vnd.sun.xml.impress',
212
            'sxw' => 'application/vnd.sun.xml.writer',
213
            't' => 'application/x-troff',
214
            'tar' => 'application/x-tar',
215
            'tcl' => 'application/x-tcl',
216
            'tex' => 'application/x-tex',
217
            'texi' => 'application/x-texinfo',
218
            'texinfo' => 'application/x-texinfo',
219
            'tga' => 'image/x-targa',
220
            'tif' => 'image/tif',
221
            'tiff' => 'image/tiff',
222
            'tr' => 'application/x-troff',
223
            'tsv' => 'text/tab-seperated-values',
224
            'txt' => 'text/plain',
225
            'ustar' => 'application/x-ustar',
226
            'vcd' => 'application/x-cdlink',
227
            'vrml' => 'model/vrml',
228
            'wav' => 'audio/x-wav',
229
            'wbmp' => 'image/vnd.wap.wbmp',
230
            'wbxml' => 'application/vnd.wap.wbxml',
231
            'webp' => 'image/webp',
232
            'wml' => 'text/vnd.wap.wml',
233
            'wmlc' => 'application/vnd.wap.wmlc',
234
            'wmls' => 'text/vnd.wap.wmlscript',
235
            'wmlsc' => 'application/vnd.wap.wmlscriptc',
236
            'wma' => 'audio/x-ms-wma',
237
            'wmv' => 'video/x-ms-wmv',
238
            'wrl' => 'model/vrml',
239
            'xbm' => 'image/x-xbitmap',
240
            'xht' => 'application/xhtml+xml',
241
            'xhtml' => 'application/xhtml+xml',
242
            'xls' => 'application/vnd.ms-excel',
243
            'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12',
244
            'xlsm' => 'application/vnd.ms-excel.sheet.macroEnabled.12',
245
            'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
246
            'xltm' => 'application/vnd.ms-excel.template.macroEnabled.12',
247
            'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
248
            'xml' => 'text/xml',
249
            'xpm' => 'image/x-xpixmap',
250
            'xsl' => 'text/xml',
251
            'xwd' => 'image/x-windowdump',
252
            'xyz' => 'chemical/x-xyz',
253
            'zip' => 'application/zip',
254
        ];
255
256
        if ($filename === true) {
257
            return $mimeTypes;
258
        }
259
260
        // Get the extension of the file
261
        $extension = explode('.', $filename);
262
263
        // $filename will be an array if a . was found
264
        if (is_array($extension)) {
265
            $extension = strtolower($extension[count($extension) - 1]);
266
        } else {
267
            //file without extension
268
            $extension = 'empty';
269
        }
270
271
        //if the extension is found, return the content type
272
        if (isset($mimeTypes[$extension])) {
273
            return $mimeTypes[$extension];
274
        }
275
276
        return 'application/octet-stream';
277
    }
278
279
    /**
280
     * This function smart streams a file to the client using HTTP headers.
281
     *
282
     * @param string $fullFilename The full path of the file to be sent
283
     * @param string $filename     The name of the file as shown to the client
284
     * @param string $contentType  The MIME type of the file
285
     *
286
     * @return bool false if file doesn't exist, true if stream succeeded
287
     */
288
    public static function smartReadFile($fullFilename, $filename, $contentType = 'application/octet-stream')
289
    {
290
        if (!file_exists($fullFilename)) {
291
            header("HTTP/1.1 404 Not Found");
292
293
            return false;
294
        }
295
296
        $size = filesize($fullFilename);
297
        $time = date('r', filemtime($fullFilename));
298
299
        $fm = @fopen($fullFilename, 'rb');
300
        if (!$fm) {
0 ignored issues
show
introduced by
$fm is of type false|resource, thus it always evaluated to false.
Loading history...
301
            header("HTTP/1.1 505 Internal server error");
302
303
            return false;
304
        }
305
306
        $begin = 0;
307
        $end = $size - 1;
308
309
        if (isset($_SERVER['HTTP_RANGE'])) {
310
            if (preg_match('/bytes=\h*(\d+)-(\d*)[\D.*]?/i', $_SERVER['HTTP_RANGE'], $matches)) {
311
                $begin = intval($matches[1]);
312
                if (!empty($matches[2])) {
313
                    $end = intval($matches[2]);
314
                }
315
            }
316
        }
317
318
        if (isset($_SERVER['HTTP_RANGE'])) {
319
            header('HTTP/1.1 206 Partial Content');
320
        } else {
321
            header('HTTP/1.1 200 OK');
322
        }
323
324
        header("Content-Type: $contentType");
325
        header('Cache-Control: public, must-revalidate, max-age=0');
326
        header('Pragma: no-cache');
327
        header('Accept-Ranges: bytes');
328
        header('Content-Length:'.(($end - $begin) + 1));
329
        if (isset($_SERVER['HTTP_RANGE'])) {
330
            header("Content-Range: bytes $begin-$end/$size");
331
        }
332
        header("Content-Disposition: inline; filename=$filename");
333
        header("Content-Transfer-Encoding: binary");
334
        header("Last-Modified: $time");
335
336
        $cur = $begin;
337
        fseek($fm, $begin, 0);
338
339
        while (!feof($fm) && $cur <= $end && (connection_status() == 0)) {
340
            echo fread($fm, min(1024 * 16, ($end - $cur) + 1));
341
            $cur += 1024 * 16;
342
        }
343
    }
344
345
    /**
346
     * This function streams a file to the client.
347
     *
348
     * @param string $full_file_name
349
     * @param bool   $forced              Whether to force the browser to download the file
350
     * @param string $name
351
     * @param bool   $fixLinksHttpToHttps change file content from http to https
352
     * @param array  $extraHeaders        Additional headers to be sent
353
     *
354
     * @return false if file doesn't exist, true if stream succeeded
355
     */
356
    public static function file_send_for_download(
357
        $full_file_name,
358
        $forced = false,
359
        $name = '',
360
        $fixLinksHttpToHttps = false,
361
        $extraHeaders = []
362
    ) {
363
        session_write_close(); //we do not need write access to session anymore
364
        if (!is_file($full_file_name)) {
365
            return false;
366
        }
367
        $filename = $name == '' ? basename($full_file_name) : api_replace_dangerous_char($name);
368
        $len = filesize($full_file_name);
369
        // Fixing error when file name contains a ","
370
        $filename = str_replace(',', '', $filename);
371
        $sendFileHeaders = api_get_configuration_value('enable_x_sendfile_headers');
372
373
        // Allows chrome to make videos and audios seekable
374
        header('Accept-Ranges: bytes');
375
        if (!empty($extraHeaders)) {
376
            foreach ($extraHeaders as $name => $value) {
377
                //TODO: add restrictions to allowed headers?
378
                header($name.': '.$value);
379
            }
380
        }
381
382
        if ($forced) {
383
            // Force the browser to save the file instead of opening it
384
            if (isset($sendFileHeaders) &&
385
                !empty($sendFileHeaders)) {
386
                header("X-Sendfile: $filename");
387
            }
388
389
            header('Content-type: application/octet-stream');
390
            header('Content-length: '.$len);
391
            if (preg_match("/MSIE 5.5/", $_SERVER['HTTP_USER_AGENT'])) {
392
                header('Content-Disposition: filename= '.$filename);
393
            } else {
394
                header('Content-Disposition: attachment; filename= '.$filename);
395
            }
396
            if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE')) {
397
                header('Pragma: ');
398
                header('Cache-Control: ');
399
                header('Cache-Control: public'); // IE cannot download from sessions without a cache
400
            }
401
            header('Content-Description: '.$filename);
402
            header('Content-Transfer-Encoding: binary');
403
404
            if (function_exists('ob_end_clean') && ob_get_length()) {
405
                // Use ob_end_clean() to avoid weird buffering situations
406
                // where file is sent broken/incomplete for download
407
                ob_end_clean();
408
            }
409
410
            $res = fopen($full_file_name, 'r');
411
            fpassthru($res);
412
413
            return true;
414
        } else {
415
            // no forced download, just let the browser decide what to do according to the mimetype
416
            $lpFixedEncoding = api_get_configuration_value('lp_fixed_encoding');
417
418
            // Commented to let courses content to be cached in order to improve performance:
419
            //header('Expires: Wed, 01 Jan 1990 00:00:00 GMT');
420
            //header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
421
422
            // Commented to avoid double caching declaration when playing with IE and HTTPS
423
            //header('Cache-Control: no-cache, must-revalidate');
424
            //header('Pragma: no-cache');
425
426
            $contentType = self::file_get_mime_type($filename);
427
428
            switch ($contentType) {
429
                case 'text/html':
430
                    $enableMathJaxScript = api_get_setting('enabled_mathjax') && api_get_configuration_value('mathjax_enable_script_header_in_all_HTML_document');
431
                    if (isset($lpFixedEncoding) && $lpFixedEncoding === 'true') {
432
                        $contentType .= '; charset=UTF-8';
433
                    } else {
434
                        $encoding = @api_detect_encoding_html(file_get_contents($full_file_name));
435
                        if (!empty($encoding)) {
436
                            $contentType .= '; charset='.$encoding;
437
                        }
438
                    }
439
                    break;
440
                case 'text/plain':
441
                    if (isset($lpFixedEncoding) && $lpFixedEncoding === 'true') {
442
                        $contentType .= '; charset=UTF-8';
443
                    } else {
444
                        $encoding = @api_detect_encoding(strip_tags(file_get_contents($full_file_name)));
445
                        if (!empty($encoding)) {
446
                            $contentType .= '; charset='.$encoding;
447
                        }
448
                    }
449
                    break;
450
                case 'video/mp4':
451
                case 'audio/mpeg':
452
                case 'audio/mp4':
453
                case 'audio/ogg':
454
                case 'audio/webm':
455
                case 'audio/wav':
456
                case 'video/ogg':
457
                case 'video/webm':
458
                    self::smartReadFile($full_file_name, $filename, $contentType);
459
                    exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
460
                case 'application/vnd.dwg':
461
                case 'application/vnd.dwf':
462
                    header('Content-type: application/octet-stream');
463
                    break;
464
            }
465
466
            header('Content-type: '.$contentType);
467
            header('Content-Length: '.$len);
468
            $userAgent = strtolower($_SERVER['HTTP_USER_AGENT']);
469
470
            if (strpos($userAgent, 'msie')) {
471
                header('Content-Disposition: ; filename= '.$filename);
472
            } else {
473
                //header('Content-Disposition: inline');
474
                header('Content-Disposition: inline;');
475
            }
476
477
            if ($fixLinksHttpToHttps) {
478
                $content = file_get_contents($full_file_name);
479
                $content = str_replace(
480
                    ['http%3A%2F%2F', 'http://'],
481
                    ['https%3A%2F%2F', 'https://'],
482
                    $content
483
                );
484
                if ($enableMathJaxScript === true) {
485
                    $content = self::includeMathJaxScript($content);
486
                }
487
                echo $content;
488
            } else {
489
                if (isset($enableMathJaxScript) && $enableMathJaxScript === true) {
490
                    $content = file_get_contents($full_file_name);
491
                    $content = self::includeMathJaxScript($content);
492
                    echo $content;
493
                } else {
494
                    if (function_exists('ob_end_clean') && ob_get_length()) {
495
                        // Use ob_end_clean() to avoid weird buffering situations
496
                        // where file is sent broken/incomplete for download
497
                        ob_end_clean();
498
                    }
499
                    readfile($full_file_name);
500
                }
501
            }
502
503
            return true;
504
        }
505
    }
506
507
    /**
508
     * Session folder filters.
509
     *
510
     * @param string $path
511
     * @param int    $sessionId
512
     *
513
     * @return string|null
514
     */
515
    public static function getSessionFolderFilters($path, $sessionId)
516
    {
517
        $sessionId = (int) $sessionId;
518
        $condition = null;
519
520
        if (!empty($sessionId)) {
521
            // Chat folder filter
522
            if ($path == '/chat_files') {
523
                $condition .= " AND (docs.session_id = '$sessionId') ";
524
            }
525
            // share_folder filter
526
            $condition .= " AND docs.path != '/shared_folder' ";
527
        }
528
529
        return $condition;
530
    }
531
532
    /**
533
     * Fetches all document data for the given user/group.
534
     *
535
     * @param array  $courseInfo
536
     * @param string $path
537
     * @param int    $toGroupId       iid
538
     * @param int    $toUserId
539
     * @param bool   $canSeeInvisible
540
     * @param bool   $search
541
     * @param int    $sessionId
542
     *
543
     * @return array with all document data
544
     */
545
    public static function getAllDocumentData(
546
        $courseInfo,
547
        $path = '/',
548
        $toGroupId = 0,
549
        $toUserId = null,
550
        $canSeeInvisible = false,
551
        $search = false,
552
        $sessionId = 0
553
    ) {
554
        if (empty($courseInfo)) {
555
            return [];
556
        }
557
558
        $tblItemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
559
        $tblDocument = Database::get_course_table(TABLE_DOCUMENT);
560
561
        if (!is_null($toUserId)) {
562
            $toUserId = (int) $toUserId;
563
            $userGroupFilter = "last.to_user_id = $toUserId";
564
            if (empty($toUserId)) {
565
                $userGroupFilter = ' (last.to_user_id = 0 OR last.to_user_id IS NULL) ';
566
            }
567
        } else {
568
            $toGroupId = (int) $toGroupId;
569
            $userGroupFilter = "last.to_group_id = $toGroupId";
570
            if (empty($toGroupId)) {
571
                $userGroupFilter = '( last.to_group_id = 0 OR last.to_group_id IS NULL) ';
572
            }
573
        }
574
575
        // Escape underscores in the path so they don't act as a wildcard
576
        $originalPath = $path;
577
        $path = str_replace('_', '\_', $path);
578
579
        $visibilityBit = ' <> 2';
580
581
        // The given path will not end with a slash, unless it's the root '/'
582
        // so no root -> add slash
583
        $addedSlash = $path == '/' ? '' : '/';
584
585
        // Condition for the session
586
        $sessionId = $sessionId ?: api_get_session_id();
587
        $conditionSession = " AND (last.session_id = '$sessionId' OR (last.session_id = '0' OR last.session_id IS NULL) )";
588
        $conditionSession .= self::getSessionFolderFilters($originalPath, $sessionId);
589
590
        $sharedCondition = null;
591
        if ($originalPath == '/shared_folder') {
592
            $students = CourseManager::get_user_list_from_course_code($courseInfo['code'], $sessionId);
593
            if (!empty($students)) {
594
                $conditionList = [];
595
                foreach ($students as $studentInfo) {
596
                    $conditionList[] = '/shared_folder/sf_user_'.$studentInfo['user_id'];
597
                }
598
                $sharedCondition .= ' AND docs.path IN ("'.implode('","', $conditionList).'")';
599
            }
600
        }
601
        $where = '';
602
        if ($search != true) {
603
            $where .= "docs.path NOT LIKE '".Database::escape_string($path.$addedSlash.'%/%')."' AND";
604
        }
605
        $sql = "SELECT
606
                    docs.id,
607
                    docs.filetype,
608
                    docs.path,
609
                    docs.title,
610
                    docs.comment,
611
                    docs.size,
612
                    docs.readonly,
613
                    docs.session_id,
614
                    last.session_id item_property_session_id,
615
                    last.lastedit_date,
616
                    last.visibility,
617
                    last.insert_user_id
618
                FROM $tblItemProperty AS last
619
                INNER JOIN $tblDocument AS docs
620
                ON (
621
                    docs.id = last.ref AND
622
                    docs.c_id = last.c_id
623
                )
624
                WHERE
625
                    last.tool = '".TOOL_DOCUMENT."' AND
626
                    docs.c_id = {$courseInfo['real_id']} AND
627
                    last.c_id = {$courseInfo['real_id']} AND
628
                    docs.path LIKE '".Database::escape_string($path.$addedSlash.'%')."' AND
629
                    $where
630
                    docs.path NOT LIKE '%_DELETED_%' AND
631
                    $userGroupFilter AND
632
                    last.visibility $visibilityBit
633
                    $conditionSession
634
                    $sharedCondition
635
                ORDER BY last.iid DESC, last.session_id DESC
636
                ";
637
638
        $result = Database::query($sql);
639
640
        $documentData = [];
641
        $isAllowedToEdit = api_is_allowed_to_edit(null, true);
642
        $isCoach = api_is_coach();
643
        if ($result !== false && Database::num_rows($result) != 0) {
644
            $rows = [];
645
646
            $hideInvisibleDocuments = api_get_configuration_value('hide_invisible_course_documents_in_sessions');
647
648
            while ($row = Database::fetch_array($result, 'ASSOC')) {
649
                if (isset($rows[$row['id']])) {
650
                    continue;
651
                }
652
653
                // If we are in session and hide_invisible_course_documents_in_sessions is enabled
654
                // Then we avoid the documents that have visibility in session but that they come from a base course
655
                if ($hideInvisibleDocuments && $sessionId) {
656
                    if ($row['item_property_session_id'] == $sessionId && empty($row['session_id'])) {
657
                        continue;
658
                    }
659
                }
660
661
                if (self::isBasicCourseFolder($row['path'], $sessionId)) {
662
                    $basicCourseDocumentsContent = self::getAllDocumentData(
663
                        $courseInfo,
664
                        $row['path']
665
                    );
666
667
                    if (empty($basicCourseDocumentsContent)) {
668
                        continue;
669
                    }
670
                }
671
672
                $rows[$row['id']] = $row;
673
            }
674
675
            // If we are in session and hide_invisible_course_documents_in_sessions is enabled
676
            // Or if we are students
677
            // Then don't list the invisible or deleted documents
678
            if (($sessionId && $hideInvisibleDocuments) || (!$isCoach && !$isAllowedToEdit)) {
679
                $rows = array_filter($rows, function ($row) {
680
                    if (in_array($row['visibility'], ['0', '2'])) {
681
                        return false;
682
                    }
683
684
                    return true;
685
                });
686
            }
687
688
            foreach ($rows as $row) {
689
                if ($row['filetype'] === 'file' &&
690
                    pathinfo($row['path'], PATHINFO_EXTENSION) == 'html'
691
                ) {
692
                    // Templates management
693
                    $tblTemplate = Database::get_main_table(TABLE_MAIN_TEMPLATES);
694
                    $sql = "SELECT id FROM $tblTemplate
695
                            WHERE
696
                                course_code = '".$courseInfo['code']."' AND
697
                                user_id = '".api_get_user_id()."' AND
698
                                ref_doc = '".$row['id']."'";
699
                    $templateResult = Database::query($sql);
700
                    $row['is_template'] = (Database::num_rows($templateResult) > 0) ? 1 : 0;
701
                }
702
                $row['basename'] = basename($row['path']);
703
                // Just filling $document_data.
704
                $documentData[$row['id']] = $row;
705
            }
706
707
            // Only for the student we filter the results see BT#1652
708
            if (!$isCoach && !$isAllowedToEdit) {
709
                // Checking parents visibility.
710
                $finalDocumentData = [];
711
712
                foreach ($documentData as $row) {
713
                    $isVisible = self::check_visibility_tree(
714
                        $row['id'],
715
                        $courseInfo,
716
                        $sessionId,
717
                        api_get_user_id(),
718
                        $toGroupId
719
                    );
720
                    if ($isVisible) {
721
                        $finalDocumentData[$row['id']] = $row;
722
                    }
723
                }
724
            } else {
725
                $finalDocumentData = $documentData;
726
            }
727
728
            return $finalDocumentData;
729
        }
730
731
        return [];
732
    }
733
734
    /**
735
     * Gets the paths of all folders in a course
736
     * can show all folders (except for the deleted ones) or only visible ones.
737
     *
738
     * @param array  $_course
739
     * @param int    $groupIid          iid
740
     * @param bool   $can_see_invisible
741
     * @param bool   $getInvisibleList
742
     * @param string $path              current path
743
     *
744
     * @return array with paths
745
     */
746
    public static function get_all_document_folders(
747
        $_course,
748
        $groupIid = 0,
749
        $can_see_invisible = false,
750
        $getInvisibleList = false,
751
        $path = ''
752
    ) {
753
        if (empty($_course)) {
754
            return [];
755
        }
756
757
        $TABLE_ITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
758
        $TABLE_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
759
        $groupIid = (int) $groupIid;
760
        $document_folders = [];
761
762
        $students = CourseManager::get_user_list_from_course_code(
763
            $_course['code'],
764
            api_get_session_id()
765
        );
766
767
        $conditionList = [];
768
        if (!empty($students)) {
769
            foreach ($students as $studentId => $studentInfo) {
770
                $conditionList[] = '/shared_folder/sf_user_'.$studentInfo['user_id'];
771
            }
772
        }
773
774
        $groupCondition = " last.to_group_id = $groupIid";
775
        if (empty($groupIid)) {
776
            $groupCondition = ' (last.to_group_id = 0 OR last.to_group_id IS NULL)';
777
        }
778
779
        $show_users_condition = '';
780
        if (api_get_setting('show_users_folders') === 'false') {
781
            $show_users_condition = " AND docs.path NOT LIKE '%shared_folder%'";
782
        }
783
784
        if ($can_see_invisible) {
785
            // condition for the session
786
            $session_id = api_get_session_id();
787
            $session_id = $session_id ?: api_get_session_id();
788
            $condition_session = " AND (last.session_id = '$session_id' OR (last.session_id = '0' OR last.session_id IS NULL) )";
789
            $condition_session .= self::getSessionFolderFilters($path, $session_id);
790
791
            if ($groupIid != 0) {
792
                $sql = "SELECT DISTINCT docs.id, path
793
                       FROM $TABLE_ITEMPROPERTY  AS last
794
                       INNER JOIN $TABLE_DOCUMENT  AS docs
795
                       ON (
796
                            docs.id = last.ref AND
797
                            docs.c_id = last.c_id
798
                       )
799
                       WHERE
800
                            last.tool = '".TOOL_DOCUMENT."' AND
801
                            last.c_id = {$_course['real_id']} AND
802
                            docs.c_id = {$_course['real_id']} AND
803
                            docs.filetype = 'folder' AND
804
                            $groupCondition AND
805
                            docs.path NOT LIKE '%shared_folder%' AND
806
                            docs.path NOT LIKE '%_DELETED_%' AND
807
                            last.visibility <> 2
808
                            $condition_session ";
809
            } else {
810
                $sql = "SELECT DISTINCT docs.id, path
811
                        FROM $TABLE_ITEMPROPERTY  AS last
812
                        INNER JOIN $TABLE_DOCUMENT  AS docs
813
                        ON (
814
                            docs.id = last.ref AND
815
                            docs.c_id = last.c_id
816
                        )
817
                        WHERE
818
                            last.tool = '".TOOL_DOCUMENT."' AND
819
                            last.c_id = {$_course['real_id']} AND
820
                            docs.c_id = {$_course['real_id']} AND
821
                            docs.filetype = 'folder' AND
822
                            docs.path NOT LIKE '%_DELETED_%' AND
823
                            $groupCondition AND
824
                            last.visibility <> 2
825
                            $show_users_condition
826
                            $condition_session
827
                        ";
828
            }
829
            $result = Database::query($sql);
830
831
            if ($result && Database::num_rows($result) != 0) {
832
                while ($row = Database::fetch_array($result, 'ASSOC')) {
833
                    if (self::is_folder_to_avoid($row['path'])) {
834
                        continue;
835
                    }
836
837
                    if (strpos($row['path'], '/shared_folder/') !== false) {
838
                        if (!in_array($row['path'], $conditionList)) {
839
                            continue;
840
                        }
841
                    }
842
843
                    $document_folders[$row['id']] = $row['path'];
844
                }
845
846
                if (!empty($document_folders)) {
847
                    // natsort($document_folders);
848
                    natcasesort($document_folders);
849
                }
850
851
                return $document_folders;
852
            } else {
853
                return false;
854
            }
855
        } else {
856
            // No invisible folders
857
            // Condition for the session
858
            $session_id = api_get_session_id();
859
            $condition_session = api_get_session_condition(
860
                $session_id,
861
                true,
862
                true, // needed to don't show files in elfinder browser
863
                'docs.session_id'
864
            );
865
866
            $visibilityCondition = 'last.visibility = 1';
867
            $fileType = "docs.filetype = 'folder' AND";
868
            if ($getInvisibleList) {
869
                $visibilityCondition = 'last.visibility = 0';
870
                $fileType = '';
871
            }
872
873
            //get visible folders
874
            $sql = "SELECT DISTINCT docs.id, path
875
                    FROM
876
                    $TABLE_ITEMPROPERTY AS last
877
                    INNER JOIN $TABLE_DOCUMENT AS docs
878
                    ON (docs.id = last.ref AND last.c_id = docs.c_id)
879
                    WHERE
880
                        $fileType
881
                        last.tool = '".TOOL_DOCUMENT."' AND
882
                        $groupCondition AND
883
                        $visibilityCondition
884
                        $show_users_condition
885
                        $condition_session AND
886
                        last.c_id = {$_course['real_id']}  AND
887
                        docs.c_id = {$_course['real_id']} ";
888
889
            $result = Database::query($sql);
890
891
            $visibleFolders = [];
892
            while ($row = Database::fetch_array($result, 'ASSOC')) {
893
                $visibleFolders[$row['id']] = $row['path'];
894
            }
895
896
            if ($getInvisibleList) {
897
                return $visibleFolders;
898
            }
899
900
            //get invisible folders
901
            $sql = "SELECT DISTINCT docs.id, path
902
                    FROM $TABLE_ITEMPROPERTY AS last
903
                    INNER JOIN $TABLE_DOCUMENT AS docs
904
                    ON (docs.id = last.ref AND last.c_id = docs.c_id)
905
                    WHERE
906
                        docs.filetype = 'folder' AND
907
                        last.tool = '".TOOL_DOCUMENT."' AND
908
                        $groupCondition AND
909
                        last.visibility = 0 $condition_session AND
910
                        last.c_id = {$_course['real_id']} AND
911
                        docs.c_id = {$_course['real_id']} ";
912
            $result = Database::query($sql);
913
            $invisibleFolders = [];
914
            while ($row = Database::fetch_array($result, 'ASSOC')) {
915
                //get visible folders in the invisible ones -> they are invisible too
916
                $sql = "SELECT DISTINCT docs.id, path
917
                        FROM $TABLE_ITEMPROPERTY AS last
918
                        INNER JOIN $TABLE_DOCUMENT AS docs
919
                        ON (docs.id = last.ref AND docs.c_id = last.c_id)
920
                        WHERE
921
                            docs.path LIKE '".Database::escape_string($row['path'].'/%')."' AND
922
                            docs.filetype = 'folder' AND
923
                            last.tool = '".TOOL_DOCUMENT."' AND
924
                            $groupCondition AND
925
                            last.visibility = 1 $condition_session AND
926
                            last.c_id = {$_course['real_id']} AND
927
                            docs.c_id = {$_course['real_id']}  ";
928
                $folder_in_invisible_result = Database::query($sql);
929
                while ($folders_in_invisible_folder = Database::fetch_array($folder_in_invisible_result, 'ASSOC')) {
930
                    $invisibleFolders[$folders_in_invisible_folder['id']] = $folders_in_invisible_folder['path'];
931
                }
932
            }
933
934
            // If both results are arrays -> //calculate the difference between the 2 arrays -> only visible folders are left :)
935
            if (is_array($visibleFolders) && is_array($invisibleFolders)) {
936
                $document_folders = array_diff($visibleFolders, $invisibleFolders);
937
                // natsort($document_folders);
938
                natcasesort($document_folders);
939
940
                return $document_folders;
941
            } elseif (is_array($visibleFolders)) {
942
                natcasesort($visibleFolders);
943
                // natsort($visibleFolders);
944
945
                return $visibleFolders;
946
            } else {
947
                //no visible folders found
948
                return false;
949
            }
950
        }
951
    }
952
953
    /**
954
     * This check if a document has the readonly property checked, then see if the user
955
     * is the owner of this file, if all this is true then return true.
956
     *
957
     * @param array  $_course
958
     * @param int    $user_id     id of the current user
959
     * @param string $file        path stored in the database (if not defined, $documentId must be used)
960
     * @param int    $document_id in case you dont have the file path ,
961
     *                            insert the id of the file here and leave $file in blank ''
962
     * @param bool   $to_delete
963
     * @param int    $sessionId
964
     *
965
     * @return bool true/false
966
     * */
967
    public static function check_readonly(
968
        $_course,
969
        $user_id,
970
        $file = null,
971
        $document_id = 0,
972
        $to_delete = false,
973
        $sessionId = null,
974
        $documentId = null
975
    ) {
976
        if (empty($sessionId)) {
977
            $sessionId = api_get_session_id();
978
        } else {
979
            $sessionId = intval($sessionId);
980
        }
981
982
        if (empty($document_id) || !is_numeric($document_id)) {
983
            $document_id = self::get_document_id($_course, $file, $sessionId);
984
        } else {
985
            $document_id = intval($document_id);
986
        }
987
988
        $TABLE_PROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
989
        $TABLE_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
990
        $course_id = $_course['real_id'];
991
992
        if ($to_delete) {
993
            if (self::is_folder($_course, $document_id)) {
994
                if (!empty($file)) {
995
                    $path = Database::escape_string($file);
996
                    // Check
997
                    $sql = "SELECT td.id, readonly, tp.insert_user_id
998
                            FROM $TABLE_DOCUMENT td
999
                            INNER JOIN $TABLE_PROPERTY tp
1000
                            ON (td.c_id = tp.c_id AND tp.ref= td.id)
1001
                            WHERE
1002
                                td.c_id = $course_id AND
1003
                                tp.c_id = $course_id AND
1004
                                td.session_id = $sessionId AND
1005
                                (path='".$path."' OR path LIKE BINARY '".$path."/%' ) ";
1006
                    // Get all id's of documents that are deleted
1007
                    $what_to_check_result = Database::query($sql);
1008
1009
                    if ($what_to_check_result && Database::num_rows($what_to_check_result) != 0) {
1010
                        // file with readonly set to 1 exist?
1011
                        $readonly_set = false;
1012
                        while ($row = Database::fetch_array($what_to_check_result)) {
1013
                            //query to delete from item_property table
1014
                            if ($row['readonly'] == 1) {
1015
                                if (!($row['insert_user_id'] == $user_id)) {
1016
                                    $readonly_set = true;
1017
                                    break;
1018
                                }
1019
                            }
1020
                        }
1021
1022
                        if ($readonly_set) {
1023
                            return true;
1024
                        }
1025
                    }
1026
                }
1027
1028
                return false;
1029
            }
1030
        }
1031
1032
        if (!empty($document_id)) {
1033
            $sql = "SELECT a.insert_user_id, b.readonly
1034
                   FROM $TABLE_PROPERTY a
1035
                   INNER JOIN $TABLE_DOCUMENT b
1036
                   ON (a.c_id = b.c_id AND a.ref= b.id)
1037
                   WHERE
1038
            			a.c_id = $course_id AND
1039
                        b.c_id = $course_id AND
1040
            			a.ref = $document_id
1041
                    LIMIT 1";
1042
            $result = Database::query($sql);
1043
            $doc_details = Database::fetch_array($result, 'ASSOC');
1044
1045
            if ($doc_details['readonly'] == 1) {
1046
                return !($doc_details['insert_user_id'] == $user_id || api_is_platform_admin());
1047
            }
1048
        }
1049
1050
        return false;
1051
    }
1052
1053
    /**
1054
     * This check if a document is a folder or not.
1055
     *
1056
     * @param array $_course
1057
     * @param int   $id      document id
1058
     *
1059
     * @return bool true/false
1060
     * */
1061
    public static function is_folder($_course, $id)
1062
    {
1063
        $table = Database::get_course_table(TABLE_DOCUMENT);
1064
        if (empty($_course)) {
1065
            return false;
1066
        }
1067
        $course_id = $_course['real_id'];
1068
        $id = (int) $id;
1069
        $sql = "SELECT filetype FROM $table
1070
                WHERE c_id = $course_id AND id= $id";
1071
        $result = Database::fetch_array(Database::query($sql), 'ASSOC');
1072
1073
        return $result['filetype'] == 'folder';
1074
    }
1075
1076
    /**
1077
     * @param int   $document_id
1078
     * @param array $course_info
1079
     * @param int   $session_id
1080
     * @param bool  $remove_content_from_db
1081
     */
1082
    public static function deleteDocumentFromDb(
1083
        $document_id,
1084
        $course_info = [],
1085
        $session_id = 0,
1086
        $remove_content_from_db = false
1087
    ) {
1088
        $TABLE_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
1089
        $TABLE_ITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
1090
1091
        // Deleting from the DB
1092
        $user_id = api_get_user_id();
1093
        $document_id = (int) $document_id;
1094
1095
        if (empty($course_info)) {
1096
            $course_info = api_get_course_info();
1097
        }
1098
1099
        if (empty($session_id)) {
1100
            $session_id = api_get_session_id();
1101
        }
1102
        // Soft DB delete
1103
        api_item_property_update(
1104
            $course_info,
1105
            TOOL_DOCUMENT,
1106
            $document_id,
1107
            'delete',
1108
            $user_id,
1109
            null,
1110
            null,
1111
            null,
1112
            null,
1113
            $session_id
1114
        );
1115
        self::delete_document_from_search_engine($course_info['code'], $document_id);
1116
        self::unset_document_as_template($document_id, $course_info['code'], $user_id);
1117
1118
        //Hard DB delete
1119
        if ($remove_content_from_db) {
1120
            $sql = "DELETE FROM $TABLE_ITEMPROPERTY
1121
                    WHERE
1122
                        c_id = {$course_info['real_id']} AND
1123
                        ref = ".$document_id." AND
1124
                        tool='".TOOL_DOCUMENT."'";
1125
            Database::query($sql);
1126
1127
            $sql = "DELETE FROM $TABLE_DOCUMENT
1128
                    WHERE c_id = {$course_info['real_id']} AND id = ".$document_id;
1129
            Database::query($sql);
1130
        }
1131
    }
1132
1133
    /**
1134
     * This deletes a document by changing visibility to 2, renaming it to filename_DELETED_#id
1135
     * Files/folders that are inside a deleted folder get visibility 2.
1136
     *
1137
     * @param array  $_course
1138
     * @param string $path          Path stored in the database
1139
     * @param string $base_work_dir Path to the "/document" folder of this course. Will be built if not provided.
1140
     * @param int    $sessionId     The ID of the session, if any
1141
     * @param int    $documentId    The document id, if available
1142
     * @param int    $groupId       iid
1143
     *
1144
     * @return bool true/false
1145
     *
1146
     * @todo now only files/folders in a folder get visibility 2, we should rename them too.
1147
     * @todo We should be able to get rid of this later when using only documentId (check further usage)
1148
     */
1149
    public static function delete_document(
1150
        $_course,
1151
        $path = null,
1152
        $base_work_dir = null,
1153
        $sessionId = null,
1154
        $documentId = null,
1155
        $groupId = 0
1156
    ) {
1157
        $TABLE_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
1158
1159
        $documentId = (int) $documentId;
1160
        $groupId = (int) $groupId;
1161
        if (empty($groupId)) {
1162
            $groupId = api_get_group_id();
1163
        }
1164
1165
        $sessionId = (int) $sessionId;
1166
        if (empty($sessionId)) {
1167
            $sessionId = api_get_session_id();
1168
        }
1169
1170
        $course_id = $_course['real_id'];
1171
1172
        if (empty($course_id)) {
1173
            return false;
1174
        }
1175
1176
        if (empty($base_work_dir)) {
1177
            if (empty($_course['directory'])) {
1178
                return false;
1179
            }
1180
            $courseDir = $_course['directory'].'/document';
1181
            $sysCoursePath = api_get_path(SYS_COURSE_PATH);
1182
            $base_work_dir = $sysCoursePath.$courseDir;
1183
        }
1184
1185
        if (empty($documentId)) {
1186
            $documentId = self::get_document_id($_course, $path, $sessionId);
1187
            $docInfo = self::get_document_data_by_id(
1188
                $documentId,
1189
                $_course['code'],
1190
                false,
1191
                $sessionId
1192
            );
1193
            $path = $docInfo['path'];
1194
        } else {
1195
            $docInfo = self::get_document_data_by_id(
1196
                $documentId,
1197
                $_course['code'],
1198
                false,
1199
                $sessionId
1200
            );
1201
            if (empty($docInfo)) {
1202
                return false;
1203
            }
1204
            $path = $docInfo['path'];
1205
        }
1206
1207
        if (empty($path) || empty($docInfo) || empty($documentId)) {
1208
            return false;
1209
        }
1210
1211
        $itemInfo = api_get_item_property_info(
1212
            $_course['real_id'],
1213
            TOOL_DOCUMENT,
1214
            $documentId,
1215
            $sessionId,
1216
            $groupId
1217
        );
1218
1219
        if (empty($itemInfo)) {
1220
            return false;
1221
        }
1222
1223
        // File was already deleted.
1224
        if ($itemInfo['lastedit_type'] == 'DocumentDeleted' ||
1225
            $itemInfo['lastedit_type'] == 'delete' ||
1226
            $itemInfo['visibility'] == 2
1227
        ) {
1228
            return false;
1229
        }
1230
1231
        // Filtering by group.
1232
        if ($itemInfo['to_group_id'] != $groupId) {
1233
            return false;
1234
        }
1235
1236
        $document_exists_in_disk = file_exists($base_work_dir.$path);
1237
        $new_path = $path.'_DELETED_'.$documentId;
1238
1239
        $file_deleted_from_db = false;
1240
        $file_deleted_from_disk = false;
1241
        $file_renamed_from_disk = false;
1242
1243
        if ($documentId) {
1244
            // Deleting doc from the DB.
1245
            self::deleteDocumentFromDb($documentId, $_course, $sessionId);
1246
            // Checking
1247
            // $file_exists_in_db = self::get_document_data_by_id($documentId, $_course['code']);
1248
            $file_deleted_from_db = true;
1249
        }
1250
1251
        // Looking for children.
1252
        if ($docInfo['filetype'] == 'folder') {
1253
            $cleanPath = Database::escape_string($path);
1254
1255
            // Deleted files inside this folder.
1256
            $sql = "SELECT id FROM $TABLE_DOCUMENT
1257
                    WHERE
1258
                        c_id = $course_id AND
1259
                        session_id = $sessionId AND
1260
                        path LIKE BINARY '".$cleanPath."/%'";
1261
1262
            // Get all id's of documents that are deleted.
1263
            $result = Database::query($sql);
1264
1265
            if ($result && Database::num_rows($result) != 0) {
1266
                // Recursive delete.
1267
                while ($row = Database::fetch_array($result)) {
1268
                    self::delete_document(
1269
                        $_course,
1270
                        null,
1271
                        $base_work_dir,
1272
                        $sessionId,
1273
                        $row['id'],
1274
                        $groupId
1275
                    );
1276
                }
1277
            }
1278
        }
1279
1280
        if ($document_exists_in_disk) {
1281
            if (api_get_setting('permanently_remove_deleted_files') === 'true') {
1282
                // Delete documents, do it like this so metadata gets deleted too
1283
                my_delete($base_work_dir.$path);
1284
                // Hard delete.
1285
                self::deleteDocumentFromDb($documentId, $_course, $sessionId, true);
1286
                $file_deleted_from_disk = true;
1287
            } else {
1288
                // Set visibility to 2 and rename file/folder to xxx_DELETED_#id (soft delete)
1289
                if (is_file($base_work_dir.$path) || is_dir($base_work_dir.$path)) {
1290
                    if (rename($base_work_dir.$path, $base_work_dir.$new_path)) {
1291
                        $new_path = Database::escape_string($new_path);
1292
1293
                        $sql = "UPDATE $TABLE_DOCUMENT
1294
                                SET path = '".$new_path."'
1295
                                WHERE
1296
                                    c_id = $course_id AND
1297
                                    session_id = $sessionId AND
1298
                                    id = ".$documentId;
1299
                        Database::query($sql);
1300
1301
                        // Soft delete.
1302
                        self::deleteDocumentFromDb($documentId, $_course, $sessionId);
1303
1304
                        // Change path of sub folders and documents in database.
1305
                        $old_item_path = $docInfo['path'];
1306
                        $new_item_path = $new_path.substr($old_item_path, strlen($path));
1307
                        $new_item_path = Database::escape_string($new_item_path);
1308
1309
                        $sql = "UPDATE $TABLE_DOCUMENT
1310
                                SET path = '".$new_item_path."'
1311
                                WHERE
1312
                                    c_id = $course_id AND
1313
                                    session_id = $sessionId AND
1314
                                    id = ".$documentId;
1315
                        Database::query($sql);
1316
1317
                        $file_renamed_from_disk = true;
1318
                    } else {
1319
                        // Couldn't rename - file permissions problem?
1320
                        error_log(
1321
                            __FILE__.' '.__LINE__.': Error renaming '.$base_work_dir.$path.' to '.$base_work_dir.$new_path.'. This is probably due to file permissions',
1322
                            0
1323
                        );
1324
                    }
1325
                }
1326
            }
1327
        }
1328
        // Checking inconsistency
1329
        //error_log('Doc status: (1 del db :'.($file_deleted_from_db?'yes':'no').') - (2 del disk: '.($file_deleted_from_disk?'yes':'no').') - (3 ren disk: '.($file_renamed_from_disk?'yes':'no').')');
1330
        if ($file_deleted_from_db && $file_deleted_from_disk ||
1331
            $file_deleted_from_db && $file_renamed_from_disk
1332
        ) {
1333
            return true;
1334
        } else {
1335
            //Something went wrong
1336
            //The file or directory isn't there anymore (on the filesystem)
1337
            // This means it has been removed externally. To prevent a
1338
            // blocking error from happening, we drop the related items from the
1339
            // item_property and the document table.
1340
            error_log(
1341
                __FILE__.' '.__LINE__.': System inconsistency detected. The file or directory '.$base_work_dir.$path.' seems to have been removed from the filesystem independently from the web platform. To restore consistency, the elements using the same path will be removed from the database',
1342
                0
1343
            );
1344
1345
            return false;
1346
        }
1347
    }
1348
1349
    /**
1350
     * Removes documents from search engine database.
1351
     *
1352
     * @param string $course_id   Course code
1353
     * @param int    $document_id Document id to delete
1354
     */
1355
    public static function delete_document_from_search_engine($course_id, $document_id)
1356
    {
1357
        // remove from search engine if enabled
1358
        if (api_get_setting('search_enabled') === 'true') {
1359
            $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
1360
            $sql = 'SELECT * FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s LIMIT 1';
1361
            $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_DOCUMENT, $document_id);
1362
            $res = Database::query($sql);
1363
            if (Database::num_rows($res) > 0) {
1364
                $row2 = Database::fetch_array($res);
1365
                $di = new ChamiloIndexer();
1366
                $di->remove_document($row2['search_did']);
1367
            }
1368
            $sql = 'DELETE FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s LIMIT 1';
1369
            $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_DOCUMENT, $document_id);
1370
            Database::query($sql);
1371
1372
            // remove terms from db
1373
            require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
1374
            delete_all_values_for_item($course_id, TOOL_DOCUMENT, $document_id);
1375
        }
1376
    }
1377
1378
    /**
1379
     * Gets the id of a document with a given path.
1380
     *
1381
     * @param array  $courseInfo
1382
     * @param string $path
1383
     * @param int    $sessionId
1384
     *
1385
     * @return int id of document / false if no doc found
1386
     */
1387
    public static function get_document_id($courseInfo, $path, $sessionId = null, $forceFileTypeFolder = false)
1388
    {
1389
        $table = Database::get_course_table(TABLE_DOCUMENT);
1390
        $courseId = $courseInfo['real_id'];
1391
1392
        if (!isset($sessionId)) {
1393
            $sessionId = api_get_session_id();
1394
        } else {
1395
            $sessionId = intval($sessionId);
1396
        }
1397
1398
        // Special case: cache doc ID for 3600s if "/" has already been queried
1399
        // recently.
1400
        // This is a hack. Better solutions: use apcu (not always available)
1401
        // and even better: reduce the amount of calls by not processing
1402
        // documents that will not be shown (e.g. on other pages of a table)
1403
        $isSlash = ($path === '/');
1404
        if ($isSlash) {
1405
            $cSSlashString = 'docIdSlash2C'.$courseId.'S'.$sessionId;
1406
            $storedSlashId = Session::read($cSSlashString);
1407
            $now = time();
1408
            if (is_array($storedSlashId)) {
1409
                if ($storedSlashId['t'] >= $now - 3600) {
1410
                    return $storedSlashId['id'];
1411
                }
1412
            }
1413
        }
1414
1415
        $path = Database::escape_string($path);
1416
        if (!empty($courseId) && !empty($path)) {
1417
            $folderCondition = '';
1418
            if ($forceFileTypeFolder) {
1419
                $folderCondition = ' AND filetype = "folder" ';
1420
            }
1421
            $sql = "SELECT id FROM $table
1422
                    WHERE
1423
                        c_id = $courseId AND
1424
                        path LIKE BINARY '$path' AND
1425
                        session_id = $sessionId
1426
                        $folderCondition
1427
                    LIMIT 1";
1428
1429
            $result = Database::query($sql);
1430
            if (Database::num_rows($result)) {
1431
                $row = Database::fetch_array($result);
1432
                if ($isSlash) {
1433
                    Session::write($cSSlashString, ['t' => $now, 'id' => intval($row['id'])]);
1434
                }
1435
1436
                return intval($row['id']);
1437
            }
1438
            if ($isSlash) {
1439
                // Even if there is no "/" document/folder, store a result to avoid querying the database again
1440
                Session::write($cSSlashString, ['t' => $now, 'id' => false]);
1441
            }
1442
        }
1443
1444
        return false;
1445
    }
1446
1447
    /**
1448
     * Gets the document data with a given id.
1449
     *
1450
     * @param int    $id            Document Id (id field in c_document table)
1451
     * @param string $course_code   Course code
1452
     * @param bool   $load_parents  load folder parents
1453
     * @param int    $session_id    The session ID,
1454
     *                              0 if requires context *out of* session, and null to use global context
1455
     * @param bool   $ignoreDeleted
1456
     *
1457
     * @return array document content
1458
     */
1459
    public static function get_document_data_by_id(
1460
        $id,
1461
        $course_code,
1462
        $load_parents = false,
1463
        $session_id = null,
1464
        $ignoreDeleted = false
1465
    ) {
1466
        $course_info = api_get_course_info($course_code);
1467
        $course_id = $course_info['real_id'];
1468
1469
        if (empty($course_info)) {
1470
            return false;
1471
        }
1472
1473
        $session_id = empty($session_id) ? api_get_session_id() : (int) $session_id;
1474
        $groupId = api_get_group_id();
1475
        $www = api_get_path(WEB_COURSE_PATH).$course_info['path'].'/document';
1476
        $TABLE_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
1477
        $id = (int) $id;
1478
        $sessionCondition = api_get_session_condition($session_id, true, true);
1479
1480
        $sql = "SELECT * FROM $TABLE_DOCUMENT
1481
                WHERE c_id = $course_id $sessionCondition AND id = $id";
1482
1483
        if ($ignoreDeleted) {
1484
            $sql .= " AND path NOT LIKE '%_DELETED_%' ";
1485
        }
1486
1487
        $result = Database::query($sql);
1488
        $courseParam = '&cidReq='.$course_code.'&id='.$id.'&id_session='.$session_id.'&gidReq='.$groupId;
1489
        if ($result && Database::num_rows($result) == 1) {
1490
            $row = Database::fetch_array($result, 'ASSOC');
1491
            //@todo need to clarify the name of the URLs not nice right now
1492
            $url_path = urlencode($row['path']);
1493
            $path = str_replace('%2F', '/', $url_path);
1494
            $pathinfo = pathinfo($row['path']);
1495
            $row['url'] = api_get_path(WEB_CODE_PATH).'document/showinframes.php?id='.$id.$courseParam;
1496
            $row['document_url'] = api_get_path(WEB_CODE_PATH).'document/document.php?id='.$id.$courseParam;
1497
            $row['absolute_path'] = api_get_path(SYS_COURSE_PATH).$course_info['path'].'/document'.$row['path'];
1498
            $row['absolute_path_from_document'] = '/document'.$row['path'];
1499
            $row['absolute_parent_path'] = api_get_path(SYS_COURSE_PATH).$course_info['path'].'/document'.$pathinfo['dirname'].'/';
1500
            $row['direct_url'] = $www.$path;
1501
            $row['basename'] = basename($row['path']);
1502
            if (dirname($row['path']) === '.') {
1503
                $row['parent_id'] = '0';
1504
            } else {
1505
                $row['parent_id'] = self::get_document_id($course_info, dirname($row['path']), $session_id, true);
1506
                if (empty($row['parent_id'])) {
1507
                    // Try one more with session id = 0
1508
                    $row['parent_id'] = self::get_document_id($course_info, dirname($row['path']), 0, true);
1509
                }
1510
            }
1511
            $parents = [];
1512
1513
            //Use to generate parents (needed for the breadcrumb)
1514
            //@todo sorry but this for is here because there's not a parent_id in the document table so we parsed the path!!
1515
            if ($load_parents) {
1516
                $dir_array = explode('/', $row['path']);
1517
                $dir_array = array_filter($dir_array);
1518
                $array_len = count($dir_array) + 1;
1519
                $real_dir = '';
1520
1521
                for ($i = 1; $i < $array_len; $i++) {
1522
                    $real_dir .= '/'.(isset($dir_array[$i]) ? $dir_array[$i] : '');
1523
                    $parent_id = self::get_document_id($course_info, $real_dir);
1524
                    if ($session_id != 0 && empty($parent_id)) {
1525
                        $parent_id = self::get_document_id($course_info, $real_dir, 0);
1526
                    }
1527
                    if (!empty($parent_id)) {
1528
                        $sub_document_data = self::get_document_data_by_id(
1529
                            $parent_id,
1530
                            $course_code,
1531
                            false,
1532
                            $session_id
1533
                        );
1534
                        if ($session_id != 0 and !$sub_document_data) {
1535
                            $sub_document_data = self::get_document_data_by_id(
1536
                                $parent_id,
1537
                                $course_code,
1538
                                false,
1539
                                0
1540
                            );
1541
                        }
1542
                        //@todo add visibility here
1543
                        $parents[] = $sub_document_data;
1544
                    }
1545
                }
1546
            }
1547
            $row['parents'] = $parents;
1548
1549
            return $row;
1550
        }
1551
1552
        return false;
1553
    }
1554
1555
    /**
1556
     * Allow to set a specific document as a new template for CKeditor
1557
     * for a particular user in a particular course.
1558
     *
1559
     * @param string $title
1560
     * @param string $description
1561
     * @param int    $document_id_for_template the document id
1562
     * @param string $course_code
1563
     * @param int    $user_id
1564
     * @param string $image
1565
     *
1566
     * @return bool
1567
     */
1568
    public static function set_document_as_template(
1569
        $title,
1570
        $description,
1571
        $document_id_for_template,
1572
        $course_code,
1573
        $user_id,
1574
        $image
1575
    ) {
1576
        // Database table definition
1577
        $table_template = Database::get_main_table(TABLE_MAIN_TEMPLATES);
1578
        $params = [
1579
            'title' => $title,
1580
            'description' => $description,
1581
            'course_code' => $course_code,
1582
            'user_id' => $user_id,
1583
            'ref_doc' => $document_id_for_template,
1584
            'image' => $image,
1585
        ];
1586
        Database::insert($table_template, $params);
1587
1588
        return true;
1589
    }
1590
1591
    /**
1592
     * Unset a document as template.
1593
     *
1594
     * @param int    $document_id
1595
     * @param string $course_code
1596
     * @param int    $user_id
1597
     */
1598
    public static function unset_document_as_template(
1599
        $document_id,
1600
        $course_code,
1601
        $user_id
1602
    ) {
1603
        $table_template = Database::get_main_table(TABLE_MAIN_TEMPLATES);
1604
        $course_code = Database::escape_string($course_code);
1605
        $user_id = intval($user_id);
1606
        $document_id = intval($document_id);
1607
        $sql = 'SELECT id FROM '.$table_template.'
1608
                WHERE
1609
                    course_code="'.$course_code.'" AND
1610
                    user_id="'.$user_id.'" AND
1611
                    ref_doc="'.$document_id.'"';
1612
        $result = Database::query($sql);
1613
        $template_id = Database::result($result, 0, 0);
1614
1615
        my_delete(api_get_path(SYS_CODE_PATH).'upload/template_thumbnails/'.$template_id.'.jpg');
1616
1617
        $sql = 'DELETE FROM '.$table_template.'
1618
                WHERE
1619
                    course_code="'.$course_code.'" AND
1620
                    user_id="'.$user_id.'" AND
1621
                    ref_doc="'.$document_id.'"';
1622
1623
        Database::query($sql);
1624
    }
1625
1626
    /**
1627
     * Return true if the documentpath have visibility=1 as
1628
     * item_property (you should use the is_visible_by_id).
1629
     *
1630
     * @param string $doc_path the relative complete path of the document
1631
     * @param array  $course   the _course array info of the document's course
1632
     * @param int
1633
     * @param string
1634
     *
1635
     * @return bool
1636
     */
1637
    public static function is_visible(
1638
        $doc_path,
1639
        $course,
1640
        $session_id = 0,
1641
        $file_type = 'file'
1642
    ) {
1643
        $docTable = Database::get_course_table(TABLE_DOCUMENT);
1644
        $propTable = Database::get_course_table(TABLE_ITEM_PROPERTY);
1645
1646
        $userId = api_get_user_id();
1647
        $course_id = $course['real_id'];
1648
        // note the extra / at the end of doc_path to match every path in
1649
        // the document table that is part of the document path
1650
        $session_id = (int) $session_id;
1651
1652
        $drhAccessContent = api_drh_can_access_all_session_content() &&
1653
            $session_id &&
1654
            SessionManager::isSessionFollowedByDrh($session_id, $userId);
1655
1656
        $hasAccess = api_is_allowed_in_course() || api_is_platform_admin() || $drhAccessContent;
1657
1658
        if (false === $hasAccess) {
1659
            return false;
1660
        }
1661
1662
        $condition = "AND d.session_id IN  ('$session_id', '0') ";
1663
        // The " d.filetype='file' " let the user see a file even if the folder is hidden see #2198
1664
1665
        /*
1666
          When using hotpotatoes files, a new html files are generated
1667
          in the hotpotatoes folder to display the test.
1668
          The genuine html file is copied to math4.htm(user_id).t.html
1669
          Images files are not copied, and keep same name.
1670
          To check the html file visibility, we don't have to check file math4.htm(user_id).t.html but file math4.htm
1671
          In this case, we have to remove (user_id).t.html to check the visibility of the file
1672
          For images, we just check the path of the image file.
1673
1674
          Exemple of hotpotatoes folder :
1675
          A.jpg
1676
          maths4-consigne.jpg
1677
          maths4.htm
1678
          maths4.htm1.t.html
1679
          maths4.htm52.t.html
1680
          maths4.htm654.t.html
1681
          omega.jpg
1682
          theta.jpg
1683
         */
1684
1685
        if (strpos($doc_path, 'HotPotatoes_files') && preg_match("/\.t\.html$/", $doc_path)) {
1686
            $doc_path = substr($doc_path, 0, strlen($doc_path) - 7 - strlen($userId));
1687
        }
1688
1689
        if (!in_array($file_type, ['file', 'folder'])) {
1690
            $file_type = 'file';
1691
        }
1692
        $doc_path = Database::escape_string($doc_path).'/';
1693
1694
        $sql = "SELECT visibility, ip.session_id
1695
                FROM $docTable d
1696
                INNER JOIN $propTable ip
1697
                ON (d.id = ip.ref AND d.c_id = ip.c_id)
1698
        		WHERE
1699
        		    d.c_id  = $course_id AND
1700
        		    ip.c_id = $course_id AND
1701
        		    ip.tool = '".TOOL_DOCUMENT."' $condition AND
1702
        			filetype = '$file_type' AND
1703
        			locate(concat(path,'/'), '$doc_path')=1
1704
                ";
1705
1706
        $result = Database::query($sql);
1707
        $isVisible = false;
1708
        $numRows = (int) Database::num_rows($result);
1709
1710
        if ($numRows) {
1711
            if (1 === $numRows) {
1712
                $row = Database::fetch_array($result, 'ASSOC');
1713
                if ($row['visibility'] == 1) {
1714
                    $isVisible = true;
1715
                }
1716
            } else {
1717
                $sessionVisibility = null;
1718
                $courseVisibility = null;
1719
                while ($row = Database::fetch_array($result, 'ASSOC')) {
1720
                    $checkSessionId = (int) $row['session_id'];
1721
                    if (empty($checkSessionId)) {
1722
                        $courseVisibility = 1 === (int) $row['visibility'];
1723
                    } else {
1724
                        if ($session_id === $checkSessionId) {
1725
                            $sessionVisibility = 1 === (int) $row['visibility'];
1726
                        }
1727
                    }
1728
                }
1729
1730
                if (empty($session_id) || (!empty($session_id) && null === $sessionVisibility)) {
1731
                    if ($courseVisibility) {
1732
                        $isVisible = true;
1733
                    }
1734
                } else {
1735
                    if ($sessionVisibility) {
1736
                        $isVisible = true;
1737
                    }
1738
                }
1739
            }
1740
        }
1741
1742
        /* improved protection of documents viewable directly through the url:
1743
            incorporates the same protections of the course at the url of
1744
            documents:
1745
            access allowed for the whole world Open, access allowed for
1746
            users registered on the platform Private access, document accessible
1747
            only to course members (see the Users list), Completely closed;
1748
            the document is only accessible to the course admin and
1749
            teaching assistants.*/
1750
        //return $_SESSION ['is_allowed_in_course'] || api_is_platform_admin();
1751
        return $isVisible;
1752
    }
1753
1754
    /**
1755
     * Return true if user can see a file.
1756
     *
1757
     * @param   int     document id
1758
     * @param   array   course info
1759
     * @param   int
1760
     * @param   int
1761
     * @param bool
1762
     *
1763
     * @return bool
1764
     */
1765
    public static function is_visible_by_id(
1766
        $doc_id,
1767
        $course_info,
1768
        $session_id,
1769
        $user_id,
1770
        $admins_can_see_everything = true,
1771
        $userIsSubscribed = null
1772
    ) {
1773
        $user_in_course = false;
1774
1775
        //1. Checking the course array
1776
        if (empty($course_info)) {
1777
            $course_info = api_get_course_info();
1778
            if (empty($course_info)) {
1779
                return false;
1780
            }
1781
        }
1782
1783
        $doc_id = (int) $doc_id;
1784
        $session_id = (int) $session_id;
1785
        // 2. Course and Session visibility are handle in local.inc.php/global.inc.php
1786
        // 3. Checking if user exist in course/session
1787
        if ($session_id == 0) {
1788
            if (is_null($userIsSubscribed)) {
1789
                $userIsSubscribed = CourseManager::is_user_subscribed_in_course(
1790
                    $user_id,
1791
                    $course_info['code']
1792
                );
1793
            }
1794
1795
            if ($userIsSubscribed === true || api_is_platform_admin()) {
1796
                $user_in_course = true;
1797
            }
1798
1799
            // Check if course is open then we can consider that the student is registered to the course
1800
            if (isset($course_info) &&
1801
                in_array(
1802
                    $course_info['visibility'],
1803
                    [COURSE_VISIBILITY_OPEN_PLATFORM, COURSE_VISIBILITY_OPEN_WORLD]
1804
                )
1805
            ) {
1806
                $user_in_course = true;
1807
            }
1808
        } else {
1809
            $user_status = SessionManager::get_user_status_in_course_session(
1810
                $user_id,
1811
                $course_info['real_id'],
1812
                $session_id
1813
            );
1814
1815
            if (in_array($user_status, ['0', '2', '6'])) {
1816
                //is true if is an student, course session teacher or coach
1817
                $user_in_course = true;
1818
            }
1819
1820
            if (api_is_platform_admin()) {
1821
                $user_in_course = true;
1822
            }
1823
        }
1824
1825
        // 4. Checking document visibility (i'm repeating the code in order to be more clear when reading ) - jm
1826
        if ($user_in_course) {
1827
            // 4.1 Checking document visibility for a Course
1828
            if ($session_id == 0) {
1829
                $item_info = api_get_item_property_info(
1830
                    $course_info['real_id'],
1831
                    'document',
1832
                    $doc_id,
1833
                    0
1834
                );
1835
1836
                if (isset($item_info['visibility'])) {
1837
                    // True for admins if document exists
1838
                    if ($admins_can_see_everything && api_is_platform_admin()) {
1839
                        return true;
1840
                    }
1841
                    if ($item_info['visibility'] == 1) {
1842
                        return true;
1843
                    }
1844
                }
1845
            } else {
1846
                // 4.2 Checking document visibility for a Course in a Session
1847
                $item_info = api_get_item_property_info(
1848
                    $course_info['real_id'],
1849
                    'document',
1850
                    $doc_id,
1851
                    0
1852
                );
1853
1854
                $item_info_in_session = api_get_item_property_info(
1855
                    $course_info['real_id'],
1856
                    'document',
1857
                    $doc_id,
1858
                    $session_id
1859
                );
1860
1861
                // True for admins if document exists
1862
                if (isset($item_info['visibility'])) {
1863
                    if ($admins_can_see_everything && api_is_platform_admin()) {
1864
                        return true;
1865
                    }
1866
                }
1867
1868
                if (isset($item_info_in_session['visibility'])) {
1869
                    if ($item_info_in_session['visibility'] == 1) {
1870
                        return true;
1871
                    }
1872
                } else {
1873
                    if ($item_info['visibility'] == 1) {
1874
                        return true;
1875
                    }
1876
                }
1877
            }
1878
        } elseif ($admins_can_see_everything && api_is_platform_admin()) {
1879
            return true;
1880
        }
1881
1882
        return false;
1883
    }
1884
1885
    /**
1886
     * Allow attach a certificate to a course.
1887
     *
1888
     * @todo move to certificate.lib.php
1889
     *
1890
     * @param string $course_id
1891
     * @param int    $document_id
1892
     * @param int    $session_id
1893
     */
1894
    public static function attach_gradebook_certificate($course_id, $document_id, $session_id = 0)
1895
    {
1896
        $tbl_category = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
1897
        $session_id = intval($session_id);
1898
        if (empty($session_id)) {
1899
            $session_id = api_get_session_id();
1900
        }
1901
1902
        if (empty($session_id)) {
1903
            $sql_session = 'AND (session_id = 0 OR isnull(session_id)) ';
1904
        } elseif ($session_id > 0) {
1905
            $sql_session = 'AND session_id='.intval($session_id);
1906
        } else {
1907
            $sql_session = '';
1908
        }
1909
        $sql = 'UPDATE '.$tbl_category.' SET document_id="'.intval($document_id).'"
1910
                WHERE course_code="'.Database::escape_string($course_id).'" '.$sql_session;
1911
        Database::query($sql);
1912
    }
1913
1914
    /**
1915
     * get the document id of default certificate.
1916
     *
1917
     * @todo move to certificate.lib.php
1918
     *
1919
     * @param string $course_id
1920
     * @param int    $session_id
1921
     *
1922
     * @return int The default certificate id
1923
     */
1924
    public static function get_default_certificate_id($course_id, $session_id = 0)
1925
    {
1926
        $tbl_category = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
1927
        $session_id = (int) $session_id;
1928
        if (empty($session_id)) {
1929
            $session_id = api_get_session_id();
1930
        }
1931
1932
        if (empty($session_id)) {
1933
            $sql_session = 'AND (session_id = 0 OR isnull(session_id)) ';
1934
        } elseif ($session_id > 0) {
1935
            $sql_session = 'AND session_id='.$session_id;
1936
        } else {
1937
            $sql_session = '';
1938
        }
1939
        $sql = 'SELECT document_id FROM '.$tbl_category.'
1940
                WHERE course_code="'.Database::escape_string($course_id).'" '.$sql_session;
1941
1942
        $rs = Database::query($sql);
1943
        $num = Database::num_rows($rs);
1944
        if ($num == 0) {
1945
            return null;
1946
        }
1947
        $row = Database::fetch_array($rs);
1948
1949
        return $row['document_id'];
1950
    }
1951
1952
    /**
1953
     * Allow replace user info in file html.
1954
     *
1955
     * @param int    $user_id
1956
     * @param string $course_code
1957
     * @param int    $sessionId
1958
     * @param bool   $is_preview
1959
     *
1960
     * @return array
1961
     */
1962
    public static function replace_user_info_into_html(
1963
        $user_id,
1964
        $course_code,
1965
        $sessionId,
1966
        $is_preview = false
1967
    ) {
1968
        $user_id = (int) $user_id;
1969
        $sessionId = (int) $sessionId;
1970
        $course_info = api_get_course_info($course_code);
1971
        $tbl_document = Database::get_course_table(TABLE_DOCUMENT);
1972
        $course_id = $course_info['real_id'];
1973
1974
        $document_id = self::get_default_certificate_id(
1975
            $course_code,
1976
            $sessionId
1977
        );
1978
1979
        $my_content_html = null;
1980
        if ($document_id) {
1981
            $sql = "SELECT path FROM $tbl_document
1982
                    WHERE c_id = $course_id AND id = $document_id";
1983
            $rs = Database::query($sql);
1984
            $new_content = '';
1985
            $all_user_info = [];
1986
            if (Database::num_rows($rs)) {
1987
                $row = Database::fetch_array($rs);
1988
                $filepath = api_get_path(SYS_COURSE_PATH).$course_info['path'].'/document'.$row['path'];
1989
                if (is_file($filepath)) {
1990
                    $my_content_html = file_get_contents($filepath);
1991
                }
1992
                $all_user_info = self::get_all_info_to_certificate(
1993
                    $user_id,
1994
                    $course_code,
1995
                    $sessionId,
1996
                    $is_preview
1997
                );
1998
1999
                $info_to_be_replaced_in_content_html = $all_user_info[0];
2000
                $info_to_replace_in_content_html = $all_user_info[1];
2001
                $new_content = str_replace(
2002
                    $info_to_be_replaced_in_content_html,
2003
                    $info_to_replace_in_content_html,
2004
                    $my_content_html
2005
                );
2006
            }
2007
2008
            return [
2009
                'content' => $new_content,
2010
                'variables' => $all_user_info,
2011
            ];
2012
        }
2013
2014
        return [];
2015
    }
2016
2017
    /**
2018
     * Return all content to replace and all content to be replace.
2019
     *
2020
     * @param int    $user_id
2021
     * @param string $courseCode
2022
     * @param bool   $is_preview
2023
     *
2024
     * @return array
2025
     */
2026
    public static function get_all_info_to_certificate($user_id, $courseCode, $sessionId, $is_preview = false)
2027
    {
2028
        $info_list = [];
2029
        $user_id = (int) $user_id;
2030
        $course_info = api_get_course_info($courseCode);
2031
        $sessionId = (int) $sessionId;
2032
2033
        // Portal info
2034
        $organization_name = api_get_setting('Institution');
2035
        $portal_name = api_get_setting('siteName');
2036
2037
        // Extra user data information
2038
        $extra_user_info_data = UserManager::get_extra_user_data(
2039
            $user_id,
2040
            false,
2041
            false,
2042
            false,
2043
            true
2044
        );
2045
2046
        // get extra fields
2047
        $extraField = new ExtraField('user');
2048
        $extraFields = $extraField->get_all(['filter = ? AND visible_to_self = ?' => [1, 1]]);
2049
2050
        // Student information
2051
        $user_info = api_get_user_info($user_id);
2052
        $first_name = $user_info['firstname'];
2053
        $last_name = $user_info['lastname'];
2054
        $username = $user_info['username'];
2055
        $user_picture = UserManager::getUserPicture($user_id, USER_IMAGE_SIZE_ORIGINAL);
2056
        $official_code = $user_info['official_code'];
2057
2058
        // Teacher information
2059
        $teacher_first_name = '';
2060
        $teacher_last_name = '';
2061
        $info_teacher_id = UserManager::get_user_id_of_course_admin_or_session_admin($course_info);
2062
2063
        if ($info_teacher_id) {
2064
            [
2065
                'firstname' => $teacher_first_name,
2066
                'lastname' => $teacher_last_name,
2067
            ] = api_get_user_info($info_teacher_id);
2068
        }
2069
2070
        // info gradebook certificate
2071
        $info_grade_certificate = UserManager::get_info_gradebook_certificate($courseCode, $sessionId, $user_id);
2072
        $date_long_certificate = '';
2073
        $date_certificate = '';
2074
        $date_short_no_time = '';
2075
        $url = '';
2076
        if ($info_grade_certificate) {
2077
            $date_certificate = $info_grade_certificate['created_at'];
2078
            $url = api_get_path(WEB_PATH).'certificates/index.php?id='.$info_grade_certificate['id'];
2079
        }
2080
        $date_no_time = api_convert_and_format_date(api_get_utc_datetime(), DATE_FORMAT_LONG_NO_DAY);
2081
        $date_short_no_time = api_convert_and_format_date(api_get_utc_datetime(), DATE_FORMAT_NUMBER);
2082
        if (!empty($date_certificate)) {
2083
            $date_long_certificate = api_convert_and_format_date($date_certificate);
2084
            $date_no_time = api_convert_and_format_date($date_certificate, DATE_FORMAT_LONG_NO_DAY);
2085
            $date_short_no_time = api_convert_and_format_date($date_certificate, DATE_FORMAT_NUMBER);
2086
        }
2087
2088
        if ($is_preview) {
2089
            $date_long_certificate = api_convert_and_format_date(api_get_utc_datetime());
2090
            $date_no_time = api_convert_and_format_date(api_get_utc_datetime(), DATE_FORMAT_LONG_NO_DAY);
2091
            $date_short_no_time = api_convert_and_format_date(api_get_utc_datetime(), DATE_FORMAT_NUMBER);
2092
        }
2093
2094
        $externalStyleFile = api_get_path(SYS_CSS_PATH).'themes/'.api_get_visual_theme().'/certificate.css';
2095
        $externalStyle = '';
2096
        if (is_file($externalStyleFile)) {
2097
            $externalStyle = file_get_contents($externalStyleFile);
2098
        }
2099
        $timeInCourse = Tracking::get_time_spent_on_the_course($user_id, $course_info['real_id'], $sessionId);
2100
        $timeInCourse = api_time_to_hms($timeInCourse, ':', false, true);
2101
2102
        $timeInCourseInAllSessions = 0;
2103
        $sessions = SessionManager::get_session_by_course($course_info['real_id']);
2104
2105
        if (!empty($sessions)) {
2106
            foreach ($sessions as $session) {
2107
                $timeInCourseInAllSessions += Tracking::get_time_spent_on_the_course($user_id, $course_info['real_id'], $session['id']);
2108
            }
2109
        }
2110
        $timeInCourseInAllSessions = api_time_to_hms($timeInCourseInAllSessions, ':', false, true);
2111
2112
        $first = Tracking::get_first_connection_date_on_the_course($user_id, $course_info['real_id'], $sessionId, false);
2113
        $first = api_convert_and_format_date($first, DATE_FORMAT_NUMBER);
2114
2115
        $last = Tracking::get_last_connection_date_on_the_course($user_id, $course_info, $sessionId, false);
2116
        $last = api_convert_and_format_date($last, DATE_FORMAT_NUMBER);
2117
2118
        if ($first === $last) {
2119
            $startDateAndEndDate = get_lang('The').' '.$first;
2120
        } else {
2121
            $startDateAndEndDate = sprintf(
2122
                get_lang('FromDateXToDateY'),
2123
                $first,
2124
                $last
2125
            );
2126
        }
2127
        $courseDescription = new CourseDescription();
2128
        $description = $courseDescription->get_data_by_description_type(2, $course_info['real_id'], $sessionId);
2129
        $courseObjectives = '';
2130
        if ($description) {
2131
            $courseObjectives = $description['description_content'];
2132
        }
2133
2134
        // Replace content
2135
        $info_to_replace_in_content_html = [
2136
            $first_name,
2137
            $last_name,
2138
            $username,
2139
            $user_picture,
2140
            $organization_name,
2141
            $portal_name,
2142
            $teacher_first_name,
2143
            $teacher_last_name,
2144
            $official_code,
2145
            $date_long_certificate,
2146
            $date_no_time,
2147
            $date_short_no_time,
2148
            $courseCode,
2149
            $course_info['name'],
2150
            isset($info_grade_certificate['grade']) ? $info_grade_certificate['grade'] : '',
2151
            $url,
2152
            '<a href="'.$url.'" target="_blank">'.get_lang('CertificateOnlineLink').'</a>',
2153
            '((certificate_barcode))',
2154
            $externalStyle,
2155
            $timeInCourse,
2156
            $timeInCourseInAllSessions,
2157
            $startDateAndEndDate,
2158
            $courseObjectives,
2159
        ];
2160
2161
        $tags = [
2162
            '((user_firstname))',
2163
            '((user_lastname))',
2164
            '((user_username))',
2165
            '((user_picture))',
2166
            '((gradebook_institution))',
2167
            '((gradebook_sitename))',
2168
            '((teacher_firstname))',
2169
            '((teacher_lastname))',
2170
            '((official_code))',
2171
            '((date_certificate))',
2172
            '((date_certificate_no_time))',
2173
            '((date_simple_certificate))',
2174
            '((course_code))',
2175
            '((course_title))',
2176
            '((gradebook_grade))',
2177
            '((certificate_link))',
2178
            '((certificate_link_html))',
2179
            '((certificate_barcode))',
2180
            '((external_style))',
2181
            '((time_in_course))',
2182
            '((time_in_course_in_all_sessions))',
2183
            '((start_date_and_end_date))',
2184
            '((course_objectives))',
2185
        ];
2186
2187
        if (!empty($extraFields)) {
2188
            $efv = new ExtraFieldValue('user');
2189
2190
            foreach ($extraFields as $extraField) {
2191
                $valueExtra = $efv->get_values_by_handler_and_field_variable(
2192
                    $user_id,
2193
                    $extraField['variable'],
2194
                    true
2195
                );
2196
                $tags[] = '(('.strtolower($extraField['variable']).'))';
2197
                $info_to_replace_in_content_html[] = $valueExtra['value'];
2198
            }
2199
        }
2200
2201
        $info_list[] = $tags;
2202
        $info_list[] = $info_to_replace_in_content_html;
2203
2204
        return $info_list;
2205
    }
2206
2207
    /**
2208
     * Remove default certificate.
2209
     *
2210
     * @param string $course_id              The course code
2211
     * @param int    $default_certificate_id The document id of the default certificate
2212
     */
2213
    public static function remove_attach_certificate($course_id, $default_certificate_id)
2214
    {
2215
        if (empty($default_certificate_id)) {
2216
            return false;
2217
        }
2218
2219
        $default_certificate = self::get_default_certificate_id($course_id);
2220
        if ((int) $default_certificate == (int) $default_certificate_id) {
2221
            $tbl_category = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
2222
            $session_id = api_get_session_id();
2223
            if ($session_id == 0 || is_null($session_id)) {
2224
                $sql_session = 'AND (session_id='.intval($session_id).' OR isnull(session_id)) ';
2225
            } elseif ($session_id > 0) {
2226
                $sql_session = 'AND session_id='.intval($session_id);
2227
            } else {
2228
                $sql_session = '';
2229
            }
2230
2231
            $sql = 'UPDATE '.$tbl_category.' SET document_id = null
2232
                    WHERE
2233
                        course_code = "'.Database::escape_string($course_id).'" AND
2234
                        document_id="'.$default_certificate_id.'" '.$sql_session;
2235
            Database::query($sql);
2236
        }
2237
    }
2238
2239
    /**
2240
     * Create directory certificate.
2241
     *
2242
     * @param array $courseInfo
2243
     */
2244
    public static function create_directory_certificate_in_course($courseInfo)
2245
    {
2246
        if (!empty($courseInfo)) {
2247
            $to_group_id = 0;
2248
            $to_user_id = null;
2249
            $course_dir = $courseInfo['path']."/document/";
2250
            $sys_course_path = api_get_path(SYS_COURSE_PATH);
2251
            $base_work_dir = $sys_course_path.$course_dir;
2252
            $dir_name = '/certificates';
2253
            $post_dir_name = get_lang('CertificatesFiles');
2254
            $visibility_command = 'invisible';
2255
2256
            $id = self::get_document_id_of_directory_certificate();
2257
2258
            if (empty($id)) {
2259
                create_unexisting_directory(
2260
                    $courseInfo,
2261
                    api_get_user_id(),
2262
                    api_get_session_id(),
2263
                    $to_group_id,
2264
                    $to_user_id,
2265
                    $base_work_dir,
2266
                    $dir_name,
2267
                    $post_dir_name,
2268
                    null,
2269
                    false,
2270
                    false
2271
                );
2272
2273
                $id = self::get_document_id_of_directory_certificate();
2274
2275
                if (empty($id)) {
2276
                    $id = add_document(
2277
                        $courseInfo,
2278
                        $dir_name,
2279
                        'folder',
2280
                        0,
2281
                        $post_dir_name,
2282
                        null,
2283
                        0,
2284
                        true,
2285
                        $to_group_id,
2286
                        0,
2287
                        0,
2288
                        false
2289
                    );
2290
                }
2291
2292
                if (!empty($id)) {
2293
                    api_item_property_update(
2294
                        $courseInfo,
2295
                        TOOL_DOCUMENT,
2296
                        $id,
2297
                        $visibility_command,
2298
                        api_get_user_id()
2299
                    );
2300
                }
2301
            }
2302
        }
2303
    }
2304
2305
    /**
2306
     * Get the document id of the directory certificate.
2307
     *
2308
     * @return int The document id of the directory certificate
2309
     *
2310
     * @todo move to certificate.lib.php
2311
     */
2312
    public static function get_document_id_of_directory_certificate()
2313
    {
2314
        $tbl_document = Database::get_course_table(TABLE_DOCUMENT);
2315
        $course_id = api_get_course_int_id();
2316
        $sql = "SELECT id FROM $tbl_document
2317
                WHERE c_id = $course_id AND path='/certificates' ";
2318
        $rs = Database::query($sql);
2319
        $row = Database::fetch_array($rs);
2320
        if ($row) {
2321
            return $row['id'];
2322
        }
2323
2324
        return 0;
2325
    }
2326
2327
    /**
2328
     * Check if a directory given is for certificate.
2329
     *
2330
     * @todo move to certificate.lib.php
2331
     *
2332
     * @param string $dir path of directory
2333
     *
2334
     * @return bool true if is a certificate or false otherwise
2335
     */
2336
    public static function is_certificate_mode($dir)
2337
    {
2338
        // I'm in the certification module?
2339
        $is_certificate_mode = false;
2340
        $is_certificate_array = explode('/', $dir);
2341
        array_shift($is_certificate_array);
2342
        if (isset($is_certificate_array[0]) && $is_certificate_array[0] == 'certificates') {
2343
            $is_certificate_mode = true;
2344
        }
2345
2346
        return $is_certificate_mode || (isset($_GET['certificate']) && $_GET['certificate'] === 'true');
2347
    }
2348
2349
    /**
2350
     * Gets the list of included resources as a list of absolute or relative paths from a html file or string html
2351
     * This allows for a better SCORM export or replace urls inside content html from copy course
2352
     * The list will generally include pictures, flash objects, java applets, or any other
2353
     * stuff included in the source of the current item. The current item is expected
2354
     * to be an HTML file or string html. If it is not, then the function will return and empty list.
2355
     *
2356
     * @param    string  source html (content or path)
2357
     * @param    bool    is file or string html
2358
     * @param    string    type (one of the app tools) - optional (otherwise takes the current item's type)
2359
     * @param    int        level of recursivity we're in
2360
     *
2361
     * @return array List of file paths. An additional field containing 'local' or 'remote' helps determine
2362
     *               if the file should be copied into the zip or just linked
2363
     */
2364
    public static function get_resources_from_source_html(
2365
        $source_html,
2366
        $is_file = false,
2367
        $type = null,
2368
        $recursivity = 1
2369
    ) {
2370
        $max = 5;
2371
        $attributes = [];
2372
        $wanted_attributes = [
2373
            'src',
2374
            'url',
2375
            '@import',
2376
            'href',
2377
            'value',
2378
            'flashvars',
2379
            'poster',
2380
        ];
2381
        $explode_attributes = ['flashvars' => 'file'];
2382
        $abs_path = '';
2383
2384
        if ($recursivity > $max) {
2385
            return [];
2386
        }
2387
2388
        if (!isset($type)) {
2389
            $type = TOOL_DOCUMENT;
2390
        }
2391
2392
        if (!$is_file) {
2393
            $attributes = self::parse_HTML_attributes(
2394
                $source_html,
2395
                $wanted_attributes,
2396
                $explode_attributes
2397
            );
2398
        } else {
2399
            if (is_file($source_html)) {
2400
                $abs_path = $source_html;
2401
                //for now, read the whole file in one go (that's gonna be a problem when the file is too big)
2402
                $info = pathinfo($abs_path);
2403
                $ext = $info['extension'];
2404
                switch (strtolower($ext)) {
2405
                    case 'html':
2406
                    case 'htm':
2407
                    case 'shtml':
2408
                    case 'css':
2409
                        $file_content = file_get_contents($abs_path);
2410
                        // get an array of attributes from the HTML source
2411
                        $attributes = self::parse_HTML_attributes(
2412
                            $file_content,
2413
                            $wanted_attributes,
2414
                            $explode_attributes
2415
                        );
2416
                        break;
2417
                    default:
2418
                        break;
2419
                }
2420
            } else {
2421
                return false;
2422
            }
2423
        }
2424
2425
        $files_list = [];
2426
        switch ($type) {
2427
            case TOOL_DOCUMENT:
2428
            case TOOL_QUIZ:
2429
            case 'sco':
2430
                foreach ($wanted_attributes as $attr) {
2431
                    if (isset($attributes[$attr])) {
2432
                        //find which kind of path these are (local or remote)
2433
                        $sources = $attributes[$attr];
2434
                        foreach ($sources as $source) {
2435
                            //skip what is obviously not a resource
2436
                            if (strpos($source, '+this.')) {
2437
                                continue; //javascript code - will still work unaltered
2438
                            }
2439
                            if (strpos($source, '.') === false) {
2440
                                continue; //no dot, should not be an external file anyway
2441
                            }
2442
                            if (strpos($source, 'mailto:')) {
2443
                                continue; //mailto link
2444
                            }
2445
                            if (strpos($source, ';') && !strpos($source, '&amp;')) {
2446
                                continue; //avoid code - that should help
2447
                            }
2448
2449
                            if ($attr == 'value') {
2450
                                if (strpos($source, 'mp3file')) {
2451
                                    $files_list[] = [
2452
                                        substr($source, 0, strpos($source, '.swf') + 4),
2453
                                        'local',
2454
                                        'abs',
2455
                                    ];
2456
                                    $mp3file = substr($source, strpos($source, 'mp3file=') + 8);
2457
                                    if (substr($mp3file, 0, 1) == '/') {
2458
                                        $files_list[] = [$mp3file, 'local', 'abs'];
2459
                                    } else {
2460
                                        $files_list[] = [$mp3file, 'local', 'rel'];
2461
                                    }
2462
                                } elseif (strpos($source, 'flv=') === 0) {
2463
                                    $source = substr($source, 4);
2464
                                    if (strpos($source, '&') > 0) {
2465
                                        $source = substr($source, 0, strpos($source, '&'));
2466
                                    }
2467
                                    if (strpos($source, '://') > 0) {
2468
                                        if (strpos($source, api_get_path(WEB_PATH)) !== false) {
2469
                                            //we found the current portal url
2470
                                            $files_list[] = [$source, 'local', 'url'];
2471
                                        } else {
2472
                                            //we didn't find any trace of current portal
2473
                                            $files_list[] = [$source, 'remote', 'url'];
2474
                                        }
2475
                                    } else {
2476
                                        $files_list[] = [$source, 'local', 'abs'];
2477
                                    }
2478
                                    /* skipping anything else to avoid two entries
2479
                                    (while the others can have sub-files in their url, flv's can't)*/
2480
                                    continue;
2481
                                }
2482
                            }
2483
                            if (strpos($source, '://') > 0) {
2484
                                //cut at '?' in a URL with params
2485
                                if (strpos($source, '?') > 0) {
2486
                                    $second_part = substr($source, strpos($source, '?'));
2487
                                    if (strpos($second_part, '://') > 0) {
2488
                                        //if the second part of the url contains a url too, treat the second one before cutting
2489
                                        $pos1 = strpos($second_part, '=');
2490
                                        $pos2 = strpos($second_part, '&');
2491
                                        $second_part = substr($second_part, $pos1 + 1, $pos2 - ($pos1 + 1));
2492
                                        if (strpos($second_part, api_get_path(WEB_PATH)) !== false) {
2493
                                            //we found the current portal url
2494
                                            $files_list[] = [$second_part, 'local', 'url'];
2495
                                            $in_files_list[] = self::get_resources_from_source_html(
2496
                                                $second_part,
2497
                                                true,
2498
                                                TOOL_DOCUMENT,
2499
                                                $recursivity + 1
2500
                                            );
2501
                                            if (count($in_files_list) > 0) {
2502
                                                $files_list = array_merge($files_list, $in_files_list);
2503
                                            }
2504
                                        } else {
2505
                                            //we didn't find any trace of current portal
2506
                                            $files_list[] = [$second_part, 'remote', 'url'];
2507
                                        }
2508
                                    } elseif (strpos($second_part, '=') > 0) {
2509
                                        if (substr($second_part, 0, 1) === '/') {
2510
                                            //link starts with a /, making it absolute (relative to DocumentRoot)
2511
                                            $files_list[] = [$second_part, 'local', 'abs'];
2512
                                            $in_files_list[] = self::get_resources_from_source_html(
2513
                                                $second_part,
2514
                                                true,
2515
                                                TOOL_DOCUMENT,
2516
                                                $recursivity + 1
2517
                                            );
2518
                                            if (count($in_files_list) > 0) {
2519
                                                $files_list = array_merge($files_list, $in_files_list);
2520
                                            }
2521
                                        } elseif (strstr($second_part, '..') === 0) {
2522
                                            //link is relative but going back in the hierarchy
2523
                                            $files_list[] = [$second_part, 'local', 'rel'];
2524
                                            //$dir = api_get_path(SYS_CODE_PATH);//dirname($abs_path);
2525
                                            //$new_abs_path = realpath($dir.'/'.$second_part);
2526
                                            $dir = '';
2527
                                            if (!empty($abs_path)) {
2528
                                                $dir = dirname($abs_path).'/';
2529
                                            }
2530
                                            $new_abs_path = realpath($dir.$second_part);
2531
                                            $in_files_list[] = self::get_resources_from_source_html(
2532
                                                $new_abs_path,
2533
                                                true,
2534
                                                TOOL_DOCUMENT,
2535
                                                $recursivity + 1
2536
                                            );
2537
                                            if (count($in_files_list) > 0) {
2538
                                                $files_list = array_merge($files_list, $in_files_list);
2539
                                            }
2540
                                        } else {
2541
                                            //no starting '/', making it relative to current document's path
2542
                                            if (substr($second_part, 0, 2) == './') {
2543
                                                $second_part = substr($second_part, 2);
2544
                                            }
2545
                                            $files_list[] = [$second_part, 'local', 'rel'];
2546
                                            $dir = '';
2547
                                            if (!empty($abs_path)) {
2548
                                                $dir = dirname($abs_path).'/';
2549
                                            }
2550
                                            $new_abs_path = realpath($dir.$second_part);
2551
                                            $in_files_list[] = self::get_resources_from_source_html(
2552
                                                $new_abs_path,
2553
                                                true,
2554
                                                TOOL_DOCUMENT,
2555
                                                $recursivity + 1
2556
                                            );
2557
                                            if (count($in_files_list) > 0) {
2558
                                                $files_list = array_merge($files_list, $in_files_list);
2559
                                            }
2560
                                        }
2561
                                    }
2562
                                    //leave that second part behind now
2563
                                    $source = substr($source, 0, strpos($source, '?'));
2564
                                    if (strpos($source, '://') > 0) {
2565
                                        if (strpos($source, api_get_path(WEB_PATH)) !== false) {
2566
                                            //we found the current portal url
2567
                                            $files_list[] = [$source, 'local', 'url'];
2568
                                            $in_files_list[] = self::get_resources_from_source_html(
2569
                                                $source,
2570
                                                true,
2571
                                                TOOL_DOCUMENT,
2572
                                                $recursivity + 1
2573
                                            );
2574
                                            if (count($in_files_list) > 0) {
2575
                                                $files_list = array_merge($files_list, $in_files_list);
2576
                                            }
2577
                                        } else {
2578
                                            //we didn't find any trace of current portal
2579
                                            $files_list[] = [$source, 'remote', 'url'];
2580
                                        }
2581
                                    } else {
2582
                                        //no protocol found, make link local
2583
                                        if (substr($source, 0, 1) === '/') {
2584
                                            //link starts with a /, making it absolute (relative to DocumentRoot)
2585
                                            $files_list[] = [$source, 'local', 'abs'];
2586
                                            $in_files_list[] = self::get_resources_from_source_html(
2587
                                                $source,
2588
                                                true,
2589
                                                TOOL_DOCUMENT,
2590
                                                $recursivity + 1
2591
                                            );
2592
                                            if (count($in_files_list) > 0) {
2593
                                                $files_list = array_merge($files_list, $in_files_list);
2594
                                            }
2595
                                        } elseif (strstr($source, '..') === 0) {
2596
                                            //link is relative but going back in the hierarchy
2597
                                            $files_list[] = [$source, 'local', 'rel'];
2598
                                            $dir = '';
2599
                                            if (!empty($abs_path)) {
2600
                                                $dir = dirname($abs_path).'/';
2601
                                            }
2602
                                            $new_abs_path = realpath($dir.$source);
2603
                                            $in_files_list[] = self::get_resources_from_source_html(
2604
                                                $new_abs_path,
2605
                                                true,
2606
                                                TOOL_DOCUMENT,
2607
                                                $recursivity + 1
2608
                                            );
2609
                                            if (count($in_files_list) > 0) {
2610
                                                $files_list = array_merge($files_list, $in_files_list);
2611
                                            }
2612
                                        } else {
2613
                                            //no starting '/', making it relative to current document's path
2614
                                            if (substr($source, 0, 2) == './') {
2615
                                                $source = substr($source, 2);
2616
                                            }
2617
                                            $files_list[] = [$source, 'local', 'rel'];
2618
                                            $dir = '';
2619
                                            if (!empty($abs_path)) {
2620
                                                $dir = dirname($abs_path).'/';
2621
                                            }
2622
                                            $new_abs_path = realpath($dir.$source);
2623
                                            $in_files_list[] = self::get_resources_from_source_html(
2624
                                                $new_abs_path,
2625
                                                true,
2626
                                                TOOL_DOCUMENT,
2627
                                                $recursivity + 1
2628
                                            );
2629
                                            if (count($in_files_list) > 0) {
2630
                                                $files_list = array_merge($files_list, $in_files_list);
2631
                                            }
2632
                                        }
2633
                                    }
2634
                                }
2635
                                //found some protocol there
2636
                                if (strpos($source, api_get_path(WEB_PATH)) !== false) {
2637
                                    //we found the current portal url
2638
                                    $files_list[] = [$source, 'local', 'url'];
2639
                                    $in_files_list[] = self::get_resources_from_source_html(
2640
                                        $source,
2641
                                        true,
2642
                                        TOOL_DOCUMENT,
2643
                                        $recursivity + 1
2644
                                    );
2645
                                    if (count($in_files_list) > 0) {
2646
                                        $files_list = array_merge($files_list, $in_files_list);
2647
                                    }
2648
                                } else {
2649
                                    //we didn't find any trace of current portal
2650
                                    $files_list[] = [$source, 'remote', 'url'];
2651
                                }
2652
                            } else {
2653
                                //no protocol found, make link local
2654
                                if (substr($source, 0, 1) === '/') {
2655
                                    //link starts with a /, making it absolute (relative to DocumentRoot)
2656
                                    $files_list[] = [$source, 'local', 'abs'];
2657
                                    $in_files_list[] = self::get_resources_from_source_html(
2658
                                        $source,
2659
                                        true,
2660
                                        TOOL_DOCUMENT,
2661
                                        $recursivity + 1
2662
                                    );
2663
                                    if (count($in_files_list) > 0) {
2664
                                        $files_list = array_merge($files_list, $in_files_list);
2665
                                    }
2666
                                } elseif (strpos($source, '..') === 0) {
2667
                                    //link is relative but going back in the hierarchy
2668
                                    $files_list[] = [$source, 'local', 'rel'];
2669
                                    $dir = '';
2670
                                    if (!empty($abs_path)) {
2671
                                        $dir = dirname($abs_path).'/';
2672
                                    }
2673
                                    $new_abs_path = realpath($dir.$source);
2674
                                    $in_files_list[] = self::get_resources_from_source_html(
2675
                                        $new_abs_path,
2676
                                        true,
2677
                                        TOOL_DOCUMENT,
2678
                                        $recursivity + 1
2679
                                    );
2680
                                    if (count($in_files_list) > 0) {
2681
                                        $files_list = array_merge($files_list, $in_files_list);
2682
                                    }
2683
                                } else {
2684
                                    //no starting '/', making it relative to current document's path
2685
                                    if (substr($source, 0, 2) == './') {
2686
                                        $source = substr($source, 2);
2687
                                    }
2688
                                    $files_list[] = [$source, 'local', 'rel'];
2689
                                    $dir = '';
2690
                                    if (!empty($abs_path)) {
2691
                                        $dir = dirname($abs_path).'/';
2692
                                    }
2693
                                    $new_abs_path = realpath($dir.$source);
2694
                                    $in_files_list[] = self::get_resources_from_source_html(
2695
                                        $new_abs_path,
2696
                                        true,
2697
                                        TOOL_DOCUMENT,
2698
                                        $recursivity + 1
2699
                                    );
2700
                                    if (count($in_files_list) > 0) {
2701
                                        $files_list = array_merge($files_list, $in_files_list);
2702
                                    }
2703
                                }
2704
                            }
2705
                        }
2706
                    }
2707
                }
2708
                break;
2709
            default: //ignore
2710
                break;
2711
        }
2712
2713
        $checked_files_list = [];
2714
        $checked_array_list = [];
2715
2716
        if (count($files_list) > 0) {
2717
            foreach ($files_list as $idx => $file) {
2718
                if (!empty($file[0])) {
2719
                    if (!in_array($file[0], $checked_files_list)) {
2720
                        $checked_files_list[] = $files_list[$idx][0];
2721
                        $checked_array_list[] = $files_list[$idx];
2722
                    }
2723
                }
2724
            }
2725
        }
2726
2727
        return $checked_array_list;
2728
    }
2729
2730
    /**
2731
     * Parses the HTML attributes given as string.
2732
     *
2733
     * @param string HTML attribute string
2734
     * @param array List of attributes that we want to get back
2735
     * @param array
2736
     *
2737
     * @return array An associative array of attributes
2738
     *
2739
     * @author Based on a function from the HTML_Common2 PEAR module     *
2740
     */
2741
    public static function parse_HTML_attributes($attrString, $wanted = [], $explode_variables = [])
2742
    {
2743
        $attributes = [];
2744
        $regs = [];
2745
        $reduced = false;
2746
        if (count($wanted) > 0) {
2747
            $reduced = true;
2748
        }
2749
        try {
2750
            //Find all occurences of something that looks like a URL
2751
            // The structure of this regexp is:
2752
            // (find protocol) then
2753
            // (optionally find some kind of space 1 or more times) then
2754
            // find (either an equal sign or a bracket) followed by an optional space
2755
            // followed by some text without quotes (between quotes itself or not)
2756
            // then possible closing brackets if we were in the opening bracket case
2757
            // OR something like @import()
2758
            $res = preg_match_all(
2759
                '/(((([A-Za-z_:])([A-Za-z0-9_:\.-]*))'.
2760
                // '/(((([A-Za-z_:])([A-Za-z0-9_:\.-]|[^\x00-\x7F])*)' . -> seems to be taking too much
2761
                // '/(((([A-Za-z_:])([^\x00-\x7F])*)' . -> takes only last letter of parameter name
2762
                '([ \n\t\r]+)?('.
2763
                // '(=([ \n\t\r]+)?("[^"]+"|\'[^\']+\'|[^ \n\t\r]+))' . -> doesn't restrict close enough to the url itself
2764
                '(=([ \n\t\r]+)?("[^"\)]+"|\'[^\'\)]+\'|[^ \n\t\r\)]+))'.
2765
                '|'.
2766
                // '(\(([ \n\t\r]+)?("[^"]+"|\'[^\']+\'|[^ \n\t\r]+)\))' . -> doesn't restrict close enough to the url itself
2767
                '(\(([ \n\t\r]+)?("[^"\)]+"|\'[^\'\)]+\'|[^ \n\t\r\)]+)\))'.
2768
                '))'.
2769
                '|'.
2770
                // '(@import([ \n\t\r]+)?("[^"]+"|\'[^\']+\'|[^ \n\t\r]+)))?/', -> takes a lot (like 100's of thousands of empty possibilities)
2771
                '(@import([ \n\t\r]+)?("[^"]+"|\'[^\']+\'|[^ \n\t\r]+)))/',
2772
                $attrString,
2773
                $regs
2774
            );
2775
        } catch (Exception $e) {
2776
            error_log('Caught exception: '.$e->getMessage(), 0);
2777
        }
2778
        if ($res) {
2779
            for ($i = 0; $i < count($regs[1]); $i++) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
2780
                $name = trim($regs[3][$i]);
2781
                $check = trim($regs[0][$i]);
2782
                $value = trim($regs[10][$i]);
2783
                if (empty($value) and !empty($regs[13][$i])) {
2784
                    $value = $regs[13][$i];
2785
                }
2786
                if (empty($name) && !empty($regs[16][$i])) {
2787
                    $name = '@import';
2788
                    $value = trim($regs[16][$i]);
2789
                }
2790
                if (!empty($name)) {
2791
                    if (!$reduced || in_array(strtolower($name), $wanted)) {
2792
                        if ($name == $check) {
2793
                            $attributes[strtolower($name)][] = strtolower($name);
2794
                        } else {
2795
                            if (!empty($value) && ($value[0] == '\'' || $value[0] == '"')) {
2796
                                $value = substr($value, 1, -1);
2797
                            }
2798
2799
                            if ($value == 'API.LMSGetValue(name') {
2800
                                $value = 'API.LMSGetValue(name)';
2801
                            }
2802
                            //Gets the xx.flv value from the string flashvars="width=320&height=240&autostart=false&file=xxx.flv&repeat=false"
2803
                            if (isset($explode_variables[$name])) {
2804
                                $value_modified = str_replace('&amp;', '&', $value);
2805
                                $value_array = explode('&', $value_modified);
2806
                                foreach ($value_array as $item) {
2807
                                    $itemParts = explode('=', $item);
2808
                                    $key = $itemParts[0];
2809
                                    $item_value = !empty($itemParts[1]) ? $itemParts[1] : '';
2810
                                    if ($key == $explode_variables[$name]) {
2811
                                        $attributes[strtolower($name)][] = $item_value;
2812
                                    }
2813
                                }
2814
                            }
2815
                            $attributes[strtolower($name)][] = $value;
2816
                        }
2817
                    }
2818
                }
2819
            }
2820
        }
2821
2822
        return $attributes;
2823
    }
2824
2825
    /**
2826
     * Replace urls inside content html from a copy course.
2827
     *
2828
     * @param string $content_html
2829
     * @param string $origin_course_code
2830
     * @param string $destination_course_directory
2831
     * @param string $origin_course_path_from_zip
2832
     * @param string $origin_course_info_path
2833
     *
2834
     * @return string new content html with replaced urls or return false if content is not a string
2835
     */
2836
    public static function replaceUrlWithNewCourseCode(
2837
        $content_html,
2838
        $origin_course_code,
2839
        $destination_course_directory,
2840
        $origin_course_path_from_zip = null,
2841
        $origin_course_info_path = null
2842
    ) {
2843
        if (empty($content_html)) {
2844
            return false;
2845
        }
2846
2847
        $orig_source_html = self::get_resources_from_source_html($content_html);
2848
        $orig_course_info = api_get_course_info($origin_course_code);
2849
2850
        // Course does not exist in the current DB probably this came from a zip file?
2851
        if (empty($orig_course_info)) {
2852
            if (!empty($origin_course_path_from_zip)) {
2853
                $orig_course_path = $origin_course_path_from_zip.'/';
2854
                $orig_course_info_path = $origin_course_info_path;
2855
            }
2856
        } else {
2857
            $orig_course_path = api_get_path(SYS_COURSE_PATH).$orig_course_info['path'].'/';
2858
            $orig_course_info_path = $orig_course_info['path'];
2859
        }
2860
2861
        $destination_course_code = CourseManager::getCourseCodeFromDirectory($destination_course_directory);
2862
        $destination_course_info = api_get_course_info($destination_course_code);
2863
        $dest_course_path = api_get_path(SYS_COURSE_PATH).$destination_course_directory.'/';
2864
        $dest_course_path_rel = api_get_path(REL_COURSE_PATH).$destination_course_directory.'/';
2865
2866
        $user_id = api_get_user_id();
2867
2868
        if (!empty($orig_source_html)) {
2869
            foreach ($orig_source_html as $source) {
2870
                // Get information about source url
2871
                $real_orig_url = $source[0]; // url
2872
                $scope_url = $source[1]; // scope (local, remote)
2873
                $type_url = $source[2]; // type (rel, abs, url)
2874
2875
                // Get path and query from origin url
2876
                $orig_parse_url = parse_url($real_orig_url);
2877
                $real_orig_path = isset($orig_parse_url['path']) ? $orig_parse_url['path'] : null;
2878
                $real_orig_query = isset($orig_parse_url['query']) ? $orig_parse_url['query'] : null;
2879
2880
                // Replace origin course code by destination course code from origin url query
2881
                $dest_url_query = '';
2882
2883
                if (!empty($real_orig_query)) {
2884
                    $dest_url_query = '?'.$real_orig_query;
2885
                    if (strpos($dest_url_query, $origin_course_code) !== false) {
2886
                        $dest_url_query = str_replace($origin_course_code, $destination_course_code, $dest_url_query);
2887
                    }
2888
                }
2889
2890
                if ($scope_url == 'local') {
2891
                    if ($type_url == 'abs' || $type_url == 'rel') {
2892
                        $document_file = strstr($real_orig_path, 'document');
2893
2894
                        if ($document_file && strpos($real_orig_path, $document_file) !== false) {
2895
                            $origin_filepath = $orig_course_path.$document_file;
2896
                            $destination_filepath = $dest_course_path.$document_file;
2897
2898
                            // copy origin file inside destination course
2899
                            if (file_exists($origin_filepath)) {
2900
                                $filepath_dir = dirname($destination_filepath);
2901
2902
                                if (!is_dir($filepath_dir)) {
2903
                                    $perm = api_get_permissions_for_new_directories();
2904
                                    $result = @mkdir($filepath_dir, $perm, true);
2905
                                    if ($result) {
2906
                                        $filepath_to_add = str_replace(
2907
                                            [$dest_course_path, 'document'],
2908
                                            '',
2909
                                            $filepath_dir
2910
                                        );
2911
2912
                                        //Add to item properties to the new folder
2913
                                        $doc_id = add_document(
2914
                                            $destination_course_info,
2915
                                            $filepath_to_add,
2916
                                            'folder',
2917
                                            0,
2918
                                            basename($filepath_to_add)
2919
                                        );
2920
                                        api_item_property_update(
2921
                                            $destination_course_info,
2922
                                            TOOL_DOCUMENT,
2923
                                            $doc_id,
2924
                                            'FolderCreated',
2925
                                            $user_id,
2926
                                            null,
2927
                                            null,
2928
                                            null,
2929
                                            null
2930
                                        );
2931
                                    }
2932
                                }
2933
2934
                                if (!file_exists($destination_filepath)) {
2935
                                    $result = @copy($origin_filepath, $destination_filepath);
2936
                                    if ($result) {
2937
                                        $filepath_to_add = str_replace(
2938
                                            [$dest_course_path, 'document'],
2939
                                            '',
2940
                                            $destination_filepath
2941
                                        );
2942
                                        $size = filesize($destination_filepath);
2943
2944
                                        // Add to item properties to the file
2945
                                        $doc_id = add_document(
2946
                                            $destination_course_info,
2947
                                            $filepath_to_add,
2948
                                            'file',
2949
                                            $size,
2950
                                            basename($filepath_to_add)
2951
                                        );
2952
                                        api_item_property_update(
2953
                                            $destination_course_info,
2954
                                            TOOL_DOCUMENT,
2955
                                            $doc_id,
2956
                                            'FolderCreated',
2957
                                            $user_id,
2958
                                            null,
2959
                                            null,
2960
                                            null,
2961
                                            null
2962
                                        );
2963
                                    }
2964
                                }
2965
                            }
2966
2967
                            // Replace origin course path by destination course path.
2968
                            if (strpos($content_html, $real_orig_url) !== false) {
2969
                                $url_course_path = str_replace(
2970
                                    $orig_course_info_path.'/'.$document_file,
2971
                                    '',
2972
                                    $real_orig_path
2973
                                );
2974
                                // See BT#7780
2975
                                $destination_url = $dest_course_path_rel.$document_file.$dest_url_query;
2976
                                // If the course code doesn't exist in the path? what we do? Nothing! see BT#1985
2977
                                if (strpos($real_orig_path, $origin_course_code) === false) {
2978
                                    $url_course_path = $real_orig_path;
2979
                                    $destination_url = $real_orig_path;
2980
                                }
2981
                                $content_html = str_replace($real_orig_url, $destination_url, $content_html);
2982
                            }
2983
                        }
2984
2985
                        // replace origin course code by destination course code  from origin url
2986
                        if (strpos($real_orig_url, '?') === 0) {
2987
                            $dest_url = str_replace($origin_course_code, $destination_course_code, $real_orig_url);
2988
                            $content_html = str_replace($real_orig_url, $dest_url, $content_html);
2989
                        }
2990
                    }
2991
                }
2992
            }
2993
        }
2994
2995
        return $content_html;
2996
    }
2997
2998
    /**
2999
     * Export document to PDF.
3000
     *
3001
     * @param int    $document_id
3002
     * @param string $courseCode
3003
     * @param string $orientation
3004
     * @param bool   $showHeaderAndFooter
3005
     */
3006
    public static function export_to_pdf(
3007
        $document_id,
3008
        $courseCode,
3009
        $orientation = 'landscape',
3010
        $showHeaderAndFooter = true
3011
    ) {
3012
        $course_data = api_get_course_info($courseCode);
3013
        $document_data = self::get_document_data_by_id($document_id, $courseCode);
3014
        $file_path = api_get_path(SYS_COURSE_PATH).$course_data['path'].'/document'.$document_data['path'];
3015
3016
        $pageFormat = 'A4';
3017
        $pdfOrientation = 'P';
3018
        if ($orientation === 'landscape') {
3019
            $pageFormat = 'A4-L';
3020
            $pdfOrientation = 'L';
3021
        }
3022
        $pdf = new PDF(
3023
            $pageFormat,
3024
            $pdfOrientation,
3025
            $showHeaderAndFooter ? [] : ['top' => 0, 'left' => 0, 'bottom' => 0, 'right' => 0]
3026
        );
3027
3028
        if (api_get_configuration_value('use_alternative_document_pdf_footer')) {
3029
            $view = new Template('', false, false, false, true, false, false);
3030
            $template = $view->get_template('export/alt_pdf_footer.tpl');
3031
            $pdf->set_custom_footer(['html' => $view->fetch($template)]);
3032
        }
3033
3034
        $pdf->html_to_pdf(
3035
            $file_path,
3036
            $document_data['title'],
3037
            $courseCode,
3038
            false,
3039
            $showHeaderAndFooter
3040
        );
3041
    }
3042
3043
    /**
3044
     * Uploads a document.
3045
     *
3046
     * @param array  $files                   the $_FILES variable
3047
     * @param string $path
3048
     * @param string $title
3049
     * @param string $comment
3050
     * @param int    $unzip                   unzip or not the file
3051
     * @param string $ifExists                overwrite, rename or warn (default)
3052
     * @param bool   $index_document          index document (search xapian module)
3053
     * @param bool   $show_output             print html messages
3054
     * @param string $fileKey
3055
     * @param bool   $treat_spaces_as_hyphens
3056
     * @param int    $userId                  Optional. User ID who upload file
3057
     * @param array  $courseInfo              Optional. Course info
3058
     * @param int    $sessionId               Optional. Session ID
3059
     * @param int    $groupId                 Optional. Group ID
3060
     * @param bool   $recordAudioExercise
3061
     *
3062
     * @return array|bool
3063
     */
3064
    public static function upload_document(
3065
        $files,
3066
        $path,
3067
        $title = '',
3068
        $comment = '',
3069
        $unzip = 0,
3070
        $ifExists = '',
3071
        $index_document = false,
3072
        $show_output = false,
3073
        $fileKey = 'file',
3074
        $treat_spaces_as_hyphens = true,
3075
        $userId = 0,
3076
        array $courseInfo = [],
3077
        $sessionId = 0,
3078
        $groupId = 0,
3079
        $recordAudioExercise = false
3080
    ) {
3081
        $course_info = $courseInfo ?: api_get_course_info();
3082
        $sessionId = $sessionId ?: api_get_session_id();
3083
        $course_dir = $course_info['path'].'/document';
3084
        $sys_course_path = api_get_path(SYS_COURSE_PATH);
3085
        $base_work_dir = $sys_course_path.$course_dir;
3086
        $userId = $userId ?: api_get_user_id();
3087
        $groupId = $groupId ?: api_get_group_id();
3088
3089
        if ($recordAudioExercise) {
3090
            $base_work_dir = $sys_course_path.$course_info['path'].'/exercises';
3091
            $path = str_replace('/../exercises/', '/', $path);
3092
        }
3093
3094
        if (isset($files[$fileKey])) {
3095
            $uploadOk = process_uploaded_file($files[$fileKey], $show_output);
3096
            if ($uploadOk) {
3097
                $new_path = handle_uploaded_document(
3098
                    $course_info,
3099
                    $files[$fileKey],
3100
                    $base_work_dir,
3101
                    $path,
3102
                    $userId,
3103
                    $groupId,
3104
                    null,
3105
                    $unzip,
3106
                    $ifExists,
3107
                    $show_output,
3108
                    false,
3109
                    null,
3110
                    $sessionId,
3111
                    $treat_spaces_as_hyphens
3112
                );
3113
3114
                // When sending zip files
3115
                if ($new_path === true && $unzip == 1) {
3116
                    return [
3117
                        'title' => $files[$fileKey]['name'],
3118
                        'url' => '#',
3119
                    ];
3120
                }
3121
3122
                if ($new_path) {
3123
                    $documentId = self::get_document_id(
3124
                        $course_info,
3125
                        $new_path,
3126
                        $sessionId
3127
                    );
3128
3129
                    if (!empty($documentId)) {
3130
                        $table_document = Database::get_course_table(TABLE_DOCUMENT);
3131
                        $params = [];
3132
3133
                        if (!empty($title)) {
3134
                            $params['title'] = $title;
3135
                        }
3136
3137
                        if (!empty($comment)) {
3138
                            $params['comment'] = trim($comment);
3139
                        }
3140
3141
                        Database::update(
3142
                            $table_document,
3143
                            $params,
3144
                            [
3145
                                'id = ? AND c_id = ? ' => [
3146
                                    $documentId,
3147
                                    $course_info['real_id'],
3148
                                ],
3149
                            ]
3150
                        );
3151
                    }
3152
3153
                    if ($index_document) {
3154
                        self::index_document(
3155
                            $documentId,
3156
                            $course_info['code'],
3157
                            null,
3158
                            $_POST['language'],
3159
                            $_REQUEST,
3160
                            $ifExists
3161
                        );
3162
                    }
3163
3164
                    if (!empty($documentId) && is_numeric($documentId)) {
3165
                        $documentData = self::get_document_data_by_id(
3166
                            $documentId,
3167
                            $course_info['code'],
3168
                            false,
3169
                            $sessionId
3170
                        );
3171
3172
                        return $documentData;
3173
                    }
3174
                }
3175
            }
3176
        }
3177
3178
        return false;
3179
    }
3180
3181
    /**
3182
     * Obtains the text inside the file with the right parser.
3183
     */
3184
    public static function get_text_content($doc_path, $doc_mime)
3185
    {
3186
        // TODO: review w$ compatibility
3187
        // Use usual exec output lines array to store stdout instead of a temp file
3188
        // because we need to store it at RAM anyway before index on ChamiloIndexer object
3189
        $ret_val = null;
3190
        switch ($doc_mime) {
3191
            case 'text/plain':
3192
                $handle = fopen($doc_path, 'r');
3193
                $output = [fread($handle, filesize($doc_path))];
3194
                fclose($handle);
3195
                break;
3196
            case 'application/pdf':
3197
                exec("pdftotext $doc_path -", $output, $ret_val);
3198
                break;
3199
            case 'application/postscript':
3200
                $temp_file = tempnam(sys_get_temp_dir(), 'chamilo');
3201
                exec("ps2pdf $doc_path $temp_file", $output, $ret_val);
3202
                if ($ret_val !== 0) { // shell fail, probably 127 (command not found)
3203
                    return false;
3204
                }
3205
                exec("pdftotext $temp_file -", $output, $ret_val);
3206
                unlink($temp_file);
3207
                break;
3208
            case 'application/msword':
3209
                exec("catdoc $doc_path", $output, $ret_val);
3210
                break;
3211
            case 'text/html':
3212
                exec("html2text $doc_path", $output, $ret_val);
3213
                break;
3214
            case 'text/rtf':
3215
                // Note: correct handling of code pages in unrtf
3216
                // on debian lenny unrtf v0.19.2 can not, but unrtf v0.20.5 can
3217
                exec("unrtf --text $doc_path", $output, $ret_val);
3218
                if ($ret_val == 127) { // command not found
3219
                    return false;
3220
                }
3221
                // Avoid index unrtf comments
3222
                if (is_array($output) && count($output) > 1) {
3223
                    $parsed_output = [];
3224
                    foreach ($output as &$line) {
3225
                        if (!preg_match('/^###/', $line, $matches)) {
3226
                            if (!empty($line)) {
3227
                                $parsed_output[] = $line;
3228
                            }
3229
                        }
3230
                    }
3231
                    $output = $parsed_output;
3232
                }
3233
                break;
3234
            case 'application/vnd.ms-powerpoint':
3235
                exec("catppt $doc_path", $output, $ret_val);
3236
                break;
3237
            case 'application/vnd.ms-excel':
3238
                exec("xls2csv -c\" \" $doc_path", $output, $ret_val);
3239
                break;
3240
        }
3241
3242
        $content = '';
3243
        if (!is_null($ret_val)) {
3244
            if ($ret_val !== 0) { // shell fail, probably 127 (command not found)
3245
                return false;
3246
            }
3247
        }
3248
        if (isset($output)) {
3249
            foreach ($output as &$line) {
3250
                $content .= $line."\n";
3251
            }
3252
3253
            return $content;
3254
        } else {
3255
            return false;
3256
        }
3257
    }
3258
3259
    /**
3260
     * Calculates the total size of all documents in a course.
3261
     *
3262
     * @author Bert vanderkimpen
3263
     *
3264
     * @param int $course_id
3265
     * @param int $group_id   (to calculate group document space)
3266
     * @param int $session_id
3267
     *
3268
     * @return int total size
3269
     */
3270
    public static function documents_total_space($course_id = null, $group_id = null, $session_id = null)
3271
    {
3272
        $TABLE_ITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
3273
        $TABLE_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
3274
3275
        $session_id = (int) $session_id;
3276
        $group_id = (int) $group_id;
3277
        $course_id = (int) $course_id;
3278
3279
        if (!$course_id) {
3280
            $course_id = api_get_course_int_id();
3281
        }
3282
3283
        $group_condition = '';
3284
        if ($group_id) {
3285
            $group_condition = " AND props.to_group_id='".$group_id."' ";
3286
        }
3287
3288
        $session_condition = '';
3289
        if ($session_id) {
3290
            $session_condition = " AND props.session_id='".$session_id."' ";
3291
        }
3292
3293
        $sql = "SELECT SUM(size)
3294
                FROM $TABLE_ITEMPROPERTY AS props
3295
                INNER JOIN $TABLE_DOCUMENT AS docs
3296
                ON (docs.id = props.ref AND props.c_id = docs.c_id)
3297
                WHERE
3298
                    props.c_id = $course_id AND
3299
                    docs.c_id = $course_id AND
3300
                    props.tool = '".TOOL_DOCUMENT."' AND
3301
                    props.visibility <> 2
3302
                    $group_condition
3303
                    $session_condition
3304
                ";
3305
        $result = Database::query($sql);
3306
3307
        if ($result && Database::num_rows($result) != 0) {
3308
            $row = Database::fetch_row($result);
3309
3310
            return (int) $row[0];
3311
        } else {
3312
            return 0;
3313
        }
3314
    }
3315
3316
    /**
3317
     * Display the document quota in a simple way.
3318
     *
3319
     *  Here we count 1 Kilobyte = 1024 Bytes, 1 Megabyte = 1048576 Bytes
3320
     */
3321
    public static function displaySimpleQuota($course_quota, $already_consumed_space)
3322
    {
3323
        $course_quota_m = round($course_quota / 1048576);
3324
        $already_consumed_space_m = round($already_consumed_space / 1048576, 2);
3325
        $percentage = $already_consumed_space / $course_quota * 100;
3326
        $percentage = round($percentage, 1);
3327
        $message = get_lang('YouAreCurrentlyUsingXOfYourX');
3328
        $message = sprintf($message, $already_consumed_space_m, $percentage.'%', $course_quota_m.' ');
3329
3330
        return Display::div($message, ['id' => 'document_quota']);
3331
    }
3332
3333
    /**
3334
     * Checks if there is enough place to add a file on a directory
3335
     * on the base of a maximum directory size allowed.
3336
     *
3337
     * @author Bert Vanderkimpen
3338
     *
3339
     * @param int $file_size     size of the file in byte
3340
     * @param int $max_dir_space maximum size
3341
     *
3342
     * @return bool true if there is enough space, false otherwise
3343
     *
3344
     * @see enough_space() uses  documents_total_space() function
3345
     */
3346
    public static function enough_space($file_size, $max_dir_space)
3347
    {
3348
        if ($max_dir_space) {
3349
            $already_filled_space = self::documents_total_space();
3350
            if (($file_size + $already_filled_space) > $max_dir_space) {
3351
                return false;
3352
            }
3353
        }
3354
3355
        return true;
3356
    }
3357
3358
    /**
3359
     * @param array $params count, url, extension
3360
     *
3361
     * @return string
3362
     */
3363
    public static function generateAudioJavascript($params = [])
3364
    {
3365
        return '
3366
            $(\'audio.audio_preview\').mediaelementplayer({
3367
                features: [\'playpause\'],
3368
                audioWidth: 30,
3369
                audioHeight: 30,
3370
                success: function(mediaElement, originalNode, instance) {
3371
                }
3372
            });';
3373
    }
3374
3375
    /**
3376
     * Shows a play icon next to the document title in the document list.
3377
     *
3378
     * @param string $documentWebPath
3379
     * @param array  $documentInfo
3380
     *
3381
     * @return string
3382
     */
3383
    public static function generateAudioPreview($documentWebPath, $documentInfo)
3384
    {
3385
        $filePath = $documentWebPath.$documentInfo['path'];
3386
        $extension = $documentInfo['file_extension'];
3387
3388
        if (!in_array($extension, ['mp3', 'wav', 'ogg'])) {
3389
            return '';
3390
        }
3391
3392
        return '<span class="preview"> <audio class="audio_preview skip" src="'.$filePath.'" type="audio/'.$extension.'" > </audio></span>';
3393
    }
3394
3395
    /**
3396
     * @param string $file
3397
     * @param string $extension
3398
     *
3399
     * @return string
3400
     */
3401
    public static function generateMediaPreview($file, $extension)
3402
    {
3403
        $id = api_get_unique_id();
3404
        switch ($extension) {
3405
            case 'wav':
3406
            case 'ogg':
3407
            case 'mp3':
3408
                $html = '<div style="margin: 0; position: absolute; top: 50%; left: 35%;">';
3409
                $html .= '<audio id="'.$id.'" controls="controls" src="'.$file.'" type="audio/mp3" ></audio></div>';
3410
                break;
3411
            default:
3412
                $html = '<video id="'.$id.'" width="100%" height="100%" controls>';
3413
                $html .= '<source src="'.$file.'" >';
3414
                $html .= '</video>';
3415
                break;
3416
        }
3417
3418
        return $html;
3419
    }
3420
3421
    /**
3422
     * @param array  $course_info
3423
     * @param bool   $lp_id
3424
     * @param string $target
3425
     * @param int    $session_id
3426
     * @param bool   $add_move_button
3427
     * @param string $filter_by_folder
3428
     * @param string $overwrite_url
3429
     * @param bool   $showInvisibleFiles
3430
     * @param bool   $showOnlyFolders
3431
     * @param int    $folderId
3432
     * @param bool   $addCloseButton
3433
     * @param bool   $addAudioPreview
3434
     * @param array  $filterByExtension
3435
     *
3436
     * @return string
3437
     */
3438
    public static function get_document_preview(
3439
        $course_info,
3440
        $lp_id = false,
3441
        $target = '',
3442
        $session_id = 0,
3443
        $add_move_button = false,
3444
        $filter_by_folder = null,
3445
        $overwrite_url = '',
3446
        $showInvisibleFiles = false,
3447
        $showOnlyFolders = false,
3448
        $folderId = false,
3449
        $addCloseButton = true,
3450
        $addAudioPreview = false,
3451
        $filterByExtension = []
3452
    ) {
3453
        if (empty($course_info['real_id']) || empty($course_info['code']) || !is_array($course_info)) {
3454
            return '';
3455
        }
3456
3457
        $user_id = api_get_user_id();
3458
        $userInfo = api_get_user_info();
3459
        $user_in_course = api_is_platform_admin();
3460
        if (!$user_in_course) {
3461
            if (CourseManager::is_course_teacher($user_id, $course_info['code'])) {
3462
                $user_in_course = true;
3463
            }
3464
        }
3465
3466
        // Condition for the session
3467
        $session_id = (int) $session_id;
3468
3469
        if (!$user_in_course) {
3470
            if (empty($session_id)) {
3471
                if (CourseManager::is_user_subscribed_in_course($user_id, $course_info['code'])) {
3472
                    $user_in_course = true;
3473
                }
3474
                // Check if course is open then we can consider that the student is registered to the course
3475
                if (isset($course_info) && in_array($course_info['visibility'], [2, 3])) {
3476
                    $user_in_course = true;
3477
                }
3478
            } else {
3479
                $user_status = SessionManager::get_user_status_in_course_session(
3480
                    $user_id,
3481
                    $course_info['real_id'],
3482
                    $session_id
3483
                );
3484
                //is true if is an student, course session teacher or coach
3485
                if (in_array($user_status, ['0', '2', '6'])) {
3486
                    $user_in_course = true;
3487
                }
3488
            }
3489
        }
3490
3491
        $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
3492
        $tbl_item_prop = Database::get_course_table(TABLE_ITEM_PROPERTY);
3493
        $condition_session = " AND (last.session_id = '$session_id' OR last.session_id = '0' OR last.session_id IS NULL)";
3494
3495
        $add_folder_filter = null;
3496
        if (!empty($filter_by_folder)) {
3497
            $add_folder_filter = " AND docs.path LIKE '".Database::escape_string($filter_by_folder)."%'";
3498
        }
3499
3500
        // If we are in LP display hidden folder https://support.chamilo.org/issues/6679
3501
        $lp_visibility_condition = null;
3502
        if ($lp_id || $showOnlyFolders) {
3503
            if ($showInvisibleFiles || $showOnlyFolders) {
3504
                $lp_visibility_condition .= ' OR last.visibility = 0';
3505
            }
3506
        }
3507
3508
        $folderCondition = " AND docs.path LIKE '/%' ";
3509
        if (!api_is_allowed_to_edit()) {
3510
            $protectedFolders = self::getProtectedFolderFromStudent();
3511
            foreach ($protectedFolders as $folder) {
3512
                $folderCondition .= " AND docs.path NOT LIKE '$folder' ";
3513
            }
3514
        }
3515
3516
        $extensionConditionToString = '';
3517
        if (!empty($filterByExtension)) {
3518
            $extensionCondition = [];
3519
            foreach ($filterByExtension as $extension) {
3520
                $extensionCondition[] = " docs.path LIKE '%.$extension' ";
3521
            }
3522
            if (!empty($extensionCondition)) {
3523
                $extensionConditionToString .= " AND (".implode('OR', $extensionCondition).") ";
3524
            }
3525
        }
3526
3527
        $parentData = [];
3528
        if ($folderId !== false) {
3529
            $parentData = self::get_document_data_by_id(
3530
                $folderId,
3531
                $course_info['code'],
3532
                false,
3533
                $session_id
3534
            );
3535
            if (!empty($parentData)) {
3536
                $cleanedPath = $parentData['path'];
3537
                $num = substr_count($cleanedPath, '/');
3538
3539
                $notLikeCondition = '';
3540
                for ($i = 1; $i <= $num; $i++) {
3541
                    $repeat = str_repeat('/%', $i + 1);
3542
                    $notLikeCondition .= " AND docs.path NOT LIKE '".Database::escape_string($cleanedPath.$repeat)."' ";
3543
                }
3544
3545
                $folderId = (int) $folderId;
3546
                $folderCondition = " AND
3547
                    docs.id <> $folderId AND
3548
                    docs.path LIKE '".$cleanedPath."/%'
3549
                    $notLikeCondition
3550
                ";
3551
            } else {
3552
                $folderCondition = " AND docs.filetype = 'file' ";
3553
            }
3554
        }
3555
3556
        $levelCondition = '';
3557
        if ($folderId === false) {
3558
            $levelCondition = " AND docs.path NOT LIKE'/%/%'";
3559
        }
3560
3561
        $sql = "SELECT DISTINCT last.visibility, docs.*
3562
                FROM $tbl_item_prop AS last
3563
                INNER JOIN $tbl_doc AS docs
3564
                ON (docs.id = last.ref AND docs.c_id = last.c_id)
3565
                WHERE
3566
                    docs.path NOT LIKE '%_DELETED_%' AND
3567
                    last.tool = '".TOOL_DOCUMENT."' $condition_session AND
3568
                    (last.visibility = '1' $lp_visibility_condition) AND
3569
                    last.visibility <> 2 AND
3570
                    docs.c_id = {$course_info['real_id']} AND
3571
                    last.c_id = {$course_info['real_id']}
3572
                    $folderCondition
3573
                    $levelCondition
3574
                    $extensionConditionToString
3575
                    $add_folder_filter
3576
                ORDER BY docs.filetype DESC, docs.title ASC";
3577
3578
        $res_doc = Database::query($sql);
3579
        $resources = Database::store_result($res_doc, 'ASSOC');
3580
3581
        $return = '';
3582
        if ($lp_id == false && $addCloseButton) {
3583
            if ($folderId === false) {
3584
                $return .= Display::div(
3585
                    Display::url(
3586
                        Display::return_icon('close.png', get_lang('Close'), [], ICON_SIZE_SMALL),
3587
                        ' javascript:void(0);',
3588
                        ['id' => 'close_div_'.$course_info['real_id'].'_'.$session_id, 'class' => 'close_div']
3589
                    ),
3590
                    ['style' => 'position:absolute;right:10px']
3591
                );
3592
            }
3593
        }
3594
3595
        // If you want to debug it, I advise you to do "echo" on the eval statements.
3596
        $newResources = [];
3597
        $added = [];
3598
        if (!empty($resources) && $user_in_course) {
3599
            foreach ($resources as $resource) {
3600
                $docId = $resource['id'];
3601
                if (in_array($docId, $added)) {
3602
                    continue;
3603
                }
3604
3605
                $is_visible = self::is_visible_by_id(
3606
                    $docId,
3607
                    $course_info,
3608
                    $session_id,
3609
                    api_get_user_id()
3610
                );
3611
3612
                if ($showOnlyFolders) {
3613
                    $isFolder = ('folder' === $resource['filetype']);
3614
                    $visibility = (int) $resource['visibility'];
3615
                    if (!$isFolder && 0 == $visibility) {
3616
                        continue;
3617
                    }
3618
                }
3619
3620
                if ($showInvisibleFiles === false) {
3621
                    if (!$is_visible) {
3622
                        continue;
3623
                    }
3624
                }
3625
                $added[] = $docId;
3626
                $newResources[] = $resource;
3627
            }
3628
        }
3629
3630
        $label = get_lang('Documents');
3631
3632
        $documents = [];
3633
        if ($folderId === false) {
3634
            $documents[$label] = [
3635
                'id' => 0,
3636
                'files' => $newResources,
3637
            ];
3638
        } else {
3639
            if (is_array($parentData)) {
3640
                $documents[$parentData['title']] = [
3641
                    'id' => (int) $folderId,
3642
                    'files' => $newResources,
3643
                ];
3644
            }
3645
        }
3646
3647
        $writeResult = self::write_resources_tree(
3648
            $userInfo,
3649
            $course_info,
3650
            $session_id,
3651
            $documents,
3652
            $lp_id,
3653
            $target,
3654
            $add_move_button,
3655
            $overwrite_url,
3656
            $folderId,
3657
            $addAudioPreview
3658
        );
3659
3660
        $return .= $writeResult;
3661
        $lpAjaxUrl = api_get_path(WEB_AJAX_PATH).'lp.ajax.php';
3662
        $extraAjaxParams = ($showOnlyFolders ? '&showOnlyFolders='.(int) $showOnlyFolders : '');
3663
        if ($lp_id === false) {
3664
            $url = $lpAjaxUrl.'?a=get_documents&lp_id=&cidReq='.$course_info['code'].$extraAjaxParams;
3665
            $return .= "<script>
3666
            $(function() {
3667
                $('.close_div').click(function() {
3668
                    var course_id = this.id.split('_')[2];
3669
                    var session_id = this.id.split('_')[3];
3670
                    $('#document_result_'+course_id+'_'+session_id).hide();
3671
                    $('.lp_resource').remove();
3672
                    $('.document_preview_container').html('');
3673
                });
3674
            });
3675
            </script>";
3676
        } else {
3677
            // For LPs
3678
            $url = $lpAjaxUrl.'?a=get_documents&lp_id='.(int) $lp_id.'&'.api_get_cidreq().$extraAjaxParams;
3679
        }
3680
3681
        if (!empty($overwrite_url)) {
3682
            $url .= '&url='.urlencode(Security::remove_XSS($overwrite_url));
3683
        }
3684
3685
        if ($add_move_button) {
3686
            $url .= '&add_move_button=1';
3687
        }
3688
3689
        $return .= "<script>
3690
            function testResources(id, img) {
3691
                var numericId = id.split('_')[1];
3692
                var parentId = 'doc_id_'+numericId;
3693
                var tempId = 'temp_'+numericId;
3694
                var image = $('#'+img);
3695
3696
                if (image.hasClass('open')) {
3697
                    image.removeClass('open');
3698
                    image.attr('src', '".Display::returnIconPath('nolines_plus.gif')."');
3699
                    $('#'+id).show();
3700
                    $('#'+tempId).hide();
3701
                } else {
3702
                    image.addClass('open');
3703
                    image.attr('src', '".Display::returnIconPath('nolines_minus.gif')."');
3704
                    $('#'+id).hide();
3705
                    $('#'+tempId).show();
3706
                    var tempDiv = $('#'+parentId).find('#'+tempId);
3707
                    if (tempDiv.length == 0) {
3708
                        $.ajax({
3709
                            type: 'GET',
3710
                            url:  '".$url."',
3711
                            data: 'folder_id='+numericId,
3712
                            success: function(data) {
3713
                                tempDiv = $('#doc_id_'+numericId).append('<div id='+tempId+'>'+data+'</div>');
3714
                            }
3715
                        });
3716
                    }
3717
                }
3718
            }
3719
            </script>";
3720
3721
        if (!$user_in_course) {
3722
            $return = '';
3723
        }
3724
3725
        return $return;
3726
    }
3727
3728
    /**
3729
     * Generate and return an HTML list of resources based on a given array.
3730
     * This list is used to show the course creator a list of available resources to choose from
3731
     * when creating a learning path.
3732
     *
3733
     * @param array  $userInfo        current user info
3734
     * @param array  $course_info
3735
     * @param int    $session_id
3736
     * @param array  $documents
3737
     * @param bool   $lp_id
3738
     * @param string $target
3739
     * @param bool   $add_move_button
3740
     * @param string $overwrite_url
3741
     * @param int    $folderId
3742
     * @param bool   $addAudioPreview
3743
     *
3744
     * @return string
3745
     */
3746
    public static function write_resources_tree(
3747
        $userInfo,
3748
        $course_info,
3749
        $session_id,
3750
        $documents,
3751
        $lp_id = false,
3752
        $target = '',
3753
        $add_move_button = false,
3754
        $overwrite_url = '',
3755
        $folderId = false,
3756
        $addAudioPreview = false
3757
    ) {
3758
        $return = '';
3759
        if (!empty($documents)) {
3760
            foreach ($documents as $key => $resource) {
3761
                if (isset($resource['id']) && isset($resource['files'])) {
3762
                    $mainFolderResource = [
3763
                        'id' => $resource['id'],
3764
                        'title' => $key,
3765
                    ];
3766
                    $close = false;
3767
3768
                    if ($folderId === false) {
3769
                        $parsedFolder = self::parseFolder($folderId, $mainFolderResource, $lp_id);
3770
                        $close = (bool) $parsedFolder;
3771
3772
                        $return .= $parsedFolder;
3773
                    }
3774
3775
                    if (isset($resource['files'])) {
3776
                        $return .= self::write_resources_tree(
3777
                            $userInfo,
3778
                            $course_info,
3779
                            $session_id,
3780
                            $resource['files'],
3781
                            $lp_id,
3782
                            $target,
3783
                            $add_move_button,
3784
                            $overwrite_url,
3785
                            false,
3786
                            $addAudioPreview
3787
                        );
3788
                    }
3789
3790
                    if ($close) {
3791
                        $return .= '</div>';
3792
                        $return .= '</ul>';
3793
                    }
3794
                } else {
3795
                    if ($resource['filetype'] === 'folder') {
3796
                        $return .= self::parseFolder($folderId, $resource, $lp_id);
3797
                    } else {
3798
                        $return .= self::parseFile(
3799
                            $userInfo,
3800
                            $course_info,
3801
                            $session_id,
3802
                            $resource,
3803
                            $lp_id,
3804
                            $add_move_button,
3805
                            $target,
3806
                            $overwrite_url,
3807
                            $addAudioPreview
3808
                        );
3809
                    }
3810
                }
3811
            }
3812
        }
3813
3814
        return $return;
3815
    }
3816
3817
    /**
3818
     * @param int   $doc_id
3819
     * @param array $courseInfo
3820
     * @param int   $sessionId
3821
     * @param int   $user_id
3822
     * @param int   $groupId               iid
3823
     * @param bool  $checkParentVisibility
3824
     *
3825
     * @return bool
3826
     */
3827
    public static function check_visibility_tree(
3828
        $doc_id,
3829
        $courseInfo,
3830
        $sessionId,
3831
        $user_id,
3832
        $groupId = 0,
3833
        $checkParentVisibility = true
3834
    ) {
3835
        if (empty($courseInfo)) {
3836
            return false;
3837
        }
3838
3839
        $courseCode = $courseInfo['code'];
3840
3841
        if (empty($courseCode)) {
3842
            return false;
3843
        }
3844
3845
        $document_data = self::get_document_data_by_id(
3846
            $doc_id,
3847
            $courseCode,
3848
            null,
3849
            $sessionId
3850
        );
3851
3852
        if ($sessionId != 0 && !$document_data) {
3853
            $document_data = self::get_document_data_by_id(
3854
                $doc_id,
3855
                $courseCode,
3856
                null,
3857
                0
3858
            );
3859
        }
3860
3861
        if (!empty($document_data)) {
3862
            // If admin or course teacher, allow anyway
3863
            if (api_is_platform_admin() || CourseManager::is_course_teacher($user_id, $courseCode)) {
3864
                return true;
3865
            }
3866
            if ($document_data['parent_id'] == false || empty($document_data['parent_id'])) {
3867
                if (!empty($groupId)) {
3868
                    return true;
3869
                }
3870
                $visible = self::is_visible_by_id($doc_id, $courseInfo, $sessionId, $user_id);
3871
3872
                return $visible;
3873
            } else {
3874
                $visible = self::is_visible_by_id($doc_id, $courseInfo, $sessionId, $user_id);
3875
3876
                if (!$visible) {
3877
                    return false;
3878
                } else {
3879
                    if ($checkParentVisibility && $doc_id != $document_data['parent_id']) {
3880
                        return self::check_visibility_tree(
3881
                            $document_data['parent_id'],
3882
                            $courseInfo,
3883
                            $sessionId,
3884
                            $user_id,
3885
                            $groupId
3886
                        );
3887
                    }
3888
3889
                    return true;
3890
                }
3891
            }
3892
        } else {
3893
            return false;
3894
        }
3895
    }
3896
3897
    /**
3898
     * Index a given document.
3899
     *
3900
     * @param   int     Document ID inside its corresponding course
3901
     * @param   string  Course code
3902
     * @param   int     Session ID (not used yet)
3903
     * @param   string  Language of document's content (defaults to course language)
3904
     * @param   array   Array of specific fields (['code'=>'value',...])
3905
     * @param   string  What to do if the file already exists (default or overwrite)
3906
     * @param   bool    When set to true, this runs the indexer without actually saving anything to any database
3907
     *
3908
     * @return bool Returns true on presumed success, false on failure
3909
     */
3910
    public static function index_document(
3911
        $docid,
3912
        $course_code,
3913
        $session_id = 0,
3914
        $lang = 'english',
3915
        $specific_fields_values = [],
3916
        $if_exists = '',
3917
        $simulation = false
3918
    ) {
3919
        if (api_get_setting('search_enabled') !== 'true') {
3920
            return false;
3921
        }
3922
        if (empty($docid) or $docid != intval($docid)) {
3923
            return false;
3924
        }
3925
        if (empty($session_id)) {
3926
            $session_id = api_get_session_id();
3927
        }
3928
        $course_info = api_get_course_info($course_code);
3929
        $course_dir = $course_info['path'].'/document';
3930
        $sys_course_path = api_get_path(SYS_COURSE_PATH);
3931
        $base_work_dir = $sys_course_path.$course_dir;
3932
3933
        $course_id = $course_info['real_id'];
3934
        $table_document = Database::get_course_table(TABLE_DOCUMENT);
3935
3936
        $qry = "SELECT path, title FROM $table_document WHERE c_id = $course_id AND id = '$docid' LIMIT 1";
3937
        $result = Database::query($qry);
3938
        if (Database::num_rows($result) == 1) {
3939
            $row = Database::fetch_array($result);
3940
            $doc_path = api_get_path(SYS_COURSE_PATH).$course_dir.$row['path'];
3941
            //TODO: mime_content_type is deprecated, fileinfo php extension is enabled by default as of PHP 5.3.0
3942
            // now versions of PHP on Debian testing(5.2.6-5) and Ubuntu(5.2.6-2ubuntu) are lower, so wait for a while
3943
            $doc_mime = mime_content_type($doc_path);
3944
            $allowed_mime_types = self::file_get_mime_type(true);
3945
3946
            // mime_content_type does not detect correctly some formats that
3947
            // are going to be supported for index, so an extensions array is used for the moment
3948
            if (empty($doc_mime)) {
3949
                $allowed_extensions = [
3950
                    'doc',
3951
                    'docx',
3952
                    'ppt',
3953
                    'pptx',
3954
                    'pps',
3955
                    'ppsx',
3956
                    'xls',
3957
                    'xlsx',
3958
                    'odt',
3959
                    'odp',
3960
                    'ods',
3961
                    'pdf',
3962
                    'txt',
3963
                    'rtf',
3964
                    'msg',
3965
                    'csv',
3966
                    'html',
3967
                    'htm',
3968
                ];
3969
                $extensions = preg_split("/[\/\\.]/", $doc_path);
3970
                $doc_ext = strtolower($extensions[count($extensions) - 1]);
3971
                if (in_array($doc_ext, $allowed_extensions)) {
3972
                    switch ($doc_ext) {
3973
                        case 'ppt':
3974
                        case 'pps':
3975
                            $doc_mime = 'application/vnd.ms-powerpoint';
3976
                            break;
3977
                        case 'xls':
3978
                            $doc_mime = 'application/vnd.ms-excel';
3979
                            break;
3980
                    }
3981
                }
3982
            }
3983
3984
            //@todo move this nightmare in a search controller or something like that!!! J.M
3985
3986
            if (in_array($doc_mime, $allowed_mime_types)) {
3987
                $file_title = $row['title'];
3988
                $file_content = self::get_text_content($doc_path, $doc_mime);
3989
                $course_code = Database::escape_string($course_code);
3990
                $ic_slide = new IndexableChunk();
3991
                $ic_slide->addValue('title', $file_title);
3992
                $ic_slide->addCourseId($course_code);
3993
                $ic_slide->addToolId(TOOL_DOCUMENT);
3994
                $xapian_data = [
3995
                    SE_COURSE_ID => $course_code,
3996
                    SE_TOOL_ID => TOOL_DOCUMENT,
3997
                    SE_DATA => ['doc_id' => $docid],
3998
                    SE_USER => api_get_user_id(),
3999
                ];
4000
4001
                $ic_slide->xapian_data = serialize($xapian_data);
4002
                $di = new ChamiloIndexer();
4003
                $return = $di->connectDb(null, null, $lang);
4004
4005
                require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
4006
                $specific_fields = get_specific_field_list();
4007
4008
                // process different depending on what to do if file exists
4009
                /**
4010
                 * @TODO Find a way to really verify if the file had been
4011
                 * overwriten. Now all work is done at
4012
                 * handle_uploaded_document() and it's difficult to verify it
4013
                 */
4014
                if (!empty($if_exists) && $if_exists == 'overwrite') {
4015
                    // Overwrite the file on search engine
4016
                    // Actually, it consists on a delete of terms from db,
4017
                    // insert new ones, create a new search engine document,
4018
                    // and remove the old one
4019
                    // Get search_did
4020
                    $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
4021
                    $sql = 'SELECT * FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s LIMIT 1';
4022
                    $sql = sprintf($sql, $tbl_se_ref, $course_code, TOOL_DOCUMENT, $docid);
4023
4024
                    $res = Database::query($sql);
4025
4026
                    if (Database::num_rows($res) > 0) {
4027
                        $se_ref = Database::fetch_array($res);
4028
                        if (!$simulation) {
4029
                            $di->remove_document($se_ref['search_did']);
4030
                        }
4031
                        $all_specific_terms = '';
4032
                        foreach ($specific_fields as $specific_field) {
4033
                            if (!$simulation) {
4034
                                delete_all_specific_field_value($course_code, $specific_field['id'], TOOL_DOCUMENT, $docid);
4035
                            }
4036
                            // Update search engine
4037
                            if (isset($specific_fields_values[$specific_field['code']])) {
4038
                                $sterms = trim($specific_fields_values[$specific_field['code']]);
4039
                            } else { //if the specific field is not defined, force an empty one
4040
                                $sterms = '';
4041
                            }
4042
                            $all_specific_terms .= ' '.$sterms;
4043
                            $sterms = explode(',', $sterms);
4044
                            foreach ($sterms as $sterm) {
4045
                                $sterm = trim($sterm);
4046
                                if (!empty($sterm)) {
4047
                                    $ic_slide->addTerm($sterm, $specific_field['code']);
4048
                                    // updated the last param here from $value to $sterm without being sure - see commit15464
4049
                                    if (!$simulation) {
4050
                                        add_specific_field_value(
4051
                                            $specific_field['id'],
4052
                                            $course_code,
4053
                                            TOOL_DOCUMENT,
4054
                                            $docid,
4055
                                            $sterm
4056
                                        );
4057
                                    }
4058
                                }
4059
                            }
4060
                        }
4061
                        // Add terms also to content to make terms findable by probabilistic search
4062
                        $file_content = $all_specific_terms.' '.$file_content;
4063
4064
                        if (!$simulation) {
4065
                            $ic_slide->addValue('content', $file_content);
4066
                            $di->addChunk($ic_slide);
4067
                            // Index and return a new search engine document id
4068
                            $did = $di->index();
4069
4070
                            if ($did) {
4071
                                // update the search_did on db
4072
                                $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
4073
                                $sql = 'UPDATE %s SET search_did=%d WHERE id=%d LIMIT 1';
4074
                                $sql = sprintf($sql, $tbl_se_ref, (int) $did, (int) $se_ref['id']);
4075
                                Database::query($sql);
4076
                            }
4077
                        }
4078
                    }
4079
                } else {
4080
                    // Add all terms
4081
                    $all_specific_terms = '';
4082
                    foreach ($specific_fields as $specific_field) {
4083
                        if (isset($specific_fields_values[$specific_field['code']])) {
4084
                            $sterms = trim($specific_fields_values[$specific_field['code']]);
4085
                        } else { //if the specific field is not defined, force an empty one
4086
                            $sterms = '';
4087
                        }
4088
                        $all_specific_terms .= ' '.$sterms;
4089
                        if (!empty($sterms)) {
4090
                            $sterms = explode(',', $sterms);
4091
                            foreach ($sterms as $sterm) {
4092
                                if (!$simulation) {
4093
                                    $ic_slide->addTerm(trim($sterm), $specific_field['code']);
4094
                                    add_specific_field_value(
4095
                                        $specific_field['id'],
4096
                                        $course_code,
4097
                                        TOOL_DOCUMENT,
4098
                                        $docid,
4099
                                        $sterm
4100
                                    );
4101
                                }
4102
                            }
4103
                        }
4104
                    }
4105
                    // Add terms also to content to make terms findable by probabilistic search
4106
                    $file_content = $all_specific_terms.' '.$file_content;
4107
                    if (!$simulation) {
4108
                        $ic_slide->addValue('content', $file_content);
4109
                        $di->addChunk($ic_slide);
4110
                        // Index and return search engine document id
4111
                        $did = $di->index();
4112
                        if ($did) {
4113
                            // Save it to db
4114
                            $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
4115
                            $sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, search_did)
4116
                            VALUES (NULL , \'%s\', \'%s\', %s, %s)';
4117
                            $sql = sprintf($sql, $tbl_se_ref, $course_code, TOOL_DOCUMENT, $docid, $did);
4118
                            Database::query($sql);
4119
                        } else {
4120
                            return false;
4121
                        }
4122
                    }
4123
                }
4124
            } else {
4125
                return false;
4126
            }
4127
        }
4128
4129
        return true;
4130
    }
4131
4132
    /**
4133
     * @return array
4134
     */
4135
    public static function get_web_odf_extension_list()
4136
    {
4137
        return ['ods', 'odt', 'odp'];
4138
    }
4139
4140
    /**
4141
     * Set of extension allowed to use Jodconverter.
4142
     *
4143
     * @param $mode 'from'
0 ignored issues
show
Documentation Bug introduced by
The doc comment 'from' at position 0 could not be parsed: Unknown type name ''from'' at position 0 in 'from'.
Loading history...
4144
     *              'to'
4145
     *              'all'
4146
     * @param $format   'text'
4147
     *                  'spreadsheet'
4148
     *                  'presentation'
4149
     *                  'drawing'
4150
     *                  'all'
4151
     *
4152
     * @return array
4153
     */
4154
    public static function getJodconverterExtensionList($mode, $format)
4155
    {
4156
        $extensionList = [];
4157
        $extensionListFromText = [
4158
            'odt',
4159
            'sxw',
4160
            'rtf',
4161
            'doc',
4162
            'docx',
4163
            'wpd',
4164
            'txt',
4165
        ];
4166
        $extensionListToText = [
4167
            'pdf',
4168
            'odt',
4169
            'sxw',
4170
            'rtf',
4171
            'doc',
4172
            'docx',
4173
            'txt',
4174
        ];
4175
        $extensionListFromSpreadsheet = [
4176
            'ods',
4177
            'sxc',
4178
            'xls',
4179
            'xlsx',
4180
            'csv',
4181
            'tsv',
4182
        ];
4183
        $extensionListToSpreadsheet = [
4184
            'pdf',
4185
            'ods',
4186
            'sxc',
4187
            'xls',
4188
            'xlsx',
4189
            'csv',
4190
            'tsv',
4191
        ];
4192
        $extensionListFromPresentation = [
4193
            'odp',
4194
            'sxi',
4195
            'ppt',
4196
            'pptx',
4197
        ];
4198
        $extensionListToPresentation = [
4199
            'pdf',
4200
            'swf',
4201
            'odp',
4202
            'sxi',
4203
            'ppt',
4204
            'pptx',
4205
        ];
4206
        $extensionListFromDrawing = ['odg'];
4207
        $extensionListToDrawing = ['svg', 'swf'];
4208
4209
        if ($mode === 'from') {
4210
            if ($format === 'text') {
4211
                $extensionList = array_merge($extensionList, $extensionListFromText);
4212
            } elseif ($format === 'spreadsheet') {
4213
                $extensionList = array_merge($extensionList, $extensionListFromSpreadsheet);
4214
            } elseif ($format === 'presentation') {
4215
                $extensionList = array_merge($extensionList, $extensionListFromPresentation);
4216
            } elseif ($format === 'drawing') {
4217
                $extensionList = array_merge($extensionList, $extensionListFromDrawing);
4218
            } elseif ($format === 'all') {
4219
                $extensionList = array_merge($extensionList, $extensionListFromText);
4220
                $extensionList = array_merge($extensionList, $extensionListFromSpreadsheet);
4221
                $extensionList = array_merge($extensionList, $extensionListFromPresentation);
4222
                $extensionList = array_merge($extensionList, $extensionListFromDrawing);
4223
            }
4224
        } elseif ($mode === 'to') {
4225
            if ($format === 'text') {
4226
                $extensionList = array_merge($extensionList, $extensionListToText);
4227
            } elseif ($format === 'spreadsheet') {
4228
                $extensionList = array_merge($extensionList, $extensionListToSpreadsheet);
4229
            } elseif ($format === 'presentation') {
4230
                $extensionList = array_merge($extensionList, $extensionListToPresentation);
4231
            } elseif ($format === 'drawing') {
4232
                $extensionList = array_merge($extensionList, $extensionListToDrawing);
4233
            } elseif ($format === 'all') {
4234
                $extensionList = array_merge($extensionList, $extensionListToText);
4235
                $extensionList = array_merge($extensionList, $extensionListToSpreadsheet);
4236
                $extensionList = array_merge($extensionList, $extensionListToPresentation);
4237
                $extensionList = array_merge($extensionList, $extensionListToDrawing);
4238
            }
4239
        } elseif ($mode === 'all') {
4240
            if ($format === 'text') {
4241
                $extensionList = array_merge($extensionList, $extensionListFromText);
4242
                $extensionList = array_merge($extensionList, $extensionListToText);
4243
            } elseif ($format === 'spreadsheet') {
4244
                $extensionList = array_merge($extensionList, $extensionListFromSpreadsheet);
4245
                $extensionList = array_merge($extensionList, $extensionListToSpreadsheet);
4246
            } elseif ($format === 'presentation') {
4247
                $extensionList = array_merge($extensionList, $extensionListFromPresentation);
4248
                $extensionList = array_merge($extensionList, $extensionListToPresentation);
4249
            } elseif ($format === 'drawing') {
4250
                $extensionList = array_merge($extensionList, $extensionListFromDrawing);
4251
                $extensionList = array_merge($extensionList, $extensionListToDrawing);
4252
            } elseif ($format === 'all') {
4253
                $extensionList = array_merge($extensionList, $extensionListFromText);
4254
                $extensionList = array_merge($extensionList, $extensionListToText);
4255
                $extensionList = array_merge($extensionList, $extensionListFromSpreadsheet);
4256
                $extensionList = array_merge($extensionList, $extensionListToSpreadsheet);
4257
                $extensionList = array_merge($extensionList, $extensionListFromPresentation);
4258
                $extensionList = array_merge($extensionList, $extensionListToPresentation);
4259
                $extensionList = array_merge($extensionList, $extensionListFromDrawing);
4260
                $extensionList = array_merge($extensionList, $extensionListToDrawing);
4261
            }
4262
        }
4263
4264
        return $extensionList;
4265
    }
4266
4267
    /**
4268
     * Get Format type list by extension and mode.
4269
     *
4270
     * @param string $mode Mode to search format type list
4271
     *
4272
     * @example 'from'
4273
     * @example 'to'
4274
     *
4275
     * @param string $extension file extension to check file type
4276
     *
4277
     * @return array
4278
     */
4279
    public static function getFormatTypeListConvertor($mode, $extension)
4280
    {
4281
        $formatTypesList = [];
4282
        $formatTypes = ['text', 'spreadsheet', 'presentation', 'drawing'];
4283
        foreach ($formatTypes as $formatType) {
4284
            if (in_array($extension, self::getJodconverterExtensionList($mode, $formatType))) {
4285
                $formatTypesList[] = $formatType;
4286
            }
4287
        }
4288
4289
        return $formatTypesList;
4290
    }
4291
4292
    /**
4293
     * @param string $path
4294
     * @param bool   $is_certificate_mode
4295
     *
4296
     * @return bool
4297
     */
4298
    public static function is_folder_to_avoid($path, $is_certificate_mode = false)
4299
    {
4300
        if (basename($path) == 'css') {
4301
            return true;
4302
        }
4303
4304
        if ($is_certificate_mode == false) {
4305
            //Certificate results
4306
            if (strstr($path, 'certificates')) {
4307
                return true;
4308
            }
4309
        }
4310
4311
        $foldersToAvoid = [
4312
            '/HotPotatoes_files',
4313
            '/certificates',
4314
        ];
4315
        $showSystemFolder = api_get_course_setting('show_system_folders');
4316
4317
        // Admin setting for Hide/Show Default folders to all users
4318
        if (api_get_setting('show_default_folders') == 'false'
4319
            || 2 == $showSystemFolder
4320
        ) {
4321
            $foldersToAvoid[] = '/images';
4322
            $foldersToAvoid[] = '/flash';
4323
            $foldersToAvoid[] = '/audio';
4324
            $foldersToAvoid[] = '/video';
4325
            $foldersToAvoid[] = '/learning_path';
4326
        }
4327
4328
        // Admin setting for Hide/Show the folders of all users
4329
        if (api_get_setting('show_users_folders') == 'false') {
4330
            $foldersToAvoid[] = '/shared_folder';
4331
4332
            if (strstr($path, 'shared_folder_session_')) {
4333
                return true;
4334
            }
4335
        }
4336
4337
        // Admin setting for Hide/Show chat history folder
4338
        if (api_get_setting('show_chat_folder') == 'false') {
4339
            $foldersToAvoid[] = '/chat_files';
4340
        }
4341
4342
        if (is_array($foldersToAvoid)) {
4343
            return in_array($path, $foldersToAvoid);
4344
        } else {
4345
            return false;
4346
        }
4347
    }
4348
4349
    /**
4350
     * @return array
4351
     */
4352
    public static function get_system_folders()
4353
    {
4354
        return [
4355
            '/certificates',
4356
            '/HotPotatoes_files',
4357
            '/chat_files',
4358
            '/images',
4359
            '/flash',
4360
            '/audio',
4361
            '/video',
4362
            '/shared_folder',
4363
            '/learning_path',
4364
        ];
4365
    }
4366
4367
    /**
4368
     * @return array
4369
     */
4370
    public static function getProtectedFolderFromStudent()
4371
    {
4372
        return [
4373
            '/certificates',
4374
            '/HotPotatoes_files',
4375
            '/chat_files',
4376
            '/shared_folder',
4377
            '/learning_path',
4378
        ];
4379
    }
4380
4381
    /**
4382
     * @param array $courseInfo
4383
     *
4384
     * @return string 'visible' or 'invisible' string
4385
     */
4386
    public static function getDocumentDefaultVisibility($courseInfo)
4387
    {
4388
        $settings = api_get_setting('tool_visible_by_default_at_creation');
4389
        $defaultVisibility = 'visible';
4390
4391
        if (isset($settings['documents'])) {
4392
            $portalDefaultVisibility = 'invisible';
4393
            if ($settings['documents'] == 'true') {
4394
                $portalDefaultVisibility = 'visible';
4395
            }
4396
4397
            $defaultVisibility = $portalDefaultVisibility;
4398
        }
4399
4400
        if (api_get_setting('documents_default_visibility_defined_in_course') == 'true') {
4401
            $courseVisibility = api_get_course_setting('documents_default_visibility', $courseInfo);
4402
            if (!empty($courseVisibility) && in_array($courseVisibility, ['visible', 'invisible'])) {
4403
                $defaultVisibility = $courseVisibility;
4404
            }
4405
        }
4406
4407
        return $defaultVisibility;
4408
    }
4409
4410
    /**
4411
     * @param array  $courseInfo
4412
     * @param int    $id         doc id
4413
     * @param string $visibility visible/invisible
4414
     * @param int    $userId
4415
     */
4416
    public static function updateVisibilityFromAllSessions($courseInfo, $id, $visibility, $userId)
4417
    {
4418
        $sessionList = SessionManager::get_session_by_course($courseInfo['real_id']);
4419
4420
        if (!empty($sessionList)) {
4421
            foreach ($sessionList as $session) {
4422
                $sessionId = $session['id'];
4423
                api_item_property_update(
4424
                    $courseInfo,
4425
                    TOOL_DOCUMENT,
4426
                    $id,
4427
                    $visibility,
4428
                    $userId,
4429
                    null,
4430
                    null,
4431
                    null,
4432
                    null,
4433
                    $sessionId
4434
                );
4435
            }
4436
        }
4437
    }
4438
4439
    /**
4440
     * @param string $filePath
4441
     * @param string $path
4442
     * @param array  $courseInfo
4443
     * @param int    $sessionId
4444
     * @param string $whatIfFileExists overwrite|rename
4445
     * @param int    $userId
4446
     * @param int    $groupId
4447
     * @param int    $toUserId
4448
     * @param string $comment
4449
     *
4450
     * @return bool|path
4451
     */
4452
    public static function addFileToDocumentTool(
4453
        $filePath,
4454
        $path,
4455
        $courseInfo,
4456
        $sessionId,
4457
        $userId,
4458
        $whatIfFileExists = 'overwrite',
4459
        $groupId = null,
4460
        $toUserId = null,
4461
        $comment = null
4462
    ) {
4463
        if (!file_exists($filePath)) {
4464
            return false;
4465
        }
4466
4467
        $fileInfo = pathinfo($filePath);
4468
4469
        $file = [
4470
            'name' => $fileInfo['basename'],
4471
            'tmp_name' => $filePath,
4472
            'size' => filesize($filePath),
4473
            'from_file' => true,
4474
        ];
4475
4476
        $course_dir = $courseInfo['path'].'/document';
4477
        $baseWorkDir = api_get_path(SYS_COURSE_PATH).$course_dir;
4478
4479
        $filePath = handle_uploaded_document(
4480
            $courseInfo,
4481
            $file,
4482
            $baseWorkDir,
4483
            $path,
4484
            $userId,
4485
            $groupId,
4486
            $toUserId,
4487
            false,
4488
            $whatIfFileExists,
4489
            false,
4490
            false,
4491
            $comment,
4492
            $sessionId
4493
        );
4494
4495
        if ($filePath) {
4496
            return self::get_document_id(
4497
                $courseInfo,
4498
                $filePath,
4499
                $sessionId
4500
            );
4501
        }
4502
4503
        return false;
4504
    }
4505
4506
    /**
4507
     * Converts wav to mp3 file.
4508
     * Requires the ffmpeg lib. In ubuntu: sudo apt-get install ffmpeg.
4509
     *
4510
     * @param string $wavFile
4511
     * @param bool   $removeWavFileIfSuccess
4512
     *
4513
     * @return bool
4514
     */
4515
    public static function convertWavToMp3($wavFile, $removeWavFileIfSuccess = false)
4516
    {
4517
        if (file_exists($wavFile)) {
4518
            try {
4519
                $ffmpeg = \FFMpeg\FFMpeg::create();
4520
                $video = $ffmpeg->open($wavFile);
4521
4522
                $mp3File = str_replace('wav', 'mp3', $wavFile);
4523
                $result = $video->save(new FFMpeg\Format\Audio\Mp3(), $mp3File);
4524
                if ($result && $removeWavFileIfSuccess) {
4525
                    unlink($wavFile);
4526
                }
4527
4528
                if (file_exists($mp3File)) {
4529
                    return $mp3File;
4530
                }
4531
            } catch (Exception $e) {
4532
                error_log($e->getMessage());
4533
                error_log($e->getPrevious()->getMessage());
4534
            }
4535
        }
4536
4537
        return false;
4538
    }
4539
4540
    /**
4541
     * @param string $documentData     wav document information
4542
     * @param array  $courseInfo
4543
     * @param int    $sessionId
4544
     * @param int    $userId           user that adds the document
4545
     * @param string $whatIfFileExists
4546
     * @param bool   $deleteWavFile
4547
     *
4548
     * @return bool
4549
     */
4550
    public static function addAndConvertWavToMp3(
4551
        $documentData,
4552
        $courseInfo,
4553
        $sessionId,
4554
        $userId,
4555
        $whatIfFileExists = 'overwrite',
4556
        $deleteWavFile = false
4557
    ) {
4558
        if (empty($documentData)) {
4559
            return false;
4560
        }
4561
4562
        if (isset($documentData['absolute_path']) &&
4563
            file_exists($documentData['absolute_path'])
4564
        ) {
4565
            $mp3FilePath = self::convertWavToMp3($documentData['absolute_path']);
4566
4567
            if (!empty($mp3FilePath) && file_exists($mp3FilePath)) {
4568
                $documentId = self::addFileToDocumentTool(
4569
                    $mp3FilePath,
4570
                    dirname($documentData['path']),
4571
                    $courseInfo,
4572
                    $sessionId,
4573
                    $userId,
4574
                    $whatIfFileExists,
4575
                    null,
4576
                    null,
4577
                    $documentData['comment']
4578
                );
4579
4580
                if (!empty($documentId)) {
4581
                    if ($deleteWavFile) {
4582
                        $coursePath = $courseInfo['directory'].'/document';
4583
                        $documentPath = api_get_path(SYS_COURSE_PATH).$coursePath;
4584
                        self::delete_document(
4585
                            $courseInfo,
4586
                            null,
4587
                            $documentPath,
4588
                            $sessionId,
4589
                            $documentData['id']
4590
                        );
4591
                    }
4592
4593
                    return $documentId;
4594
                }
4595
            }
4596
        }
4597
4598
        return false;
4599
    }
4600
4601
    /**
4602
     * Sets.
4603
     *
4604
     * @param string $file         ($document_data['path'])
4605
     * @param string $file_url_sys
4606
     *
4607
     * @return string
4608
     */
4609
    public static function generateAudioTempFile($file, $file_url_sys)
4610
    {
4611
        //make temp audio
4612
        $temp_folder = api_get_path(SYS_ARCHIVE_PATH).'temp/audio';
4613
        if (!file_exists($temp_folder)) {
4614
            @mkdir($temp_folder, api_get_permissions_for_new_directories(), true);
4615
        }
4616
4617
        //make htaccess with allow from all, and file index.html into temp/audio
4618
        $htaccess = api_get_path(SYS_ARCHIVE_PATH).'temp/audio/.htaccess';
4619
        if (!file_exists($htaccess)) {
4620
            $htaccess_content = "order deny,allow\r\nallow from all\r\nOptions -Indexes";
4621
            $fp = @fopen(api_get_path(SYS_ARCHIVE_PATH).'temp/audio/.htaccess', 'w');
4622
            if ($fp) {
4623
                fwrite($fp, $htaccess_content);
4624
                fclose($fp);
4625
            }
4626
        }
4627
4628
        //encript temp name file
4629
        $name_crip = sha1(uniqid()); //encript
4630
        $findext = explode(".", $file);
4631
        $extension = $findext[count($findext) - 1];
4632
        $file_crip = $name_crip.'.'.$extension;
4633
4634
        //copy file to temp/audio directory
4635
        $from_sys = $file_url_sys;
4636
        $to_sys = api_get_path(SYS_ARCHIVE_PATH).'temp/audio/'.$file_crip;
4637
4638
        if (file_exists($from_sys)) {
4639
            copy($from_sys, $to_sys);
4640
        }
4641
4642
        // get file from tmp directory
4643
        Session::write('temp_audio_nanogong', $to_sys);
4644
4645
        return api_get_path(WEB_ARCHIVE_PATH).'temp/audio/'.$file_crip;
4646
    }
4647
4648
    /**
4649
     * Erase temp nanogong audio.
4650
     */
4651
    public static function removeGeneratedAudioTempFile()
4652
    {
4653
        $tempAudio = Session::read('temp_audio_nanogong');
4654
        if (!empty(isset($tempAudio)) && is_file($tempAudio)) {
4655
            unlink($tempAudio);
4656
            Session::erase('temp_audio_nanogong');
4657
        }
4658
    }
4659
4660
    /**
4661
     * Check if the path is used in this course.
4662
     *
4663
     * @param array  $courseInfo
4664
     * @param string $path
4665
     *
4666
     * @return array
4667
     */
4668
    public static function getDocumentByPathInCourse($courseInfo, $path)
4669
    {
4670
        $table = Database::get_course_table(TABLE_DOCUMENT);
4671
        $path = Database::escape_string($path);
4672
        $courseId = $courseInfo['real_id'];
4673
        if (empty($courseId)) {
4674
            return false;
4675
        }
4676
        $sql = "SELECT * FROM $table WHERE c_id = $courseId AND path = '$path'";
4677
        $result = Database::query($sql);
4678
4679
        return Database::store_result($result, 'ASSOC');
4680
    }
4681
4682
    /**
4683
     * @param array $_course
4684
     *
4685
     * @return int
4686
     */
4687
    public static function createDefaultAudioFolder($_course)
4688
    {
4689
        if (!isset($_course['path'])) {
4690
            return false;
4691
        }
4692
4693
        $audioId = null;
4694
        $path = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/';
4695
        if (!is_dir($path.'audio')) {
4696
            mkdir($path.'audio', api_get_permissions_for_new_directories());
4697
            $audioId = add_document($_course, '/audio', 'folder', 0, get_lang('Audio'));
4698
            api_item_property_update(
4699
                $_course,
4700
                TOOL_DOCUMENT,
4701
                $audioId,
4702
                'FolderCreated',
4703
                api_get_user_id(),
4704
                null,
4705
                null,
4706
                null,
4707
                null,
4708
                api_get_session_id()
4709
            );
4710
        }
4711
4712
        return $audioId;
4713
    }
4714
4715
    /**
4716
     * Generate a default certificate for a courses.
4717
     *
4718
     * @todo move to certificate lib
4719
     *
4720
     * @global string $css CSS directory
4721
     * @global string $img_dir image directory
4722
     * @global string $default_course_dir Course directory
4723
     * @global string $js JS directory
4724
     *
4725
     * @param array $courseData     The course info
4726
     * @param bool  $fromBaseCourse
4727
     * @param int   $sessionId
4728
     */
4729
    public static function generateDefaultCertificate(
4730
        $courseData,
4731
        $fromBaseCourse = false,
4732
        $sessionId = 0
4733
    ) {
4734
        if (empty($courseData)) {
4735
            return false;
4736
        }
4737
4738
        global $css, $img_dir, $default_course_dir, $js;
4739
        $codePath = api_get_path(REL_CODE_PATH);
4740
        $dir = '/certificates';
4741
        $comment = null;
4742
        $title = get_lang('DefaultCertificate');
4743
        $fileName = api_replace_dangerous_char($title);
4744
        $filePath = api_get_path(SYS_COURSE_PATH)."{$courseData['directory']}/document$dir";
4745
4746
        if (!is_dir($filePath)) {
4747
            mkdir($filePath, api_get_permissions_for_new_directories());
4748
        }
4749
4750
        $fileFullPath = "$filePath/$fileName.html";
4751
        $fileType = 'file';
4752
        $templateContent = file_get_contents(api_get_path(SYS_CODE_PATH).'gradebook/certificate_template/template.html');
4753
4754
        $search = ['{CSS}', '{IMG_DIR}', '{REL_CODE_PATH}', '{COURSE_DIR}'];
4755
        $replace = [$css.$js, $img_dir, $codePath, $default_course_dir];
4756
4757
        $fileContent = str_replace($search, $replace, $templateContent);
4758
        $saveFilePath = "$dir/$fileName.html";
4759
4760
        if ($fromBaseCourse) {
4761
            $defaultCertificateId = self::get_default_certificate_id(
4762
                $courseData['code'],
4763
                0
4764
            );
4765
            if (!empty($defaultCertificateId)) {
4766
                // We have a certificate from the course base
4767
                $documentData = self::get_document_data_by_id(
4768
                    $defaultCertificateId,
4769
                    $courseData['code'],
4770
                    false,
4771
                    0
4772
                );
4773
4774
                if ($documentData) {
4775
                    $fileContent = file_get_contents($documentData['absolute_path']);
4776
                }
4777
            }
4778
        }
4779
4780
        if (file_exists($fileFullPath) === false) {
4781
            $result = file_put_contents($fileFullPath, $fileContent);
4782
            if ($result) {
4783
                $fileSize = filesize($fileFullPath);
4784
4785
                $documentId = add_document(
4786
                    $courseData,
4787
                    $saveFilePath,
4788
                    $fileType,
4789
                    $fileSize,
4790
                    $title,
4791
                    $comment,
4792
                    0, //$readonly = 0,
4793
                    true, //$save_visibility = true,
4794
                    null, //$group_id = null,
4795
                    $sessionId
4796
                );
4797
4798
                api_item_property_update(
4799
                    $courseData,
4800
                    TOOL_DOCUMENT,
4801
                    $documentId,
4802
                    'DocumentAdded',
4803
                    api_get_user_id(),
4804
                    null,
4805
                    null,
4806
                    null,
4807
                    null,
4808
                    $sessionId
4809
                );
4810
4811
                $defaultCertificateId = self::get_default_certificate_id(
4812
                    $courseData['code'],
4813
                    $sessionId
4814
                );
4815
4816
                if (!isset($defaultCertificateId)) {
4817
                    self::attach_gradebook_certificate(
4818
                        $courseData['code'],
4819
                        $documentId,
4820
                        $sessionId
4821
                    );
4822
                }
4823
            }
4824
        }
4825
    }
4826
4827
    /**
4828
     * Update the document name.
4829
     *
4830
     * @param int    $documentId The document id
4831
     * @param string $newName    The new name
4832
     */
4833
    public static function renameDocument($documentId, $newName)
4834
    {
4835
        $documentId = intval($documentId);
4836
        $newName = Database::escape_string($newName);
4837
        $docuentTable = Database::get_course_table(TABLE_DOCUMENT);
4838
4839
        $values = [
4840
            'title' => $newName,
4841
        ];
4842
4843
        $whereConditions = [
4844
            'id = ?' => $documentId,
4845
        ];
4846
4847
        Database::update($docuentTable, $values, $whereConditions);
4848
    }
4849
4850
    /**
4851
     * Get folder/file suffix.
4852
     *
4853
     * @param array $courseInfo
4854
     * @param int   $sessionId
4855
     * @param int   $groupId
4856
     *
4857
     * @return string
4858
     */
4859
    public static function getDocumentSuffix($courseInfo, $sessionId, $groupId)
4860
    {
4861
        // If no session or group, then no suffix.
4862
        if (empty($sessionId) && empty($groupId)) {
4863
            return '';
4864
        }
4865
4866
        return '__'.intval($sessionId).'__'.intval($groupId);
4867
    }
4868
4869
    /**
4870
     * Fix a document name adding session id and group id
4871
     * Turns picture.jpg -> picture__1__2.jpg
4872
     * Where 1 = session id and 2 group id
4873
     * Of session id and group id are empty then the function returns:
4874
     * picture.jpg ->  picture.jpg.
4875
     *
4876
     * @param string $name       folder or file name
4877
     * @param string $type       'folder' or 'file'
4878
     * @param array  $courseInfo
4879
     * @param int    $sessionId
4880
     * @param int    $groupId
4881
     *
4882
     * @return string
4883
     */
4884
    public static function fixDocumentName($name, $type, $courseInfo, $sessionId, $groupId)
4885
    {
4886
        $suffix = self::getDocumentSuffix($courseInfo, $sessionId, $groupId);
4887
4888
        switch ($type) {
4889
            case 'folder':
4890
                $name = $name.$suffix;
4891
                break;
4892
            case 'file':
4893
                $name = self::addSuffixToFileName($name, $suffix);
4894
                break;
4895
        }
4896
4897
        return $name;
4898
    }
4899
4900
    /**
4901
     * Add a suffix to a file Example:
4902
     * /folder/picture.jpg => to /folder/picture_this.jpg
4903
     * where "_this" is the suffix.
4904
     *
4905
     * @param string $name
4906
     * @param string $suffix
4907
     *
4908
     * @return string
4909
     */
4910
    public static function addSuffixToFileName($name, $suffix)
4911
    {
4912
        $extension = pathinfo($name, PATHINFO_EXTENSION);
4913
        $fileName = pathinfo($name, PATHINFO_FILENAME);
4914
        $dir = pathinfo($name, PATHINFO_DIRNAME);
4915
4916
        if ($dir == '.') {
4917
            $dir = null;
4918
        }
4919
4920
        if (!empty($dir) && $dir != '/') {
4921
            $dir = $dir.'/';
4922
        }
4923
4924
        $name = $dir.$fileName.$suffix.'.'.$extension;
4925
4926
        return $name;
4927
    }
4928
4929
    /**
4930
     * Check if folder exist in the course base or in the session course.
4931
     *
4932
     * @param string $folder     Example: /folder/folder2
4933
     * @param array  $courseInfo
4934
     * @param int    $sessionId
4935
     * @param int    $groupId    group.id
4936
     *
4937
     * @return bool
4938
     */
4939
    public static function folderExists(
4940
        $folder,
4941
        $courseInfo,
4942
        $sessionId,
4943
        $groupId
4944
    ) {
4945
        $courseId = $courseInfo['real_id'];
4946
4947
        if (empty($courseId)) {
4948
            return false;
4949
        }
4950
4951
        $sessionId = (int) $sessionId;
4952
        $folderWithSuffix = self::fixDocumentName(
4953
            $folder,
4954
            'folder',
4955
            $courseInfo,
4956
            $sessionId,
4957
            $groupId
4958
        );
4959
4960
        $folder = Database::escape_string($folder);
4961
        $folderWithSuffix = Database::escape_string($folderWithSuffix);
4962
4963
        // Check if pathname already exists inside document table
4964
        $tbl_document = Database::get_course_table(TABLE_DOCUMENT);
4965
        $sql = "SELECT id, path FROM $tbl_document
4966
                WHERE
4967
                    filetype = 'folder' AND
4968
                    c_id = $courseId AND
4969
                    (path = '$folder' OR path = '$folderWithSuffix') AND
4970
                    (session_id = 0 OR session_id = $sessionId)
4971
        ";
4972
4973
        $rs = Database::query($sql);
4974
        if (Database::num_rows($rs)) {
4975
            return true;
4976
        }
4977
4978
        return false;
4979
    }
4980
4981
    /**
4982
     * Check if file exist in the course base or in the session course.
4983
     *
4984
     * @param string $fileName   Example: /folder/picture.jpg
4985
     * @param array  $courseInfo
4986
     * @param int    $sessionId
4987
     * @param int    $groupId
4988
     *
4989
     * @return bool
4990
     */
4991
    public static function documentExists(
4992
        $fileName,
4993
        $courseInfo,
4994
        $sessionId,
4995
        $groupId
4996
    ) {
4997
        $courseId = $courseInfo['real_id'];
4998
4999
        if (empty($courseId)) {
5000
            return false;
5001
        }
5002
5003
        $sessionId = (int) $sessionId;
5004
        $fileNameEscape = Database::escape_string($fileName);
5005
5006
        $fileNameWithSuffix = self::fixDocumentName(
5007
            $fileName,
5008
            'file',
5009
            $courseInfo,
5010
            $sessionId,
5011
            $groupId
5012
        );
5013
5014
        $fileNameWithSuffix = Database::escape_string($fileNameWithSuffix);
5015
5016
        // Check if pathname already exists inside document table
5017
        $table = Database::get_course_table(TABLE_DOCUMENT);
5018
        $sql = "SELECT id, path FROM $table
5019
                WHERE
5020
                    filetype = 'file' AND
5021
                    c_id = $courseId AND
5022
                    (
5023
                        path = '".$fileNameEscape."' OR
5024
                        path = '$fileNameWithSuffix'
5025
                    ) AND
5026
                    (session_id = 0 OR session_id = $sessionId)
5027
        ";
5028
        $rs = Database::query($sql);
5029
        if (Database::num_rows($rs)) {
5030
            return true;
5031
        }
5032
5033
        return false;
5034
    }
5035
5036
    /**
5037
     * Undo the suffix applied to a file example:
5038
     * turns picture__1__1.jpg to picture.jpg.
5039
     *
5040
     * @param string $name
5041
     * @param int    $courseId
5042
     * @param int    $sessionId
5043
     * @param int    $groupId
5044
     *
5045
     * @return string
5046
     */
5047
    public static function undoFixDocumentName(
5048
        $name,
5049
        $courseId,
5050
        $sessionId,
5051
        $groupId
5052
    ) {
5053
        if (empty($sessionId) && empty($groupId)) {
5054
            return $name;
5055
        }
5056
5057
        $suffix = self::getDocumentSuffix(
5058
            ['real_id' => $courseId],
5059
            $sessionId,
5060
            $groupId
5061
        );
5062
5063
        $name = str_replace($suffix, '', $name);
5064
5065
        return $name;
5066
    }
5067
5068
    /**
5069
     * @param string $path
5070
     * @param string $name
5071
     * @param array  $courseInfo
5072
     * @param int    $sessionId
5073
     * @param int    $groupId
5074
     *
5075
     * @return string
5076
     */
5077
    public static function getUniqueFileName($path, $name, $courseInfo, $sessionId, $groupId)
5078
    {
5079
        $counter = 1;
5080
        $filePath = $path.$name;
5081
        $uniqueName = $name;
5082
        while ($documentExists = self::documentExists(
5083
            $filePath,
5084
            $courseInfo,
5085
            $sessionId,
5086
            $groupId
5087
        )) {
5088
            $uniqueName = self::addSuffixToFileName($name, '_'.$counter);
5089
            $filePath = $path.$uniqueName;
5090
            $counter++;
5091
        }
5092
5093
        return $uniqueName;
5094
    }
5095
5096
    /**
5097
     * Builds the form that enables the user to
5098
     * select a directory to browse/upload in.
5099
     *
5100
     * @param array    An array containing the folders we want to be able to select
5101
     * @param string    The current folder (path inside of the "document" directory, including the prefix "/")
5102
     * @param string    Group directory, if empty, prevents documents to be uploaded
5103
     * (because group documents cannot be uploaded in root)
5104
     * @param bool    Whether to change the renderer (this will add a template <span>
5105
     * to the QuickForm object displaying the form)
5106
     *
5107
     * @return string html form
5108
     */
5109
    public static function build_directory_selector(
5110
        $folders,
5111
        $document_id,
5112
        $group_dir = '',
5113
        $change_renderer = false,
5114
        &$form = null,
5115
        $selectName = 'id',
5116
        $attributes = []
5117
    ) {
5118
        $doc_table = Database::get_course_table(TABLE_DOCUMENT);
5119
        $course_id = api_get_course_int_id();
5120
        $folder_titles = [];
5121
5122
        if (is_array($folders)) {
5123
            $escaped_folders = [];
5124
            foreach ($folders as $key => $val) {
5125
                $escaped_folders[$key] = Database::escape_string($val);
5126
            }
5127
            $folder_sql = implode("','", $escaped_folders);
5128
5129
            $sql = "SELECT path, title
5130
                    FROM $doc_table
5131
                    WHERE
5132
                        filetype = 'folder' AND
5133
                        c_id = $course_id AND
5134
                        path IN ('".$folder_sql."')
5135
                        ORDER BY path";
5136
            $res = Database::query($sql);
5137
            $folder_titles = [];
5138
            while ($obj = Database::fetch_object($res)) {
5139
                $folder_titles[$obj->path] = $obj->title;
5140
            }
5141
            //natcasesort($folder_titles);
5142
        }
5143
5144
        if (empty($form)) {
5145
            $form = new FormValidator('selector', 'GET', api_get_self().'?'.api_get_cidreq());
5146
            $attributes = ['onchange' => 'javascript: document.selector.submit();'];
5147
        }
5148
        $form->addElement('hidden', 'cidReq', api_get_course_id());
5149
        $form->addElement('hidden', 'id_session', api_get_session_id());
5150
        $form->addElement('hidden', 'gidReq', api_get_group_id());
5151
5152
        $parent_select = $form->addSelect(
5153
            $selectName,
5154
            get_lang('CurrentDirectory'),
5155
            '',
5156
            $attributes
5157
        );
5158
5159
        // Group documents cannot be uploaded in the root
5160
        if (empty($group_dir)) {
5161
            $parent_select->addOption(get_lang('Documents'), '/');
5162
5163
            if (is_array($folders)) {
5164
                $foldersSortedByTitles = [];
5165
                foreach ($folders as $folder_id => &$folder) {
5166
                    $selected = ($document_id == $folder_id) ? ' selected="selected"' : '';
5167
                    $path_parts = explode('/', $folder);
5168
                    $folder_titles[$folder] = cut($folder_titles[$folder], 80);
5169
                    $counter = count($path_parts) - 2;
5170
                    if ($counter > 0) {
5171
                        $label = str_repeat('&nbsp;&nbsp;&nbsp;', $counter).' &mdash; '.$folder_titles[$folder];
5172
                    } else {
5173
                        $label = ' &mdash; '.$folder_titles[$folder];
5174
                    }
5175
                    $label = Security::remove_XSS($label);
5176
                    $foldersSortedByTitles[$folder_id] = [
5177
                        'id' => $folder_id,
5178
                        'title' => $folder_titles[$folder],
5179
                        'selected' => $selected,
5180
                        'label' => $label,
5181
                    ];
5182
                }
5183
                foreach ($folders as $id => $title) {
5184
                    $parent_select->addOption(
5185
                        $foldersSortedByTitles[$id]['label'],
5186
                        $foldersSortedByTitles[$id]['id']
5187
                    );
5188
                    if ($foldersSortedByTitles[$id]['selected'] != '') {
5189
                        $parent_select->setSelected($foldersSortedByTitles[$id]['id']);
5190
                    }
5191
                }
5192
            }
5193
        } else {
5194
            if (!empty($folders)) {
5195
                $foldersSortedByTitles = [];
5196
                foreach ($folders as $folder_id => &$folder) {
5197
                    $selected = ($document_id == $folder_id) ? ' selected="selected"' : '';
5198
                    $label = $folder_titles[$folder];
5199
                    if ($folder == $group_dir) {
5200
                        $label = get_lang('Documents');
5201
                    } else {
5202
                        $path_parts = explode('/', str_replace($group_dir, '', $folder));
5203
                        $label = cut($label, 80);
5204
                        $label = str_repeat('&nbsp;&nbsp;&nbsp;', count($path_parts) - 2).' &mdash; '.$label;
5205
                    }
5206
                    $foldersSortedByTitles[$folder_titles[$folder]] = [
5207
                        'id' => $folder_id,
5208
                        'selected' => $selected,
5209
                        'label' => $label,
5210
                    ];
5211
                }
5212
                foreach ($folder_titles as $title) {
5213
                    $parent_select->addOption(
5214
                        $foldersSortedByTitles[$title]['label'],
5215
                        $foldersSortedByTitles[$title]['id']
5216
                    );
5217
                    if ($foldersSortedByTitles[$title]['selected'] != '') {
5218
                        $parent_select->setSelected($foldersSortedByTitles[$title]['id']);
5219
                    }
5220
                }
5221
            }
5222
        }
5223
5224
        return $form->toHtml();
5225
    }
5226
5227
    /**
5228
     * Create a html hyperlink depending on if it's a folder or a file.
5229
     *
5230
     * @param string $documentWebPath
5231
     * @param array  $document_data
5232
     * @param bool   $show_as_icon      - if it is true, only a clickable icon will be shown
5233
     * @param int    $visibility        (1/0)
5234
     * @param int    $counter
5235
     * @param int    $size
5236
     * @param bool   $isAllowedToEdit
5237
     * @param bool   $isCertificateMode
5238
     *
5239
     * @return string url
5240
     */
5241
    public static function create_document_link(
5242
        $documentWebPath,
5243
        $document_data,
5244
        $show_as_icon = false,
5245
        $counter = null,
5246
        $visibility = true,
5247
        $size = 0,
5248
        $isAllowedToEdit = false,
5249
        $isCertificateMode = false
5250
    ) {
5251
        global $dbl_click_id;
5252
        $www = $documentWebPath;
5253
5254
        $secToken = Security::getTokenFromSession();
5255
5256
        $sessionId = api_get_session_id();
5257
        $courseParams = api_get_cidreq();
5258
        $webODFList = self::get_web_odf_extension_list();
5259
5260
        // Get the title or the basename depending on what we're using
5261
        if ($document_data['title'] != '') {
5262
            $title = $document_data['title'];
5263
        } else {
5264
            $title = basename($document_data['path']);
5265
        }
5266
5267
        if (api_get_configuration_value('save_titles_as_html')) {
5268
            $title = strip_tags($title);
5269
        }
5270
5271
        $filetype = $document_data['filetype'];
5272
        $path = $document_data['path'];
5273
        $url_path = urlencode($document_data['path']);
5274
        $basePageUrl = api_get_path(WEB_CODE_PATH).'document/';
5275
        $pageUrl = $basePageUrl.'document.php';
5276
5277
        // Add class="invisible" on invisible files
5278
        $visibility_class = $visibility == false ? ' class="muted"' : '';
5279
        $forcedownload_link = '';
5280
        $forcedownload_icon = '';
5281
        $prevent_multiple_click = '';
5282
        $force_download_html = '';
5283
5284
        if (!$show_as_icon) {
5285
            // Build download link (icon)
5286
            $forcedownload_link = $filetype === 'folder'
5287
                ? $pageUrl.'?'.$courseParams.'&action=downloadfolder&id='.$document_data['id'].'&sec_token='.$secToken
5288
                : $pageUrl.'?'.$courseParams.'&amp;action=download&amp;id='.$document_data['id'].'&sec_token='.$secToken;
5289
            // Folder download or file download?
5290
            $forcedownload_icon = $filetype === 'folder' ? 'save_pack.png' : 'save.png';
5291
            // Prevent multiple clicks on zipped folder download
5292
            $prevent_multiple_click = $filetype === 'folder' ? " onclick=\"javascript: if(typeof clic_$dbl_click_id == 'undefined' || !clic_$dbl_click_id) { clic_$dbl_click_id=true; window.setTimeout('clic_".($dbl_click_id++)."=false;',10000); } else { return false; }\"" : '';
5293
        }
5294
5295
        $target = '_self';
5296
        $is_browser_viewable_file = false;
5297
5298
        if ($filetype === 'file') {
5299
            // Check the extension
5300
            $ext = explode('.', $path);
5301
            $ext = strtolower($ext[count($ext) - 1]);
5302
5303
            // HTML-files an some other types are shown in a frameset by default.
5304
            $is_browser_viewable_file = self::isBrowserViewable($ext);
5305
            if ($is_browser_viewable_file) {
5306
                $url = $basePageUrl.'showinframes.php?'.$courseParams.'&id='.$document_data['id'];
5307
            } else {
5308
                // url-encode for problematic characters (we may not call them dangerous characters...)
5309
                //$path = str_replace('%2F', '/', $url_path).'?'.$courseParams;
5310
                $url = $www.str_replace('%2F', '/', $url_path).'?'.$courseParams;
5311
            }
5312
        } else {
5313
            $url = $pageUrl.'?'.$courseParams.'&id='.$document_data['id'];
5314
        }
5315
5316
        if ($isCertificateMode) {
5317
            $url .= '&certificate=true&selectcat='.(isset($_GET['selectcat']) ? $_GET['selectcat'] : '');
5318
        }
5319
5320
        // The little download icon
5321
        $tooltip_title = $title;
5322
        $tooltip_title_alt = $tooltip_title;
5323
5324
        if ($filetype === 'link') {
5325
            $tooltip_title_alt = $title;
5326
            $url = $document_data['comment'].'" target="_blank';
5327
        }
5328
5329
        if ($path === '/shared_folder') {
5330
            $tooltip_title_alt = get_lang('UserFolders');
5331
        } elseif (strstr($path, 'shared_folder_session_')) {
5332
            $tooltip_title_alt = get_lang('UserFolders').' ('.api_get_session_name(api_get_session_id()).')';
5333
        } elseif (strstr($tooltip_title, 'sf_user_')) {
5334
            $userinfo = api_get_user_info(substr($tooltip_title, 8));
5335
            $tooltip_title_alt = get_lang('UserFolder').' '.$userinfo['complete_name'];
5336
        } elseif ($path == '/chat_files') {
5337
            $tooltip_title_alt = get_lang('ChatFiles');
5338
        } elseif ($path == '/learning_path') {
5339
            $tooltip_title_alt = get_lang('LearningPaths');
5340
        } elseif ($path == '/video') {
5341
            $tooltip_title_alt = get_lang('Video');
5342
        } elseif ($path == '/audio') {
5343
            $tooltip_title_alt = get_lang('Audio');
5344
        } elseif ($path == '/flash') {
5345
            $tooltip_title_alt = get_lang('Flash');
5346
        } elseif ($path == '/images') {
5347
            $tooltip_title_alt = get_lang('Images');
5348
        } elseif ($path == '/images/gallery') {
5349
            $tooltip_title_alt = get_lang('DefaultCourseImages');
5350
        }
5351
5352
        $copyToMyFiles = $open_in_new_window_link = '';
5353
        $curdirpath = isset($_GET['curdirpath']) ? Security::remove_XSS($_GET['curdirpath']) : null;
5354
        $send_to = null;
5355
        $checkExtension = $path;
5356
        $extension = pathinfo($path, PATHINFO_EXTENSION);
5357
        $document_data['file_extension'] = $extension;
5358
5359
        if (!$show_as_icon) {
5360
            // to force download if a document can be downloaded or not
5361
            $hideDownloadIcon = false;
5362
            if (true === api_get_configuration_value('documents_hide_download_icon')) {
5363
                $hideDownloadIcon = true;
5364
            }
5365
            if (self::getHideDownloadIcon($document_data['id'])) {
5366
                $hideDownloadIcon = false;
5367
            }
5368
            if (!$hideDownloadIcon) {
5369
                if ($filetype == 'folder') {
5370
                    if ($isAllowedToEdit ||
5371
                        api_is_platform_admin() ||
5372
                        api_get_setting('students_download_folders') == 'true'
5373
                    ) {
5374
                        // filter: when I am into a shared folder, I can only show "my shared folder" for donwload
5375
                        if (self::is_shared_folder($curdirpath, $sessionId)) {
5376
                            if (preg_match('/shared_folder\/sf_user_'.api_get_user_id().'$/', urldecode($forcedownload_link)) ||
5377
                                preg_match('/shared_folder_session_'.$sessionId.'\/sf_user_'.api_get_user_id().'$/', urldecode($forcedownload_link)) ||
5378
                                $isAllowedToEdit || api_is_platform_admin()
5379
                            ) {
5380
                                $force_download_html = $size == 0 ? '' : '<a href="'.$forcedownload_link.'" style="float:right"'.$prevent_multiple_click.'>'.
5381
                                    Display::return_icon($forcedownload_icon, get_lang('Download'), [], ICON_SIZE_SMALL).'</a>';
5382
                            }
5383
                        } elseif (!preg_match('/shared_folder/', urldecode($forcedownload_link)) ||
5384
                            $isAllowedToEdit ||
5385
                            api_is_platform_admin()
5386
                        ) {
5387
                            $force_download_html = $size == 0 ? '' : '<a href="'.$forcedownload_link.'" style="float:right"'.$prevent_multiple_click.'>'.
5388
                                Display::return_icon($forcedownload_icon, get_lang('Download'), [], ICON_SIZE_SMALL).'</a>';
5389
                        }
5390
                    }
5391
                } else {
5392
                    $force_download_html = $size == 0 ? '' : '<a href="'.$forcedownload_link.'" style="float:right"'.$prevent_multiple_click.' download="'.$document_data['basename'].'">'.
5393
                        Display::return_icon($forcedownload_icon, get_lang('Download'), [], ICON_SIZE_SMALL).'</a>';
5394
                }
5395
            }
5396
5397
            // Copy files to user's myfiles
5398
            if (api_get_setting('allow_my_files') === 'true' &&
5399
                api_get_setting('users_copy_files') === 'true' && api_is_anonymous() === false
5400
            ) {
5401
                $copy_myfiles_link = $filetype === 'file' ? $pageUrl.'?'.$courseParams.'&action=copytomyfiles&id='.$document_data['id'].'&sec_token='.$secToken : api_get_self().'?'.$courseParams.'&sec_token='.$secToken;
5402
                if ($filetype === 'file') {
5403
                    $copyToMyFiles = '<a href="'.$copy_myfiles_link.'" style="float:right"'.$prevent_multiple_click.'>'.
5404
                        Display::return_icon('briefcase.png', get_lang('CopyToMyFiles'), [], ICON_SIZE_SMALL).'&nbsp;&nbsp;</a>';
5405
5406
                    if (api_get_setting('allow_my_files') === 'false') {
5407
                        $copyToMyFiles = '';
5408
                    }
5409
                }
5410
            }
5411
5412
            $pdf_icon = '';
5413
            if (!$isAllowedToEdit &&
5414
                $filetype === 'file' &&
5415
                api_get_setting('students_export2pdf') == 'true' &&
5416
                in_array($extension, ['html', 'htm'])
5417
            ) {
5418
                $pdf_icon = ' <a style="float:right".'.$prevent_multiple_click.' href="'.$pageUrl.'?'.$courseParams.'&action=export_to_pdf&id='.$document_data['id'].'&sec_token='.$secToken.'&curdirpath='.$curdirpath.'">'.
5419
                    Display::return_icon('pdf.png', get_lang('Export2PDF'), [], ICON_SIZE_SMALL).'</a> ';
5420
            }
5421
5422
            if ($is_browser_viewable_file) {
5423
                $open_in_new_window_link = '<a href="'.$www.str_replace('%2F', '/', $url_path).'?'.$courseParams.'" style="float:right"'.$prevent_multiple_click.' target="_blank">'.
5424
                    Display::return_icon('open_in_new_window.png', get_lang('OpenInANewWindow'), [], ICON_SIZE_SMALL).'&nbsp;&nbsp;</a>';
5425
            }
5426
5427
            $hook = HookDocumentItemView::create();
5428
            $hookItemViewTools = $hook->setEventData($document_data)->notifyDocumentItemView();
5429
5430
            $rightTools = implode(
5431
                PHP_EOL,
5432
                [
5433
                    $force_download_html,
5434
                    $send_to,
5435
                    $copyToMyFiles,
5436
                    $open_in_new_window_link,
5437
                    $pdf_icon,
5438
                    $hookItemViewTools ? implode(PHP_EOL, $hookItemViewTools) : '',
5439
                ]
5440
            );
5441
5442
            if ($filetype === 'file') {
5443
                // Sound preview
5444
                if (preg_match('/mp3$/i', urldecode($checkExtension)) ||
5445
                    (preg_match('/wav$/i', urldecode($checkExtension))) ||
5446
                    preg_match('/ogg$/i', urldecode($checkExtension))
5447
                ) {
5448
                    return '<span style="float:left" '.$visibility_class.'>'.
5449
                        $title.
5450
                        '</span>'.$rightTools;
5451
                } elseif (
5452
                    // Show preview
5453
                    preg_match('/swf$/i', urldecode($checkExtension)) ||
5454
                    preg_match('/png$/i', urldecode($checkExtension)) ||
5455
                    preg_match('/gif$/i', urldecode($checkExtension)) ||
5456
                    preg_match('/jpg$/i', urldecode($checkExtension)) ||
5457
                    preg_match('/jpeg$/i', urldecode($checkExtension)) ||
5458
                    preg_match('/bmp$/i', urldecode($checkExtension)) ||
5459
                    preg_match('/svg$/i', urldecode($checkExtension))
5460
                ) {
5461
                    // Simpler version of showinframesmin.php with no headers
5462
                    $url = 'show_content.php?'.$courseParams.'&id='.$document_data['id'];
5463
                    $class = 'ajax';
5464
                    if ($visibility == false) {
5465
                        $class = 'ajax text-muted';
5466
                    }
5467
5468
                    return Display::url(
5469
                            $title,
5470
                            $url,
5471
                            [
5472
                                'class' => $class,
5473
                                'title' => $tooltip_title_alt,
5474
                                'data-title' => $title,
5475
                                'style' => 'float:left;',
5476
                            ]
5477
                        )
5478
                        .$rightTools;
5479
                } else {
5480
                    // For a "PDF Download" of the file.
5481
                    $pdfPreview = null;
5482
                    if ($ext != 'pdf' && !in_array($ext, $webODFList)) {
5483
                        $url = $basePageUrl.'showinframes.php?'.$courseParams.'&id='.$document_data['id'];
5484
                    } else {
5485
                        $pdfPreview = Display::url(
5486
                            Display::return_icon('preview.png', get_lang('Preview'), null, ICON_SIZE_SMALL),
5487
                            api_get_path(WEB_CODE_PATH).'document/showinframes.php?'.$courseParams.'&id='.$document_data['id'],
5488
                            ['style' => 'float:right']
5489
                        );
5490
                    }
5491
                    // No plugin just the old and good showinframes.php page
5492
                    return '<a href="'.$url.'" title="'.$tooltip_title_alt.'" style="float:left" '.$visibility_class.' >'.$title.'</a>'.
5493
                        $pdfPreview.$rightTools;
5494
                }
5495
            } else {
5496
                return '<a href="'.$url.'" title="'.$tooltip_title_alt.'" '.$visibility_class.' style="float:left">'.$title.'</a>'
5497
                    .$rightTools;
5498
            }
5499
            // end copy files to users myfiles
5500
        } else {
5501
            // Icon column
5502
            if (preg_match('/shared_folder/', urldecode($checkExtension)) &&
5503
                preg_match('/shared_folder$/', urldecode($checkExtension)) == false &&
5504
                preg_match('/shared_folder_session_'.$sessionId.'$/', urldecode($url)) == false
5505
            ) {
5506
                if ($filetype == 'file') {
5507
                    //Sound preview
5508
                    if (preg_match('/mp3$/i', urldecode($checkExtension)) ||
5509
                        (preg_match('/wav$/i', urldecode($checkExtension))) ||
5510
                        preg_match('/ogg$/i', urldecode($checkExtension))) {
5511
                        return self::generateAudioPreview($documentWebPath, $document_data);
5512
                    } elseif (
5513
                        // Show preview
5514
                        preg_match('/swf$/i', urldecode($checkExtension)) ||
5515
                        preg_match('/png$/i', urldecode($checkExtension)) ||
5516
                        preg_match('/gif$/i', urldecode($checkExtension)) ||
5517
                        preg_match('/jpg$/i', urldecode($checkExtension)) ||
5518
                        preg_match('/jpeg$/i', urldecode($checkExtension)) ||
5519
                        preg_match('/bmp$/i', urldecode($checkExtension)) ||
5520
                        preg_match('/svg$/i', urldecode($checkExtension))
5521
                    ) {
5522
                        $url = $basePageUrl.'showinframes.php?'.$courseParams.'&id='.$document_data['id'];
5523
5524
                        return '<a href="'.$url.'" title="'.$tooltip_title_alt.'" '.$visibility_class.' style="float:left">'.
5525
                            self::build_document_icon_tag($filetype, $path, $isAllowedToEdit).
5526
                            Display::return_icon('shared.png', get_lang('ResourceShared'), []).
5527
                            '</a>';
5528
                    } else {
5529
                        return '<a href="'.$url.'" title="'.$tooltip_title_alt.'" '.$visibility_class.' style="float:left">'.
5530
                            self::build_document_icon_tag($filetype, $path, $isAllowedToEdit).
5531
                            Display::return_icon('shared.png', get_lang('ResourceShared'), []).
5532
                            '</a>';
5533
                    }
5534
                } else {
5535
                    return '<a href="'.$url.'" title="'.$tooltip_title_alt.'" target="'.$target.'"'.$visibility_class.' style="float:left">'.
5536
                        self::build_document_icon_tag($filetype, $path, $isAllowedToEdit).
5537
                        Display::return_icon('shared.png', get_lang('ResourceShared'), []).
5538
                        '</a>';
5539
                }
5540
            } else {
5541
                if ($filetype === 'file') {
5542
                    // Sound preview with jplayer
5543
                    if (preg_match('/mp3$/i', urldecode($checkExtension)) ||
5544
                        (preg_match('/wav$/i', urldecode($checkExtension))) ||
5545
                        preg_match('/ogg$/i', urldecode($checkExtension))) {
5546
                        return self::generateAudioPreview($documentWebPath, $document_data);
5547
                    } elseif (
5548
                        //Show preview
5549
                        preg_match('/html$/i', urldecode($checkExtension)) ||
5550
                        preg_match('/htm$/i', urldecode($checkExtension)) ||
5551
                        preg_match('/swf$/i', urldecode($checkExtension)) ||
5552
                        preg_match('/png$/i', urldecode($checkExtension)) ||
5553
                        preg_match('/gif$/i', urldecode($checkExtension)) ||
5554
                        preg_match('/jpg$/i', urldecode($checkExtension)) ||
5555
                        preg_match('/jpeg$/i', urldecode($checkExtension)) ||
5556
                        preg_match('/bmp$/i', urldecode($checkExtension)) ||
5557
                        preg_match('/svg$/i', urldecode($checkExtension))
5558
                    ) {
5559
                        $url = $basePageUrl.'showinframes.php?'.$courseParams.'&id='.$document_data['id']; //without preview
5560
5561
                        return '<a href="'.$url.'" title="'.$tooltip_title_alt.'" '.$visibility_class.' style="float:left">'.
5562
                            self::build_document_icon_tag($filetype, $path, $isAllowedToEdit).
5563
                            '</a>';
5564
                    } else {
5565
                        return '<a href="'.$url.'" title="'.$tooltip_title_alt.'" '.$visibility_class.' style="float:left">'.
5566
                            self::build_document_icon_tag($filetype, $path, $isAllowedToEdit).
5567
                            '</a>';
5568
                    }
5569
                } else {
5570
                    return '<a href="'.$url.'" title="'.$tooltip_title_alt.'" target="'.$target.'"'.$visibility_class.' style="float:left">'.
5571
                        self::build_document_icon_tag($filetype, $path, $isAllowedToEdit).
5572
                        '</a>';
5573
                }
5574
            }
5575
        }
5576
    }
5577
5578
    /**
5579
     * Builds an img html tag for the file type.
5580
     *
5581
     * @param string $type            (file/folder)
5582
     * @param string $path
5583
     * @param bool   $isAllowedToEdit
5584
     *
5585
     * @return string img html tag
5586
     */
5587
    public static function build_document_icon_tag($type, $path, $isAllowedToEdit = null)
5588
    {
5589
        $basename = basename($path);
5590
        $sessionId = api_get_session_id();
5591
        if (is_null($isAllowedToEdit)) {
5592
            $isAllowedToEdit = api_is_allowed_to_edit(null, true);
5593
        }
5594
        $user_image = false;
5595
        if ($type == 'file') {
5596
            $icon = choose_image($basename);
5597
            $basename = substr(strrchr($basename, '.'), 1);
5598
        } elseif ($type == 'link') {
5599
            $icon = 'clouddoc.png';
5600
            $basename = get_lang('CloudFileLink');
5601
        } else {
5602
            if ($path == '/shared_folder') {
5603
                $icon = 'folder_users.png';
5604
                if ($isAllowedToEdit) {
5605
                    $basename = get_lang('HelpUsersFolder');
5606
                } else {
5607
                    $basename = get_lang('UserFolders');
5608
                }
5609
            } elseif (strstr($basename, 'sf_user_')) {
5610
                $userInfo = api_get_user_info(substr($basename, 8));
5611
                $icon = $userInfo['avatar_small'];
5612
                $basename = get_lang('UserFolder').' '.$userInfo['complete_name'];
5613
                $user_image = true;
5614
            } elseif (strstr($path, 'shared_folder_session_')) {
5615
                $sessionName = api_get_session_name($sessionId);
5616
                if ($isAllowedToEdit) {
5617
                    $basename = '***('.$sessionName.')*** '.get_lang('HelpUsersFolder');
5618
                } else {
5619
                    $basename = get_lang('UserFolders').' ('.$sessionName.')';
5620
                }
5621
                $icon = 'folder_users.png';
5622
            } else {
5623
                $icon = 'folder_document.png';
5624
5625
                if ($path == '/audio') {
5626
                    $icon = 'folder_audio.png';
5627
                    if ($isAllowedToEdit) {
5628
                        $basename = get_lang('HelpDefaultDirDocuments');
5629
                    } else {
5630
                        $basename = get_lang('Audio');
5631
                    }
5632
                } elseif ($path == '/flash') {
5633
                    $icon = 'folder_flash.png';
5634
                    if ($isAllowedToEdit) {
5635
                        $basename = get_lang('HelpDefaultDirDocuments');
5636
                    } else {
5637
                        $basename = get_lang('Flash');
5638
                    }
5639
                } elseif ($path == '/images') {
5640
                    $icon = 'folder_images.png';
5641
                    if ($isAllowedToEdit) {
5642
                        $basename = get_lang('HelpDefaultDirDocuments');
5643
                    } else {
5644
                        $basename = get_lang('Images');
5645
                    }
5646
                } elseif ($path == '/video') {
5647
                    $icon = 'folder_video.png';
5648
                    if ($isAllowedToEdit) {
5649
                        $basename = get_lang('HelpDefaultDirDocuments');
5650
                    } else {
5651
                        $basename = get_lang('Video');
5652
                    }
5653
                } elseif ($path == '/images/gallery') {
5654
                    $icon = 'folder_gallery.png';
5655
                    if ($isAllowedToEdit) {
5656
                        $basename = get_lang('HelpDefaultDirDocuments');
5657
                    } else {
5658
                        $basename = get_lang('Gallery');
5659
                    }
5660
                } elseif ($path == '/chat_files') {
5661
                    $icon = 'folder_chat.png';
5662
                    if ($isAllowedToEdit) {
5663
                        $basename = get_lang('HelpFolderChat');
5664
                    } else {
5665
                        $basename = get_lang('ChatFiles');
5666
                    }
5667
                } elseif ($path == '/learning_path') {
5668
                    $icon = 'folder_learningpath.png';
5669
                    if ($isAllowedToEdit) {
5670
                        $basename = get_lang('HelpFolderLearningPaths');
5671
                    } else {
5672
                        $basename = get_lang('LearningPaths');
5673
                    }
5674
                }
5675
            }
5676
        }
5677
5678
        if ($user_image) {
5679
            return Display::img($icon, $basename, [], false);
5680
        }
5681
5682
        return Display::return_icon($icon, $basename, [], ICON_SIZE_SMALL);
5683
    }
5684
5685
    /**
5686
     * Creates the row of edit icons for a file/folder.
5687
     *
5688
     * @param array $document_data
5689
     * @param int   $id
5690
     * @param bool  $is_template
5691
     * @param int   $is_read_only
5692
     * @param int   $visibility    (1/0)
5693
     *
5694
     * @return string html img tags with hyperlinks
5695
     */
5696
    public static function build_edit_icons($document_data, $id, $is_template, $is_read_only, $visibility)
5697
    {
5698
        $sessionId = api_get_session_id();
5699
        $courseParams = api_get_cidreq();
5700
        $document_id = $document_data['id'];
5701
        $type = $document_data['filetype'];
5702
        $is_read_only = $document_data['readonly'];
5703
        $path = $document_data['path'];
5704
5705
        $secToken = Security::getTokenFromSession();
5706
5707
        if ($type == 'link') {
5708
            $parent_id = self::get_document_id(
5709
                api_get_course_info(),
5710
                rtrim($path, '/'),
5711
                0
5712
            );
5713
        } else {
5714
            $parent_id = self::get_document_id(
5715
                api_get_course_info(),
5716
                dirname($path),
5717
                0
5718
            );
5719
        }
5720
5721
        if (empty($parent_id) && !empty($sessionId)) {
5722
            $parent_id = self::get_document_id(
5723
                api_get_course_info(),
5724
                dirname($path),
5725
                $sessionId
5726
            );
5727
        }
5728
5729
        $curdirpath = dirname($document_data['path']);
5730
        $is_certificate_mode = self::is_certificate_mode($path);
5731
        $curdirpath = urlencode($curdirpath);
5732
        $extension = pathinfo($path, PATHINFO_EXTENSION);
5733
        //@todo Implement remote support for converter
5734
        $usePpt2lp = api_get_setting('service_ppt2lp', 'active') == 'true' && api_get_setting('service_ppt2lp', 'host') == 'localhost';
5735
        $formatTypeList = self::getFormatTypeListConvertor('from', $extension);
5736
        $formatType = current($formatTypeList);
5737
5738
        // If document is read only *or* we're in a session and the document
5739
        // is from a non-session context, hide the edition capabilities
5740
        $modify_icons = [];
5741
        $modify_icons[] = self::getButtonEdit($is_read_only, $document_data, $extension, $is_certificate_mode);
5742
5743
        $hook = HookDocumentItemAction::create();
5744
        if (!empty($hook)) {
5745
            $hook->setEventData($document_data);
5746
            $data = $hook->notifyDocumentItemAction(HOOK_EVENT_TYPE_PRE);
5747
            if (isset($data['actions'])) {
5748
                foreach ($data['actions'] as $action) {
5749
                    $modify_icons[] = $action;
5750
                }
5751
            }
5752
        }
5753
5754
        $modify_icons[] = self::getButtonMove($is_read_only, $document_data, $is_certificate_mode, $parent_id);
5755
        $modify_icons[] = self::getButtonVisibility(
5756
            $is_read_only,
5757
            $visibility,
5758
            $document_data,
5759
            $is_certificate_mode,
5760
            $parent_id
5761
        );
5762
        $modify_icons[] = self::getButtonDelete(
5763
            $is_read_only,
5764
            $document_data,
5765
            $is_certificate_mode,
5766
            $curdirpath,
5767
            $parent_id
5768
        );
5769
5770
        if (!$is_read_only) {
5771
            // Add action to covert to PDF, will create a new document whit same filename but .pdf extension
5772
            // @TODO: add prompt to select a format target
5773
            if (!in_array($path, self::get_system_folders())) {
5774
                if ($usePpt2lp && $formatType) {
5775
                    $modify_icons[] = Display::url(
5776
                        Display::return_icon('convert.png', get_lang('Convert')),
5777
                        '#',
5778
                        ['class' => 'convertAction', 'data-documentId' => $document_id, 'data-formatType' => $formatType]
5779
                    );
5780
                }
5781
            }
5782
        }
5783
5784
        if ($type == 'file' && ($extension == 'html' || $extension == 'htm')) {
5785
            if ($is_template == 0) {
5786
                if ((isset($_GET['curdirpath']) && $_GET['curdirpath'] != '/certificates') || !isset($_GET['curdirpath'])) {
5787
                    $modify_icons[] = Display::url(
5788
                        Display::return_icon('wizard.png', get_lang('AddAsTemplate')),
5789
                        api_get_self()."?$courseParams&curdirpath=$curdirpath&add_as_template=$id&sec_token=$secToken"
5790
                    );
5791
                }
5792
                if ((isset($_GET['curdirpath']) && $_GET['curdirpath'] == '/certificates') || $is_certificate_mode) {//allow attach certificate to course
5793
                    $visibility_icon_certificate = 'nocertificate';
5794
                    if (self::get_default_certificate_id(api_get_course_id()) == $id) {
5795
                        $visibility_icon_certificate = 'certificate';
5796
                        $certificate = get_lang('DefaultCertificate');
5797
                        $preview = get_lang('PreviewCertificate');
5798
                        $is_preview = true;
5799
                    } else {
5800
                        $is_preview = false;
5801
                        $certificate = get_lang('NoDefaultCertificate');
5802
                    }
5803
                    if (isset($_GET['selectcat'])) {
5804
                        $modify_icons[] = Display::url(
5805
                            Display::return_icon($visibility_icon_certificate.'.png', $certificate),
5806
                            api_get_self()."?$courseParams&curdirpath=$curdirpath&selectcat=".intval($_GET['selectcat'])."&set_certificate=$id&sec_token=$secToken"
5807
                        );
5808
                        if ($is_preview) {
5809
                            $modify_icons[] = Display::url(
5810
                                Display::return_icon('preview_view.png', $preview),
5811
                                api_get_self()."?$courseParams&curdirpath=$curdirpath&set_preview=$id&sec_token=$secToken"
5812
                            );
5813
                        }
5814
                    }
5815
                }
5816
            } else {
5817
                $modify_icons[] = Display::url(
5818
                    Display::return_icon('wizard_na.png', get_lang('RemoveAsTemplate')),
5819
                    api_get_self()."?$courseParams&curdirpath=$curdirpath&remove_as_template=$id&sec_token=$secToken"
5820
                );
5821
            }
5822
5823
            $modify_icons[] = Display::url(
5824
                Display::return_icon('pdf.png', get_lang('Export2PDF')),
5825
                api_get_self()."?$courseParams&action=export_to_pdf&id=$id&curdirpath=$curdirpath&sec_token=$secToken"
5826
            );
5827
        }
5828
        if ($type == 'file') {
5829
            $randomUploadName = md5(uniqid(mt_rand(), true));
5830
            $modify_icons[] = Display::url(
5831
                Display::return_icon('upload_file.png', get_lang('ReplaceFile')),
5832
                "#!",
5833
                [
5834
                    'data-id' => $randomUploadName,
5835
                    'class' => 'removeHiddenFile',
5836
                ]
5837
            );
5838
            $form = new FormValidator(
5839
                'upload',
5840
                'POST',
5841
                api_get_self().'?'.api_get_cidreq()."&sec_token=$secToken",
5842
                '',
5843
                ['enctype' => 'multipart/form-data']
5844
            );
5845
            $form->addElement('html', "<div class='replaceIndividualFile upload_element_".$randomUploadName." hidden'>");
5846
            $form->addElement('hidden', 'id_'.$randomUploadName, $randomUploadName);
5847
            $form->addElement('hidden', 'currentFile', '');
5848
            $form->addElement('hidden', 'currentUrl', api_get_self().'?'.api_get_cidreq().'&id='.$document_id);
5849
            $form->addElement('hidden', 'id_'.$randomUploadName, $document_id);
5850
            $label = '';
5851
            $form->addElement('file', 'file_'.$randomUploadName, [get_lang('File'), $label], 'style="width: 250px" id="user_upload"');
5852
            $form->addButtonSend(get_lang('SendDocument'), 'submitDocument');
5853
            $form->addProgress('DocumentUpload', 'file');
5854
            $form->addElement('html', '</div>');
5855
5856
            $html = $form->returnForm();
5857
5858
            $modify_icons[] = $html;
5859
        }
5860
5861
        // Specific case to remove action icons for students on files in the Chat conversation history inside a group -refs BT#21165
5862
        if (strpos($document_data['path'], 'chat_files') !== false && $document_data['filetype'] === 'file' && api_is_student()) {
5863
            $modify_icons = [];
5864
        }
5865
5866
        return implode(PHP_EOL, $modify_icons);
5867
    }
5868
5869
    /**
5870
     * @param $folders
5871
     * @param $curdirpath
5872
     * @param $move_file
5873
     * @param string $group_dir
5874
     *
5875
     * @return string
5876
     */
5877
    public static function build_move_to_selector($folders, $curdirpath, $move_file, $group_dir = '')
5878
    {
5879
        $form = new FormValidator('move_to', 'post', api_get_self().'?'.api_get_cidreq());
5880
5881
        // Form title
5882
        $form->addHidden('move_file', $move_file);
5883
5884
        $options = [];
5885
5886
        // Group documents cannot be uploaded in the root
5887
        if ($group_dir == '') {
5888
            if ($curdirpath != '/') {
5889
                $options['/'] = get_lang('Documents');
5890
            }
5891
5892
            if (is_array($folders)) {
5893
                foreach ($folders as &$folder) {
5894
                    // Hide some folders
5895
                    if ($folder == '/HotPotatoes_files' ||
5896
                        $folder == '/certificates' ||
5897
                        basename($folder) == 'css'
5898
                    ) {
5899
                        continue;
5900
                    }
5901
                    // Admin setting for Hide/Show the folders of all users
5902
                    if (api_get_setting('show_users_folders') == 'false' &&
5903
                        (strstr($folder, '/shared_folder') || strstr($folder, 'shared_folder_session_'))
5904
                    ) {
5905
                        continue;
5906
                    }
5907
5908
                    // Admin setting for Hide/Show Default folders to all users
5909
                    if (api_get_setting('show_default_folders') == 'false' &&
5910
                        (
5911
                            $folder == '/images' ||
5912
                            $folder == '/flash' ||
5913
                            $folder == '/audio' ||
5914
                            $folder == '/video' ||
5915
                            strstr($folder, '/images/gallery') ||
5916
                            $folder == '/video/flv'
5917
                        )
5918
                    ) {
5919
                        continue;
5920
                    }
5921
5922
                    // Admin setting for Hide/Show chat history folder
5923
                    if (api_get_setting('show_chat_folder') == 'false' &&
5924
                        $folder == '/chat_files') {
5925
                        continue;
5926
                    }
5927
5928
                    // You cannot move a file to:
5929
                    // 1. current directory
5930
                    // 2. inside the folder you want to move
5931
                    // 3. inside a subfolder of the folder you want to move
5932
                    if (($curdirpath != $folder) &&
5933
                        ($folder != $move_file) &&
5934
                        (substr($folder, 0, strlen($move_file) + 1) != $move_file.'/')
5935
                    ) {
5936
                        // If document title is used, we have to display titles instead of real paths...
5937
                        $path_displayed = self::get_titles_of_path($folder);
5938
                        if (empty($path_displayed)) {
5939
                            $path_displayed = get_lang('Untitled');
5940
                        }
5941
                        $options[$folder] = $path_displayed;
5942
                    }
5943
                }
5944
            }
5945
        } else {
5946
            $firstPath = '';
5947
            foreach ($folders as $folder) {
5948
                if (($curdirpath != $folder) &&
5949
                    ($folder != $move_file) &&
5950
                    (substr($folder, 0, strlen($move_file) + 1) != $move_file.'/')
5951
                ) {
5952
                    // Cannot copy dir into his own subdir
5953
                    $path_displayed = self::get_titles_of_path($folder);
5954
                    if ($firstPath == '' && $path_displayed != '') {
5955
                        $firstPath = $path_displayed;
5956
                        $group_dir = $firstPath;
5957
                    }
5958
                    $display_folder = substr($path_displayed, strlen($group_dir));
5959
                    if ($display_folder == '') {
5960
                        $display_folder = get_lang('Documents');
5961
                    }
5962
                    $options[$folder] = $display_folder;
5963
                }
5964
            }
5965
        }
5966
        $form->addElement('select', 'move_to', get_lang('MoveTo'), $options);
5967
        $form->addButtonNext(get_lang('MoveElement'), 'move_file_submit');
5968
5969
        return $form->returnForm();
5970
    }
5971
5972
    /**
5973
     * Gets the path translated with title of docs and folders.
5974
     *
5975
     * @param string $path the real path
5976
     *
5977
     * @return the path which should be displayed
5978
     */
5979
    public static function get_titles_of_path($path)
5980
    {
5981
        global $tmp_folders_titles;
5982
        $course_id = api_get_course_int_id();
5983
        $nb_slashes = substr_count($path, '/');
5984
        $current_slash_pos = 0;
5985
        $path_displayed = '';
5986
        for ($i = 0; $i < $nb_slashes; $i++) {
5987
            // For each folder of the path, retrieve title.
5988
            $current_slash_pos = strpos($path, '/', $current_slash_pos + 1);
5989
            $tmp_path = substr($path, strpos($path, '/', 0), $current_slash_pos);
5990
5991
            if (empty($tmp_path)) {
5992
                // If empty, then we are in the final part of the path
5993
                $tmp_path = $path;
5994
            }
5995
5996
            if (!empty($tmp_folders_titles[$tmp_path])) {
5997
                // If this path has soon been stored here we don't need a new query
5998
                $path_displayed .= $tmp_folders_titles[$tmp_path];
5999
            } else {
6000
                $sql = 'SELECT title FROM '.Database::get_course_table(TABLE_DOCUMENT).'
6001
                        WHERE c_id = '.$course_id.' AND path LIKE BINARY "'.$tmp_path.'"';
6002
                $rs = Database::query($sql);
6003
                $tmp_title = '/'.Database::result($rs, 0, 0);
6004
                $path_displayed .= $tmp_title;
6005
                $tmp_folders_titles[$tmp_path] = $tmp_title;
6006
            }
6007
        }
6008
6009
        return $path_displayed;
6010
    }
6011
6012
    /**
6013
     * Creates form that asks for the directory name.
6014
     *
6015
     * @return string html-output text for the form
6016
     */
6017
    public static function create_dir_form($dirId)
6018
    {
6019
        global $document_id;
6020
        $form = new FormValidator('create_dir_form', 'post', api_get_self().'?'.api_get_cidreq());
6021
        $form->addElement('hidden', 'create_dir', 1);
6022
        $form->addElement('hidden', 'dir_id', intval($document_id));
6023
        $form->addElement('hidden', 'id', intval($dirId));
6024
        $form->addElement('header', get_lang('CreateDir'));
6025
        $form->addText('dirname', get_lang('NewDir'), ['autofocus' => 'autofocus']);
6026
        $form->addButtonCreate(get_lang('CreateFolder'));
6027
6028
        return $form->returnForm();
6029
    }
6030
6031
    /**
6032
     * Checks whether the user is in shared folder.
6033
     *
6034
     * @param string $curdirpath
6035
     * @param int    $sessionId
6036
     *
6037
     * @return bool Return true when user is into shared folder
6038
     */
6039
    public static function is_shared_folder($curdirpath, $sessionId)
6040
    {
6041
        $clean_curdirpath = Security::remove_XSS($curdirpath);
6042
        if ($clean_curdirpath == '/shared_folder') {
6043
            return true;
6044
        } elseif ($clean_curdirpath == '/shared_folder_session_'.$sessionId) {
6045
            return true;
6046
        }
6047
6048
        return false;
6049
    }
6050
6051
    /**
6052
     * Checks whether the user is into any user shared folder.
6053
     *
6054
     * @param string $path
6055
     * @param int    $sessionId
6056
     *
6057
     * @return bool Return true when user is in any user shared folder
6058
     */
6059
    public static function is_any_user_shared_folder($path, $sessionId)
6060
    {
6061
        $clean_path = Security::remove_XSS($path);
6062
        if (strpos($clean_path, 'shared_folder/sf_user_')) {
6063
            return true;
6064
        } elseif (strpos($clean_path, 'shared_folder_session_'.$sessionId.'/sf_user_')) {
6065
            return true;
6066
        }
6067
6068
        return false;
6069
    }
6070
6071
    /**
6072
     * Create users shared folder for course.
6073
     *
6074
     * @param int $userId
6075
     * @param int $sessionId
6076
     */
6077
    public static function createUserSharedFolder($userId, array $courseInfo, $sessionId = 0)
6078
    {
6079
        $documentDirectory = api_get_path(SYS_COURSE_PATH).$courseInfo['directory'].'/document';
6080
        $userInfo = api_get_user_info($userId);
6081
6082
        if (!$sessionId) {
6083
            //Create shared folder. Necessary for recycled courses.
6084
            if (!file_exists($documentDirectory.'/shared_folder')) {
6085
                create_unexisting_directory(
6086
                    $courseInfo,
6087
                    $userId,
6088
                    0,
6089
                    0,
6090
                    0,
6091
                    $documentDirectory,
6092
                    '/shared_folder',
6093
                    get_lang('UserFolders'),
6094
                    0,
6095
                    false,
6096
                    false
6097
                );
6098
            }
6099
            // Create dynamic user shared folder
6100
            if (!file_exists($documentDirectory.'/shared_folder/sf_user_'.$userId)) {
6101
                create_unexisting_directory(
6102
                    $courseInfo,
6103
                    $userId,
6104
                    0,
6105
                    0,
6106
                    0,
6107
                    $documentDirectory,
6108
                    '/shared_folder/sf_user_'.$userId,
6109
                    $userInfo['complete_name'],
6110
                    1,
6111
                    false,
6112
                    false
6113
                );
6114
            }
6115
6116
            return;
6117
        }
6118
6119
        // Create shared folder session.
6120
        if (!file_exists($documentDirectory.'/shared_folder_session_'.$sessionId)) {
6121
            create_unexisting_directory(
6122
                $courseInfo,
6123
                api_get_user_id(),
6124
                $sessionId,
6125
                0,
6126
                0,
6127
                $documentDirectory,
6128
                '/shared_folder_session_'.$sessionId,
6129
                get_lang('UserFolders').' ('.api_get_session_name($sessionId).')',
6130
                0,
6131
                false,
6132
                false
6133
            );
6134
        }
6135
        //Create dynamic user shared folder into a shared folder session
6136
        if (!file_exists($documentDirectory.'/shared_folder_session_'.$sessionId.'/sf_user_'.$userId)) {
6137
            create_unexisting_directory(
6138
                $courseInfo,
6139
                $userId,
6140
                $sessionId,
6141
                0,
6142
                0,
6143
                $documentDirectory,
6144
                '/shared_folder_session_'.$sessionId.'/sf_user_'.$userId,
6145
                $userInfo['complete_name'].'('.api_get_session_name($sessionId).')',
6146
                1,
6147
                false,
6148
                false
6149
            );
6150
        }
6151
    }
6152
6153
    /**
6154
     * Checks whether the user is into his shared folder or into a subfolder.
6155
     *
6156
     * @param int    $user_id
6157
     * @param string $path
6158
     * @param int    $sessionId
6159
     *
6160
     * @return bool Return true when user is in his user shared folder or into a subfolder
6161
     */
6162
    public static function is_my_shared_folder($user_id, $path, $sessionId)
6163
    {
6164
        $clean_path = Security::remove_XSS($path).'/';
6165
        $user_id = (int) $user_id;
6166
        //for security does not remove the last slash
6167
        $main_user_shared_folder = '/shared_folder\/sf_user_'.$user_id.'\//';
6168
        //for security does not remove the last slash
6169
        $main_user_shared_folder_session = '/shared_folder_session_'.$sessionId.'\/sf_user_'.$user_id.'\//';
6170
6171
        if (preg_match($main_user_shared_folder, $clean_path)) {
6172
            return true;
6173
        } elseif (preg_match($main_user_shared_folder_session, $clean_path)) {
6174
            return true;
6175
        } else {
6176
            return false;
6177
        }
6178
    }
6179
6180
    public static function isBasicCourseFolder($path, $sessionId)
6181
    {
6182
        $cleanPath = Security::remove_XSS($path);
6183
        $basicCourseFolder = '/basic-course-documents__'.$sessionId.'__0';
6184
6185
        return $cleanPath == $basicCourseFolder;
6186
    }
6187
6188
    /**
6189
     * Check if the file name or folder searched exist.
6190
     *
6191
     * @return bool Return true when exist
6192
     */
6193
    public static function searchKeyword($name, $keyword)
6194
    {
6195
        if (api_strripos($name, $keyword) !== false) {
6196
            return true;
6197
        }
6198
6199
        return false;
6200
    }
6201
6202
    /**
6203
     * Checks whether a document can be previewed by using the browser.
6204
     *
6205
     * @param string $file_extension the filename extension of the document (it must be in lower case)
6206
     *
6207
     * @return bool returns TRUE or FALSE
6208
     */
6209
    public static function isBrowserViewable($file_extension)
6210
    {
6211
        static $allowed_extensions = [
6212
            'htm', 'html', 'xhtml',
6213
            'gif', 'jpg', 'jpeg', 'png', 'tif', 'tiff',
6214
            'pdf', 'svg', 'swf',
6215
            'txt', 'log',
6216
            'mp4', 'ogg', 'ogv', 'ogx', 'mpg', 'mpeg', 'mov', 'avi', 'webm', 'wmv',
6217
            'mp3', 'oga', 'wav', 'au', 'wma', 'mid', 'kar',
6218
        ];
6219
6220
        /*
6221
          //TODO: make a admin switch to strict mode
6222
          1. global default $allowed_extensions
6223
          if (in_array($file_extension, $allowed_extensions)) { // Assignment + a logical check.
6224
          return true;
6225
          }
6226
          2. check native support
6227
          3. check plugins: quicktime, mediaplayer, vlc, acrobat, flash, java
6228
         */
6229
6230
        if (!($result = in_array($file_extension, $allowed_extensions))) {
6231
            // Assignment + a logical check.
6232
            return false;
6233
        }
6234
6235
        //check native support (Explorer, Opera, Firefox, Chrome, Safari)
6236
        if ($file_extension == "pdf") {
6237
            return api_browser_support('pdf');
6238
        } elseif ($file_extension == "mp3") {
6239
            return api_browser_support('mp3');
6240
        } elseif ($file_extension == "mp4") {
6241
            return api_browser_support('mp4');
6242
        } elseif ($file_extension == "ogg" || $file_extension == "ogx" || $file_extension == "ogv" || $file_extension == "oga") {
6243
            return api_browser_support('ogg');
6244
        } elseif ($file_extension == "svg") {
6245
            return api_browser_support('svg');
6246
        } elseif ($file_extension == "mpg" || $file_extension == "mpeg") {
6247
            return api_browser_support('mpg');
6248
        } elseif ($file_extension == "mov") {
6249
            return api_browser_support('mov');
6250
        } elseif ($file_extension == "wav") {
6251
            return api_browser_support('wav');
6252
        } elseif ($file_extension == "mid" || $file_extension == "kar") {
6253
            return api_browser_support('mid');
6254
        } elseif ($file_extension == "avi") {
6255
            return api_browser_support('avi');
6256
        } elseif ($file_extension == "wma") {
6257
            return api_browser_support('wma');
6258
        } elseif ($file_extension == "wmv") {
6259
            return api_browser_support('wmv');
6260
        } elseif ($file_extension == "tif" || $file_extension == "tiff") {
6261
            return api_browser_support('tif');
6262
        } elseif ($file_extension == "mov") {
6263
            return api_browser_support('mov');
6264
        } elseif ($file_extension == "au") {
6265
            return api_browser_support('au');
6266
        } elseif ($file_extension == "webm") {
6267
            return api_browser_support('webm');
6268
        }
6269
6270
        return $result;
6271
    }
6272
6273
    /**
6274
     * @param array $courseInfo
6275
     * @param int   $sessionId
6276
     *
6277
     * @return array
6278
     */
6279
    public static function getDeletedDocuments($courseInfo, $sessionId = 0)
6280
    {
6281
        $table = Database::get_course_table(TABLE_DOCUMENT);
6282
        $courseId = $courseInfo['real_id'];
6283
        $sessionCondition = api_get_session_condition($sessionId);
6284
        $sql = "SELECT * FROM $table
6285
                WHERE
6286
                  path LIKE '%DELETED%' AND
6287
                  c_id = $courseId
6288
                  $sessionCondition
6289
                ORDER BY path
6290
        ";
6291
6292
        $result = Database::query($sql);
6293
        $files = [];
6294
        while ($document = Database::fetch_array($result, 'ASSOC')) {
6295
            $files[] = $document;
6296
        }
6297
6298
        return $files;
6299
    }
6300
6301
    /**
6302
     * @param int   $id
6303
     * @param array $courseInfo
6304
     * @param int   $sessionId
6305
     *
6306
     * @return array
6307
     */
6308
    public static function getDeletedDocument($id, $courseInfo, $sessionId = 0)
6309
    {
6310
        if (empty($courseInfo)) {
6311
            return false;
6312
        }
6313
6314
        $table = Database::get_course_table(TABLE_DOCUMENT);
6315
        $courseId = $courseInfo['real_id'];
6316
        $id = (int) $id;
6317
        $sessionCondition = api_get_session_condition($sessionId);
6318
        $sql = "SELECT * FROM $table
6319
                WHERE
6320
                  path LIKE '%DELETED%' AND
6321
                  id = $id AND
6322
                  c_id = $courseId
6323
                  $sessionCondition
6324
                LIMIT 1
6325
        ";
6326
        $result = Database::query($sql);
6327
        if (Database::num_rows($result)) {
6328
            $result = Database::fetch_array($result, 'ASSOC');
6329
6330
            return $result;
6331
        }
6332
6333
        return [];
6334
    }
6335
6336
    /**
6337
     * @param int   $id
6338
     * @param array $courseInfo
6339
     * @param int   $sessionId
6340
     *
6341
     * @return bool
6342
     */
6343
    public static function purgeDocument($id, $courseInfo, $sessionId = 0)
6344
    {
6345
        $document = self::getDeletedDocument($id, $courseInfo, $sessionId);
6346
        if (!empty($document)) {
6347
            $path = $document['path'];
6348
            $coursePath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/';
6349
            my_delete($coursePath.$path);
6350
            // Hard delete.
6351
            self::deleteDocumentFromDb($id, $courseInfo, $sessionId, true);
6352
6353
            return true;
6354
        }
6355
6356
        return false;
6357
    }
6358
6359
    /**
6360
     * @param array $courseInfo
6361
     * @param int   $sessionId
6362
     */
6363
    public static function purgeDocuments($courseInfo, $sessionId)
6364
    {
6365
        $files = self::getDeletedDocuments($courseInfo, $sessionId);
6366
        foreach ($files as $file) {
6367
            self::purgeDocument($file['id'], $courseInfo, $sessionId);
6368
        }
6369
    }
6370
6371
    /**
6372
     * @param int   $id
6373
     * @param array $courseInfo
6374
     * @param int   $sessionId
6375
     */
6376
    public static function downloadDeletedDocument($id, $courseInfo, $sessionId)
6377
    {
6378
        $document = self::getDeletedDocument($id, $courseInfo, $sessionId);
6379
        if (!empty($document)) {
6380
            $coursePath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/';
6381
6382
            if (Security::check_abs_path($coursePath.$document['path'], $coursePath)) {
6383
                self::file_send_for_download($coursePath.$document['path'], true);
6384
                exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
6385
            }
6386
        }
6387
    }
6388
6389
    /**
6390
     * @param array $courseInfo
6391
     * @param int   $sessionId
6392
     *
6393
     * @return bool
6394
     */
6395
    public static function downloadAllDeletedDocument($courseInfo, $sessionId)
6396
    {
6397
        $files = self::getDeletedDocuments($courseInfo, $sessionId);
6398
6399
        if (empty($files)) {
6400
            return false;
6401
        }
6402
6403
        $coursePath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document';
6404
6405
        // Creating a ZIP file.
6406
        $tempZipFile = api_get_path(SYS_ARCHIVE_PATH).api_get_unique_id().'.zip';
6407
        $zip = new PclZip($tempZipFile);
6408
        foreach ($files as $file) {
6409
            $zip->add(
6410
                $coursePath.$file['path'],
6411
                PCLZIP_OPT_REMOVE_PATH,
6412
                $coursePath
6413
            );
6414
        }
6415
6416
        if (Security::check_abs_path($tempZipFile, api_get_path(SYS_ARCHIVE_PATH))) {
6417
            self::file_send_for_download($tempZipFile, true);
6418
            @unlink($tempZipFile);
6419
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
6420
        }
6421
    }
6422
6423
    /**
6424
     * Delete documents from a session in a course.
6425
     *
6426
     * @param array $courseInfo
6427
     * @param int   $sessionId
6428
     *
6429
     * @return bool
6430
     */
6431
    public static function deleteDocumentsFromSession($courseInfo, $sessionId)
6432
    {
6433
        if (empty($courseInfo)) {
6434
            return false;
6435
        }
6436
6437
        if (empty($sessionId)) {
6438
            return false;
6439
        }
6440
6441
        $itemPropertyTable = Database::get_course_table(TABLE_ITEM_PROPERTY);
6442
        $documentTable = Database::get_course_table(TABLE_DOCUMENT);
6443
6444
        $conditionSession = api_get_session_condition($sessionId, true, false, 'd.session_id');
6445
        $courseId = $courseInfo['real_id'];
6446
6447
        // get invisible folders
6448
        $sql = "SELECT DISTINCT d.id, path
6449
                FROM $itemPropertyTable i
6450
                INNER JOIN $documentTable d
6451
                ON (i.c_id = d.c_id)
6452
                WHERE
6453
                    d.id = i.ref AND
6454
                    i.tool = '".TOOL_DOCUMENT."'
6455
                    $conditionSession AND
6456
                    i.c_id = $courseId AND
6457
                    d.c_id = $courseId ";
6458
6459
        $result = Database::query($sql);
6460
        $documents = Database::store_result($result, 'ASSOC');
6461
        if ($documents) {
6462
            $course_dir = $courseInfo['directory'].'/document';
6463
            $sys_course_path = api_get_path(SYS_COURSE_PATH);
6464
            $base_work_dir = $sys_course_path.$course_dir;
6465
6466
            foreach ($documents as $document) {
6467
                $documentId = $document['id'];
6468
                self::delete_document(
6469
                    $courseInfo,
6470
                    null,
6471
                    $base_work_dir,
6472
                    $sessionId,
6473
                    $documentId
6474
                );
6475
            }
6476
        }
6477
6478
        $sql = "DELETE FROM $documentTable
6479
                WHERE c_id = $courseId AND session_id = $sessionId";
6480
        Database::query($sql);
6481
6482
        $sql = "DELETE FROM $itemPropertyTable
6483
                WHERE c_id = $courseId AND session_id = $sessionId AND tool = '".TOOL_DOCUMENT."'";
6484
        Database::query($sql);
6485
    }
6486
6487
    /**
6488
     * Update the file or directory path in the document db document table.
6489
     *
6490
     * @author - Hugues Peeters <[email protected]>
6491
     *
6492
     * @param string $action     - action type require : 'delete' or 'update'
6493
     * @param string $old_path   - old path info stored to change
6494
     * @param string $new_path   - new path info to substitute
6495
     * @param int    $documentId - iid of specific document
6496
     *
6497
     * @desc Update the file or directory path in the document db document table
6498
     */
6499
    public static function updateDbInfo($action, $old_path, $new_path = '', $documentId = 0)
6500
    {
6501
        $documentId = (int) $documentId;
6502
        $dbTable = Database::get_course_table(TABLE_DOCUMENT);
6503
        $course_id = api_get_course_int_id();
6504
        $old_path = Database::escape_string($old_path);
6505
        switch ($action) {
6506
            case 'delete':
6507
                $query = "DELETE FROM $dbTable
6508
                          WHERE
6509
                            c_id = $course_id AND
6510
                            (
6511
                                path LIKE BINARY '".$old_path."' OR
6512
                                path LIKE BINARY '".$old_path."/%'
6513
                            )";
6514
                Database::query($query);
6515
                break;
6516
            case 'update':
6517
                if ($new_path[0] == '.') {
6518
                    $new_path = substr($new_path, 1);
6519
                }
6520
                $new_path = str_replace('//', '/', $new_path);
6521
6522
                // Attempt to update	- tested & working for root	dir
6523
                $new_path = Database::escape_string($new_path);
6524
                $query = "UPDATE $dbTable SET
6525
                            path = CONCAT('".$new_path."', SUBSTRING(path, LENGTH('".$old_path."')+1) )
6526
                          WHERE
6527
                                c_id = $course_id AND
6528
                                (path LIKE BINARY '".$old_path."' OR path LIKE BINARY '".$old_path."/%')";
6529
                if ($documentId != 0) {
6530
                    $query .= " AND iid = $documentId";
6531
                }
6532
                Database::query($query);
6533
                break;
6534
        }
6535
    }
6536
6537
    /**
6538
     * This function calculates the resized width and resized heigt
6539
     * according to the source and target widths
6540
     * and heights, height so that no distortions occur
6541
     * parameters.
6542
     *
6543
     * @param $image = the absolute path to the image
0 ignored issues
show
Documentation Bug introduced by
The doc comment = at position 0 could not be parsed: Unknown type name '=' at position 0 in =.
Loading history...
6544
     * @param $target_width = how large do you want your resized image
6545
     * @param $target_height = how large do you want your resized image
6546
     * @param $slideshow (default=0) =
6547
     *      indicates weither we are generating images for a slideshow or not,
6548
     *		this overrides the $_SESSION["image_resizing"] a bit so that a thumbnail
6549
     *	    view is also possible when you choose not to resize the source images
6550
     *
6551
     * @return array
6552
     */
6553
    public static function resizeImageSlideShow(
6554
        $image,
6555
        $target_width,
6556
        $target_height,
6557
        $slideshow = 0
6558
    ) {
6559
        // Modifications by Ivan Tcholakov, 04-MAY-2009.
6560
        $result = [];
6561
        $imageResize = Session::read('image_resizing');
6562
        if ($imageResize == 'resizing' || $slideshow == 1) {
6563
            $new_sizes = api_resize_image($image, $target_width, $target_height);
6564
            $result[] = $new_sizes['height'];
6565
            $result[] = $new_sizes['width'];
6566
        } else {
6567
            $size = api_getimagesize($image);
6568
            $result[] = $size['height'];
6569
            $result[] = $size['width'];
6570
        }
6571
6572
        return $result;
6573
    }
6574
6575
    /**
6576
     * Calculates the total size of a directory by adding the sizes (that
6577
     * are stored in the database) of all files & folders in this directory.
6578
     *
6579
     * @param string $value           Document path or document id
6580
     * @param bool   $canSeeInvisible
6581
     * @param bool   $byId            Default true, if is getting size by document id or false if getting by path
6582
     *
6583
     * @return int Total size
6584
     */
6585
    public static function getTotalFolderSize($value, $canSeeInvisible = false, $byId = true)
6586
    {
6587
        $table_itemproperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
6588
        $table_document = Database::get_course_table(TABLE_DOCUMENT);
6589
        $tool_document = TOOL_DOCUMENT;
6590
6591
        $course_id = api_get_course_int_id();
6592
        $session_id = api_get_session_id();
6593
        $session_condition = api_get_session_condition(
6594
            $session_id,
6595
            true,
6596
            true,
6597
            'props.session_id'
6598
        );
6599
6600
        if (empty($course_id)) {
6601
            return 0;
6602
        }
6603
6604
        $visibility_rule = ' props.visibility '.($canSeeInvisible ? '<> 2' : '= 1');
6605
6606
        if ($byId) {
6607
            $id = (int) $value;
6608
            $query = "SELECT path FROM $table_document WHERE id = $id";
6609
            $result1 = Database::query($query);
6610
            if ($result1 && Database::num_rows($result1) != 0) {
6611
                $row = Database::fetch_row($result1);
6612
                $path = $row[0];
6613
            } else {
6614
                return 0;
6615
            }
6616
        } else {
6617
            $path = Database::escape_string($value);
6618
        }
6619
6620
        $sql = "SELECT SUM(table1.size) FROM (
6621
                SELECT props.ref, size
6622
                FROM $table_itemproperty AS props
6623
                INNER JOIN $table_document AS docs
6624
                ON (docs.id = props.ref AND docs.c_id = props.c_id)
6625
                WHERE
6626
                    docs.c_id = $course_id AND
6627
                    docs.path LIKE '$path/%' AND
6628
                    props.c_id = $course_id AND
6629
                    props.tool = '$tool_document' AND
6630
                    $visibility_rule
6631
                    $session_condition
6632
                GROUP BY ref
6633
            ) as table1";
6634
6635
        $result = Database::query($sql);
6636
        if ($result && Database::num_rows($result) != 0) {
6637
            $row = Database::fetch_row($result);
6638
6639
            return $row[0] == null ? 0 : $row[0];
6640
        } else {
6641
            return 0;
6642
        }
6643
    }
6644
6645
    /**
6646
     * Adds a cloud link to the database.
6647
     *
6648
     * @author - Aquilino Blanco Cores <[email protected]>
6649
     *
6650
     * @param array  $_course
6651
     * @param string $path
6652
     * @param string $url
6653
     * @param string $name
6654
     *
6655
     * @return int id of document or 0 if already exists or there was a problem creating it
6656
     */
6657
    public static function addCloudLink($_course, $path, $url, $name)
6658
    {
6659
        $file_path = $path;
6660
        if (!self::cloudLinkExists($_course, $path, $url)) {
6661
            $doc_id = add_document($_course, $file_path, 'link', 0, $name, $url);
6662
            if ($doc_id) {
6663
                // Update document item_property
6664
                api_item_property_update(
6665
                    $_course,
6666
                    TOOL_DOCUMENT,
6667
                    $doc_id,
6668
                    'DocumentAdded',
6669
                    api_get_user_id(),
6670
                    api_get_group_id(),
6671
                    api_get_user_id(),
6672
                    null,
6673
                    null,
6674
                    api_get_session_id()
6675
                );
6676
            }
6677
6678
            // If the file is in a folder, we need to update all parent folders
6679
            item_property_update_on_folder($_course, $file_path, api_get_user_id());
6680
6681
            return $doc_id;
6682
        } else {
6683
            return 0;
6684
        }
6685
    }
6686
6687
    /**
6688
     * Deletes a cloud link from the database.
6689
     *
6690
     * @author - Aquilino Blanco Cores <[email protected]>
6691
     *
6692
     * @param array  $courseInfo
6693
     * @param string $documentId
6694
     *
6695
     * @return bool true if success / false if an error occurred
6696
     */
6697
    public static function deleteCloudLink($courseInfo, $documentId)
6698
    {
6699
        if (empty($documentId) || empty($courseInfo)) {
6700
            return false;
6701
        }
6702
6703
        $documentId = (int) $documentId;
6704
        $fileDeletedFromDb = false;
6705
        if (!empty($documentId)) {
6706
            self::deleteDocumentFromDb($documentId, $courseInfo, 0, true);
6707
            // checking
6708
            $table = Database::get_course_table(TABLE_DOCUMENT);
6709
            $courseId = $courseInfo['real_id'];
6710
            $sql = "SELECT * FROM $table WHERE id = $documentId AND c_id = $courseId";
6711
            $result = Database::query($sql);
6712
            $exists = Database::num_rows($result) > 0;
6713
            $fileDeletedFromDb = !$exists;
6714
        }
6715
6716
        return $fileDeletedFromDb;
6717
    }
6718
6719
    /**
6720
     * Gets the id of a cloud link with a given path.
6721
     *
6722
     * @author - Aquilino Blanco Cores <[email protected]>
6723
     *
6724
     * @param array  $courseInfo
6725
     * @param string $path
6726
     * @param string $url
6727
     *
6728
     * @return int link's id / false if no link found
6729
     */
6730
    public static function getCloudLinkId($courseInfo, $path, $url)
6731
    {
6732
        $table = Database::get_course_table(TABLE_DOCUMENT);
6733
6734
        if (empty($courseInfo)) {
6735
            return false;
6736
        }
6737
6738
        $courseId = (int) $courseInfo['real_id'];
6739
        $path = Database::escape_string($path);
6740
6741
        if (substr($path, -1) != '/') {
6742
            // Add final slash to path if not present
6743
            $path .= '/';
6744
        }
6745
6746
        if (!empty($courseId) && !empty($path)) {
6747
            $sql = "SELECT id FROM $table
6748
                    WHERE
6749
                        c_id = $courseId AND
6750
                        path LIKE BINARY '$path' AND
6751
                        comment = '$url' AND
6752
                        filetype = 'link'
6753
                    LIMIT 1";
6754
            $result = Database::query($sql);
6755
            if ($result && Database::num_rows($result)) {
6756
                $row = Database::fetch_array($result);
6757
6758
                return intval($row[0]);
6759
            }
6760
        }
6761
6762
        return false;
6763
    }
6764
6765
    /**
6766
     * Checks if a cloud link exists.
6767
     *
6768
     * @author - Aquilino Blanco Cores <[email protected]>
6769
     *
6770
     * @param array  $courseInfo
6771
     * @param string $path
6772
     * @param string $url
6773
     *
6774
     * @return bool true if it exists false in other case
6775
     */
6776
    public static function cloudLinkExists($courseInfo, $path, $url)
6777
    {
6778
        $exists = self::getCloudLinkId($courseInfo, $path, $url);
6779
6780
        return $exists;
6781
    }
6782
6783
    /**
6784
     * Gets the wellformed URLs regular expression in order to use it on forms' verifications.
6785
     *
6786
     * @author Aquilino Blanco Cores <[email protected]>
6787
     *
6788
     * @return string the well formed URLs regular expressions string
6789
     */
6790
    public static function getWellFormedUrlRegex()
6791
    {
6792
        return '/\(?((http|https|ftp):\/\/)(?:((?:[^\W\s]|\.|-|[:]{1})+)@{1})?((?:www.)?(?:[^\W\s]|\.|-)+[\.][^\W\s]{2,4}|localhost(?=\/)|\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})(?::(\d*))?([\/]?[^\s\?]*[\/]{1})*(?:\/?([^\s\n\?\[\]\{\}\#]*(?:(?=\.)){1}|[^\s\n\?\[\]\{\}\.\#]*)?([\.]{1}[^\s\?\#]*)?)?(?:\?{1}([^\s\n\#\[\]]*))?([\#][^\s\n]*)?\)?/i';
6793
    }
6794
6795
    /**
6796
     * Gets the files hosting sites' whitelist.
6797
     *
6798
     * @author Aquilino Blanco Cores <[email protected]>
6799
     *
6800
     * @return array the sites list
6801
     */
6802
    public static function getFileHostingWhiteList()
6803
    {
6804
        $links = api_get_configuration_value('documents_custom_cloud_link_list');
6805
6806
        if (!empty($links) && isset($links['links'])) {
6807
            return $links['links'];
6808
        }
6809
6810
        return [
6811
            'asuswebstorage.com',
6812
            'box.com',
6813
            'dropbox.com',
6814
            'dropboxusercontent.com',
6815
            'docs.google.com',
6816
            'drive.google.com',
6817
            'fileserve.com',
6818
            'icloud.com',
6819
            'livefilestore.com', // OneDrive
6820
            'mediafire.com',
6821
            'mega.nz',
6822
            'onedrive.live.com',
6823
            'scribd.com',
6824
            'slideshare.net',
6825
            'sharepoint.com',
6826
            'wetransfer.com',
6827
        ];
6828
    }
6829
6830
    /**
6831
     * @param int $userId
6832
     *
6833
     * @return array Example [ 0 => ['code' => 'ABC', 'directory' => 'ABC0', 'path' => '/images/gallery/test.png', 'code_path' => 'ABC:/images/gallery/test.png'], 1 => ...]
6834
     */
6835
    public static function getAllDocumentsCreatedByUser($userId)
6836
    {
6837
        $tblItemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
6838
        $tblDocument = Database::get_course_table(TABLE_DOCUMENT);
6839
        $tblCourse = Database::get_main_table(TABLE_MAIN_COURSE);
6840
        $userId = (int) $userId;
6841
6842
        $sql = "SELECT DISTINCT c.code, c.directory, docs.path
6843
                FROM $tblItemProperty AS last
6844
                INNER JOIN $tblDocument AS docs
6845
                ON (
6846
                    docs.id = last.ref AND
6847
                    docs.c_id = last.c_id AND
6848
                    docs.filetype <> 'folder'
6849
                )
6850
                INNER JOIN $tblCourse as c
6851
                ON (
6852
                    docs.c_id = c.id
6853
                )
6854
                WHERE
6855
                    last.tool = '".TOOL_DOCUMENT."' AND
6856
                    last.insert_user_id = $userId AND
6857
                    docs.path NOT LIKE '%_DELETED_%'
6858
                ORDER BY c.directory, docs.path
6859
                ";
6860
        $result = Database::query($sql);
6861
6862
        $list = [];
6863
        if (Database::num_rows($result) != 0) {
6864
            while ($row = Database::fetch_array($result, 'ASSOC')) {
6865
                $row['code_path'] = $row['code'].':'.$row['path'];
6866
                $list[] = $row;
6867
            }
6868
        }
6869
6870
        return $list;
6871
    }
6872
6873
    /**
6874
     * Writes the content of a sent file to an existing one in the system, backing up the previous one.
6875
     *
6876
     * @param array  $_course
6877
     * @param string $path          Path stored in the database
6878
     * @param string $base_work_dir Path to the documents folder (if not defined, $documentId must be used)
6879
     * @param int    $sessionId     The ID of the session, if any
6880
     * @param int    $documentId    The document id, if available
6881
     * @param int    $groupId       iid
6882
     * @param file   $file          $_FILES content
6883
     *
6884
     * @return bool true/false
6885
     */
6886
    public static function writeContentIntoDocument(
6887
        $_course,
6888
        $path = null,
6889
        $base_work_dir = null,
6890
        $sessionId = null,
6891
        $documentId = null,
6892
        $groupId = 0,
6893
        $file = null
6894
    ) {
6895
        $TABLE_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
6896
6897
        $documentId = (int) $documentId;
6898
        $groupId = (int) $groupId;
6899
        if (empty($groupId)) {
6900
            $groupId = api_get_group_id();
6901
        }
6902
6903
        $sessionId = (int) $sessionId;
6904
        if (empty($sessionId)) {
6905
            $sessionId = api_get_session_id();
6906
        }
6907
6908
        $course_id = $_course['real_id'];
6909
6910
        if (empty($course_id)) {
6911
            Display::addFlash(Display::return_message(get_lang('NoCourse'), 'error'));
6912
6913
            return false;
6914
        }
6915
6916
        if (empty($base_work_dir)) {
6917
            Display::addFlash(get_lang('Path'));
6918
6919
            return false;
6920
        }
6921
6922
        if (isset($file) && $file['error'] == 4) {
6923
            //no file
6924
            Display::addFlash(Display::return_message(get_lang('NoArchive'), 'error'));
6925
6926
            return false;
6927
        }
6928
6929
        if (empty($documentId)) {
6930
            $documentId = self::get_document_id($_course, $path, $sessionId);
6931
            $docInfo = self::get_document_data_by_id(
6932
                $documentId,
6933
                $_course['code'],
6934
                false,
6935
                $sessionId
6936
            );
6937
            $path = $docInfo['path'];
6938
        } else {
6939
            $docInfo = self::get_document_data_by_id(
6940
                $documentId,
6941
                $_course['code'],
6942
                false,
6943
                $sessionId
6944
            );
6945
            if (empty($docInfo)) {
6946
                Display::addFlash(Display::return_message(get_lang('ArchiveName'), 'error'));
6947
6948
                return false;
6949
            }
6950
            $path = $docInfo['path'];
6951
        }
6952
6953
        if (empty($path) || empty($docInfo) || empty($documentId)) {
6954
            $str = '';
6955
            $str .= "<br>".get_lang('Path');
6956
            $str .= "<br>".get_lang('ArchiveName');
6957
            $str .= "<br>".get_lang('NoFileSpecified');
6958
            Display::addFlash(Display::return_message($str, 'error'));
6959
6960
            return false;
6961
        }
6962
6963
        $itemInfo = api_get_item_property_info(
6964
            $_course['real_id'],
6965
            TOOL_DOCUMENT,
6966
            $documentId,
6967
            $sessionId,
6968
            $groupId
6969
        );
6970
6971
        if (empty($itemInfo)) {
6972
            Display::addFlash(Display::return_message(get_lang('NoFileSpecified'), 'error'));
6973
6974
            return false;
6975
        }
6976
6977
        // Filtering by group.
6978
        if ($itemInfo['to_group_id'] != $groupId) {
6979
            Display::addFlash(Display::return_message(get_lang("NoGroupsAvailable"), 'error'));
6980
6981
            return false;
6982
        }
6983
        $now = new DateTime();
6984
        $now = $now->format('Y_m_d__H_i_s_');
6985
6986
        $document_exists_in_disk = file_exists($base_work_dir.$path);
6987
        $new_path = $path.'_REPLACED_DATE_'.$now.'_ID_'.$documentId;
6988
6989
        $fileMoved = false;
6990
        $file_renamed_from_disk = false;
6991
6992
        $originalMime = self::file_get_mime_type($base_work_dir.$path);
6993
        $newMime = finfo_file(finfo_open(FILEINFO_MIME_TYPE), $file['tmp_name']);
6994
        if ($originalMime != $newMime) {
6995
            Display::addFlash(Display::return_message(get_lang('FileError'), 'error'));
6996
6997
            return false;
6998
        }
6999
7000
        if ($document_exists_in_disk) {
7001
            // Move old file to xxx_REPLACED_DATE_#date_ID_#id (soft delete)
7002
            if (is_file($base_work_dir.$path) || is_dir($base_work_dir.$path)) {
7003
                if (rename($base_work_dir.$path, $base_work_dir.$new_path)) {
7004
                    $file_renamed_from_disk = true;
7005
                } else {
7006
                    // Couldn't rename - file permissions problem?
7007
                    Display::addFlash(Display::return_message(get_lang('ErrorImportingFile'), 'error'));
7008
                    error_log(
7009
                        __FILE__.' '.__LINE__.': Error renaming '.$base_work_dir.$path.' to '
7010
                        .$base_work_dir.$new_path.'. This is probably due to file permissions',
7011
                        0
7012
                    );
7013
                }
7014
            }
7015
7016
            if (move_uploaded_file($file['tmp_name'], $base_work_dir.$path)) {
7017
                //update file size into db
7018
                $size = filesize($base_work_dir.$path);
7019
                $sql = "UPDATE $TABLE_DOCUMENT
7020
                                SET size = '".$size."'
7021
                                WHERE
7022
                                    c_id = $course_id AND
7023
                                    session_id = $sessionId AND
7024
                                    id = ".$documentId;
7025
                Database::query($sql);
7026
                $fileMoved = true;
7027
            }
7028
        }
7029
        // Checking inconsistency
7030
        if ($fileMoved &&
7031
            $file_renamed_from_disk
7032
        ) {
7033
            return true;
7034
        } else {
7035
            Display::addFlash(Display::return_message(get_lang('ErrorImportingFile'), 'warning'));
7036
            //Something went wrong
7037
            //The file or directory isn't there anymore (on the filesystem)
7038
            // This means it has been removed externally. To prevent a
7039
            // blocking error from happening, we drop the related items from the
7040
            // item_property and the document table.
7041
            error_log(
7042
                __FILE__.' '.__LINE__.': System inconsistency detected. '.
7043
                'The file or directory '.$base_work_dir.$path.
7044
                ' seems to have been removed from the filesystem independently from '.
7045
                'the web platform. To restore consistency, the elements using the same '.
7046
                'path will be removed from the database',
7047
                0
7048
            );
7049
7050
            return false;
7051
        }
7052
    }
7053
7054
    /**
7055
     * It gest extra value to define if download icon is visible or not.
7056
     *
7057
     * @param $documentId
7058
     *
7059
     * @return bool
7060
     */
7061
    public static function getHideDownloadIcon($documentId)
7062
    {
7063
        $extraFieldValue = new ExtraFieldValue('document');
7064
        $extraValue = $extraFieldValue->get_values_by_handler_and_field_variable($documentId, 'can_be_downloaded');
7065
        $canBeDownloadedIcon = false;
7066
        if (!empty($extraValue) && isset($extraValue['value'])) {
7067
            $canBeDownloadedIcon = (bool) $extraValue['value'];
7068
        }
7069
7070
        return $canBeDownloadedIcon;
7071
    }
7072
7073
    /**
7074
     * Parse file information into a link.
7075
     *
7076
     * @param array  $userInfo        Current user info
7077
     * @param array  $courseInfo
7078
     * @param int    $session_id
7079
     * @param array  $resource
7080
     * @param int    $lp_id
7081
     * @param bool   $add_move_button
7082
     * @param string $target
7083
     * @param string $overwrite_url
7084
     * @param bool   $addAudioPreview
7085
     *
7086
     * @return string|null
7087
     */
7088
    private static function parseFile(
7089
        $userInfo,
7090
        $courseInfo,
7091
        $session_id,
7092
        $resource,
7093
        $lp_id,
7094
        $add_move_button,
7095
        $target,
7096
        $overwrite_url,
7097
        $addAudioPreview = false
7098
    ) {
7099
        $img_sys_path = api_get_path(SYS_CODE_PATH).'img/';
7100
        $web_code_path = api_get_path(WEB_CODE_PATH);
7101
7102
        $documentId = $resource['id'];
7103
        $path = $resource['path'];
7104
7105
        if (empty($path)) {
7106
            $num = 0;
7107
        } else {
7108
            $num = substr_count($path, '/') - 1;
7109
        }
7110
7111
        // It's a file.
7112
        $icon = choose_image($path);
7113
        $position = strrpos($icon, '.');
7114
        $icon = substr($icon, 0, $position).'_small.gif';
7115
        $my_file_title = Security::remove_XSS($resource['title']);
7116
        $visibility = $resource['visibility'];
7117
7118
        // If title is empty we try to use the path
7119
        if (empty($my_file_title)) {
7120
            $my_file_title = basename($path);
7121
        }
7122
7123
        if (api_get_configuration_value('save_titles_as_html')) {
7124
            $my_file_title = strip_tags($my_file_title);
7125
        }
7126
7127
        // Show the "image name" not the filename of the image.
7128
        if ($lp_id) {
7129
            // LP URL
7130
            $url = api_get_path(WEB_CODE_PATH).
7131
                'lp/lp_controller.php?'.api_get_cidreq().'&action=add_item&type='.TOOL_DOCUMENT.'&file='.$documentId.'&lp_id='.(int) $lp_id;
7132
        } else {
7133
            // Direct document URL
7134
            $url = $web_code_path.'document/document.php?cidReq='.$courseInfo['code'].'&id_session='.$session_id.'&id='.$documentId;
7135
        }
7136
7137
        if (!empty($overwrite_url)) {
7138
            $overwrite_url = Security::remove_XSS($overwrite_url);
7139
            $url = $overwrite_url.'&cidReq='.$courseInfo['code'].'&id_session='.$session_id.'&document_id='.$documentId;
7140
        }
7141
7142
        $img = Display::returnIconPath($icon);
7143
        if (!file_exists($img_sys_path.$icon)) {
7144
            $img = Display::returnIconPath('default_small.gif');
7145
        }
7146
7147
        $icon = '<img alt="" src="'.$img.'" title="" />';
7148
7149
        $preview = '';
7150
        if ($addAudioPreview) {
7151
            $path = api_get_path(WEB_COURSE_PATH).$courseInfo['directory'].'/document';
7152
            $resource['file_extension'] = pathinfo($resource['path'], PATHINFO_EXTENSION);
7153
            $preview = self::generateAudioPreview($path, $resource);
7154
            if (!empty($preview)) {
7155
                $preview .= '&nbsp;';
7156
                $icon = '';
7157
            }
7158
        }
7159
7160
        $link = Display::url(
7161
            $icon.'&nbsp;'.
7162
            $my_file_title,
7163
            $url,
7164
            ['target' => $target, 'class' => 'moved']
7165
        );
7166
7167
        $directUrl = $web_code_path.'document/document.php?cidReq='.$courseInfo['code'].'&id_session='.$session_id.'&id='.$documentId;
7168
        $link .= '&nbsp;'.Display::url(
7169
                Display::return_icon('preview_view.png', get_lang('Preview')),
7170
                $directUrl,
7171
                ['target' => '_blank']
7172
            );
7173
7174
        $visibilityClass = null;
7175
        if ($visibility == 0) {
7176
            $visibilityClass = ' text-muted ';
7177
        }
7178
        $return = null;
7179
7180
        if ($lp_id == false) {
7181
            $return .= '<li class="doc_resource '.$visibilityClass.' " data_id="'.$documentId.'" data_type="document" title="'.$my_file_title.'" >';
7182
        } else {
7183
            $return .= '<li class="doc_resource lp_resource_element '.$visibilityClass.' " data_id="'.$documentId.'" data_type="document" title="'.$my_file_title.'" >';
7184
        }
7185
7186
        $return .= '<div class="item_data" style="margin-left:'.($num * 5).'px;margin-right:5px;">';
7187
        $return .= $preview;
7188
7189
        if ($add_move_button) {
7190
            $return .= '<a class="moved" href="#">';
7191
            $return .= Display::return_icon('move_everywhere.png', get_lang('Move'), [], ICON_SIZE_TINY);
7192
            $return .= '</a> ';
7193
        }
7194
7195
        $return .= $link;
7196
        $sessionStar = api_get_session_image($resource['session_id'], $userInfo['status']);
7197
        $return .= $sessionStar;
7198
7199
        $return .= '</div></li>';
7200
7201
        return $return;
7202
    }
7203
7204
    /**
7205
     * @param int   $folderId
7206
     * @param array $resource
7207
     * @param int   $lp_id
7208
     *
7209
     * @return string|null
7210
     */
7211
    private static function parseFolder($folderId, $resource, $lp_id)
7212
    {
7213
        $title = isset($resource['title']) ? $resource['title'] : null;
7214
        $path = isset($resource['path']) ? $resource['path'] : null;
7215
7216
        if (empty($path)) {
7217
            $num = 0;
7218
        } else {
7219
            $num = substr_count($path, '/');
7220
        }
7221
7222
        // It's a folder.
7223
        //hide some folders
7224
        if (in_array(
7225
            $path,
7226
            ['/shared_folder', '/chat_files', '/HotPotatoes_files', '/css', '/certificates']
7227
        )) {
7228
            return null;
7229
        } elseif (preg_match('/_groupdocs/', $path)) {
7230
            return null;
7231
        } elseif (preg_match('/sf_user_/', $path)) {
7232
            return null;
7233
        } elseif (preg_match('/shared_folder_session_/', $path)) {
7234
            return null;
7235
        }
7236
7237
        // if in LP, hidden folder are displayed in grey
7238
        $folder_class_hidden = '';
7239
        if ($lp_id) {
7240
            if (isset($resource['visibility']) && $resource['visibility'] == 0) {
7241
                $folder_class_hidden = ' doc_folder_hidden'; // in base.css
7242
            }
7243
        }
7244
        $onclick = 'onclick="javascript: testResources(\'res_'.$resource['id'].'\',\'img_'.$resource['id'].'\')"';
7245
        $return = null;
7246
7247
        if (empty($path)) {
7248
            $return = '<ul class="lp_resource">';
7249
        }
7250
7251
        $return .= '<li
7252
            class="doc_folder'.$folder_class_hidden.'"
7253
            id="doc_id_'.$resource['id'].'"
7254
            style="margin-left:'.($num * 18).'px;"
7255
            >';
7256
7257
        $image = Display::returnIconPath('nolines_plus.gif');
7258
        if (empty($path)) {
7259
            $image = Display::returnIconPath('nolines_minus.gif');
7260
        }
7261
        $return .= '<img
7262
            style="cursor: pointer;"
7263
            src="'.$image.'"
7264
            align="absmiddle"
7265
            id="img_'.$resource['id'].'" '.$onclick.'
7266
        >';
7267
7268
        $return .= Display::return_icon('lp_folder.gif').'&nbsp;';
7269
        $return .= '<span '.$onclick.' style="cursor: pointer;" >'.
7270
            Security::remove_XSS($title).
7271
            '</span>';
7272
        $return .= '</li>';
7273
7274
        if (empty($path)) {
7275
            if ($folderId == false) {
7276
                $return .= '<div id="res_'.$resource['id'].'" >';
7277
            } else {
7278
                $return .= '<div id="res_'.$resource['id'].'" style="display: none;" >';
7279
            }
7280
        }
7281
7282
        return $return;
7283
    }
7284
7285
    /**
7286
     * Get the button to edit document.
7287
     *
7288
     * @param bool   $isReadOnly
7289
     * @param string $extension
7290
     * @param bool   $isCertificateMode
7291
     *
7292
     * @return string
7293
     */
7294
    private static function getButtonEdit($isReadOnly, array $documentData, $extension, $isCertificateMode)
7295
    {
7296
        $extension = strtolower($extension);
7297
        $iconEn = Display::return_icon('edit.png', get_lang('Modify'));
7298
        $iconDis = Display::return_icon('edit_na.png', get_lang('Modify'));
7299
        $courseParams = api_get_cidreq();
7300
        $webOdfExtensionList = self::get_web_odf_extension_list();
7301
        $path = $documentData['path'];
7302
        $document_id = $documentData['id'];
7303
7304
        if ($isReadOnly) {
7305
            if (!api_is_course_admin() && !api_is_platform_admin()) {
7306
                return $iconDis;
7307
            }
7308
7309
            if (
7310
                $extension == 'svg' && api_browser_support('svg') &&
7311
                api_get_setting('enabled_support_svg') == 'true'
7312
            ) {
7313
                return Display::url($iconEn, "edit_draw.php?$courseParams&id=$document_id");
7314
            }
7315
7316
            if (
7317
                in_array($extension, $webOdfExtensionList) &&
7318
                api_get_configuration_value('enabled_support_odf') === true
7319
            ) {
7320
                return Display::url($iconEn, "edit_odf.php?$courseParams&id=$document_id");
7321
            }
7322
7323
            if (
7324
                in_array($extension, ['png', 'jpg', 'jpeg', 'bmp', 'gif', 'pxd']) &&
7325
                api_get_setting('enabled_support_pixlr') == 'true'
7326
            ) {
7327
                return Display::url($iconEn, "edit_paint.php?$courseParams&id=$document_id");
7328
            }
7329
7330
            return Display::url($iconEn, "edit_document.php?$courseParams&id=$document_id");
7331
        }
7332
7333
        if (in_array($path, self::get_system_folders()) || $documentData['filetype'] === 'folder' && strpos($path, 'chat_files') !== false) {
7334
            return $iconDis;
7335
        }
7336
7337
        if ($isCertificateMode) {
7338
            return Display::url($iconEn, "edit_document.php?$courseParams&id=$document_id&curdirpath=/certificates");
7339
        }
7340
7341
        $sessionId = api_get_session_id();
7342
7343
        if ($sessionId && $documentData['session_id'] != $sessionId) {
7344
            return $iconDis;
7345
        }
7346
7347
        if (
7348
            $extension == 'svg' && api_browser_support('svg') &&
7349
            api_get_setting('enabled_support_svg') == 'true'
7350
        ) {
7351
            return Display::url($iconEn, "edit_draw.php?$courseParams&id=$document_id");
7352
        }
7353
7354
        if (
7355
            in_array($extension, $webOdfExtensionList) &&
7356
            api_get_configuration_value('enabled_support_odf') === true
7357
        ) {
7358
            return Display::url($iconEn, "edit_odf.php?$courseParams&id=$document_id");
7359
        }
7360
7361
        if (
7362
            in_array($extension, ['png', 'jpg', 'jpeg', 'bmp', 'gif', 'pxd']) &&
7363
            api_get_setting('enabled_support_pixlr') == 'true'
7364
        ) {
7365
            return Display::url($iconEn, "edit_paint.php?$courseParams&id=$document_id");
7366
        }
7367
7368
        return Display::url($iconEn, "edit_document.php?$courseParams&id=$document_id");
7369
    }
7370
7371
    /**
7372
     * Get the button to move document.
7373
     *
7374
     * @param bool $isReadOnly
7375
     * @param bool $isCertificateMode
7376
     * @param int  $parentId
7377
     *
7378
     * @return string
7379
     */
7380
    private static function getButtonMove($isReadOnly, array $documentData, $isCertificateMode, $parentId)
7381
    {
7382
        $iconEn = Display::return_icon('move.png', get_lang('Move'));
7383
        $iconDis = Display::return_icon('move_na.png', get_lang('Move'));
7384
7385
        if ($isReadOnly) {
7386
            return $iconDis;
7387
        }
7388
7389
        $path = $documentData['path'];
7390
        $document_id = $documentData['id'];
7391
        $sessionId = api_get_session_id();
7392
        $courseParams = api_get_cidreq();
7393
7394
        if ($isCertificateMode || in_array($path, self::get_system_folders()) || $documentData['filetype'] === 'folder' && strpos($path, 'chat_files') !== false) {
7395
            return $iconDis;
7396
        }
7397
7398
        if ($sessionId) {
7399
            if ($documentData['session_id'] != $sessionId) {
7400
                return $iconDis;
7401
            }
7402
        }
7403
7404
        $urlMoveParams = http_build_query([
7405
            'id' => $parentId,
7406
            'move' => $document_id,
7407
            'sec_token' => Security::getTokenFromSession(),
7408
        ]);
7409
7410
        return Display::url(
7411
            $iconEn,
7412
            api_get_self()."?$courseParams&$urlMoveParams"
7413
        );
7414
    }
7415
7416
    /**
7417
     * Get the button to set visibility to document.
7418
     *
7419
     * @param bool $isReadOnly
7420
     * @param int  $visibility
7421
     * @param bool $isCertificateMode
7422
     * @param int  $parentId
7423
     *
7424
     * @return string|null
7425
     */
7426
    private static function getButtonVisibility(
7427
        $isReadOnly,
7428
        $visibility,
7429
        array $documentData,
7430
        $isCertificateMode,
7431
        $parentId
7432
    ) {
7433
        $visibility_icon = $visibility == 0 ? 'invisible' : 'visible';
7434
        $visibility_command = $visibility == 0 ? 'set_visible' : 'set_invisible';
7435
        $courseParams = api_get_cidreq();
7436
7437
        if ($isReadOnly) {
7438
            if (api_is_allowed_to_edit() || api_is_platform_admin()) {
7439
                return Display::return_icon($visibility_icon.'.png', get_lang('VisibilityCannotBeChanged'));
7440
            }
7441
7442
            return null;
7443
        }
7444
7445
        if ($isCertificateMode) {
7446
            return Display::return_icon($visibility_icon.'.png', get_lang('VisibilityCannotBeChanged'));
7447
        }
7448
7449
        if (api_is_allowed_to_edit() || api_is_platform_admin()) {
7450
            $tip_visibility = $visibility_icon == 'invisible' ? get_lang('Show') : get_lang('Hide');
7451
            $secToken = Security::getTokenFromSession();
7452
7453
            return Display::url(
7454
                Display::return_icon($visibility_icon.'.png', $tip_visibility),
7455
                api_get_self()."?$courseParams&id=$parentId&$visibility_command={$documentData['id']}&sec_token=$secToken"
7456
            );
7457
        }
7458
7459
        return null;
7460
    }
7461
7462
    /**
7463
     * GEt the button to delete a document.
7464
     *
7465
     * @param bool   $isReadOnly
7466
     * @param bool   $isCertificateMode
7467
     * @param string $curDirPath
7468
     * @param int    $parentId
7469
     *
7470
     * @return string
7471
     */
7472
    private static function getButtonDelete(
7473
        $isReadOnly,
7474
        array $documentData,
7475
        $isCertificateMode,
7476
        $curDirPath,
7477
        $parentId
7478
    ) {
7479
        $iconEn = Display::return_icon('delete.png', get_lang('Delete'));
7480
        $iconDis = Display::return_icon('delete_na.png', get_lang('ThisFolderCannotBeDeleted'));
7481
        $path = $documentData['path'];
7482
        $id = $documentData['id'];
7483
        $courseParams = api_get_cidreq();
7484
7485
        if ($isReadOnly) {
7486
            return $iconDis;
7487
        }
7488
7489
        if (in_array($path, self::get_system_folders()) || $documentData['filetype'] === 'folder' && strpos($path, 'chat_files') !== false) {
7490
            return $iconDis;
7491
        }
7492
7493
        $titleToShow = addslashes(basename($documentData['title']));
7494
        $urlDeleteParams = http_build_query([
7495
            'curdirpath' => $curDirPath,
7496
            'action' => 'delete_item',
7497
            'id' => $parentId,
7498
            'deleteid' => $documentData['id'],
7499
            'sec_token' => Security::getTokenFromSession(),
7500
        ]);
7501
7502
        $btn = Display::url(
7503
            $iconEn,
7504
            '#',
7505
            [
7506
                'data-item-title' => $titleToShow,
7507
                'data-href' => api_get_self()."?$courseParams&$urlDeleteParams",
7508
                'data-toggle' => 'modal',
7509
                'data-target' => '#confirm-delete',
7510
            ]
7511
        );
7512
7513
        if (
7514
            isset($_GET['curdirpath']) &&
7515
            $_GET['curdirpath'] == '/certificates' &&
7516
            self::get_default_certificate_id(api_get_course_id()) == $id
7517
        ) {
7518
            return $btn;
7519
        }
7520
7521
        if ($isCertificateMode) {
7522
            return $btn;
7523
        }
7524
7525
        $sessionId = api_get_session_id();
7526
7527
        if ($sessionId) {
7528
            if ($documentData['session_id'] != $sessionId) {
7529
                return $iconDis;
7530
            }
7531
        }
7532
7533
        return $btn;
7534
    }
7535
7536
    /**
7537
     * Retrieves all documents in a course by their parent folder ID.
7538
     *
7539
     * @param array  $courseInfo      Information about the course.
7540
     * @param int    $parentId        The ID of the parent folder.
7541
     * @param int    $toGroupId       (Optional) The ID of the group to filter by. Default is 0.
7542
     * @param int|null $toUserId      (Optional) The ID of the user to filter by. Default is null.
7543
     * @param bool   $canSeeInvisible (Optional) Whether to include invisible documents. Default is false.
7544
     * @param bool   $search          (Optional) Whether to perform a search or fetch all documents. Default is true.
7545
     * @param int    $sessionId       (Optional) The session ID to filter by. Default is 0.
7546
     *
7547
     * @return array List of documents that match the criteria.
7548
     */
7549
    public static function getAllDocumentsByParentId(
7550
        $courseInfo,
7551
        $parentId,
7552
        $toGroupId = 0,
7553
        $toUserId = null,
7554
        $canSeeInvisible = false,
7555
        $search = true,
7556
        $sessionId = 0
7557
    ) {
7558
        if (empty($courseInfo)) {
7559
            return [];
7560
        }
7561
7562
        $tblDocument = Database::get_course_table(TABLE_DOCUMENT);
7563
7564
        $parentId = (int) $parentId;
7565
7566
        $sql = "SELECT path, filetype
7567
            FROM $tblDocument
7568
            WHERE id = $parentId
7569
              AND c_id = {$courseInfo['real_id']}";
7570
7571
        $result = Database::query($sql);
7572
7573
        if ($result === false || Database::num_rows($result) == 0) {
7574
            return [];
7575
        }
7576
7577
        $parentRow = Database::fetch_array($result, 'ASSOC');
7578
        $parentPath = $parentRow['path'];
7579
        $filetype = $parentRow['filetype'];
7580
7581
        if ($filetype !== 'folder') {
7582
            return [];
7583
        }
7584
7585
        return self::getAllDocumentData(
7586
            $courseInfo,
7587
            $parentPath,
7588
            $toGroupId,
7589
            $toUserId,
7590
            $canSeeInvisible,
7591
            $search,
7592
            $sessionId
7593
        );
7594
    }
7595
7596
    /**
7597
     * Include MathJax script in document.
7598
     *
7599
     * @param string file content $content
7600
     *
7601
     * @return string file content
7602
     */
7603
    private static function includeMathJaxScript($content)
7604
    {
7605
        $scriptTag = '<script src="'.api_get_path(WEB_PUBLIC_PATH).'assets/MathJax/MathJax.js?config=TeX-MML-AM_HTMLorMML"></script>';
7606
        // Find position of </body> tag
7607
        $pos = strpos($content, '</body>');
7608
        // If </body> tag found, insert the script tag before it
7609
        if ($pos !== false) {
7610
            $content = substr_replace($content, $scriptTag, $pos, 0);
7611
        } else {
7612
            // If </body> tag not found, just append the script tag at the end
7613
            $content .= $scriptTag;
7614
        }
7615
7616
        return $content;
7617
    }
7618
}
7619