Passed
Push — master ( ad6b2a...ec8fd5 )
by Julito
28:29 queued 12s
created

Display::toolbarAction()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 8
nc 2
nop 2
dl 0
loc 12
rs 10
c 0
b 0
f 0
1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
use Chamilo\CoreBundle\Component\Utils\ChamiloApi;
6
use Chamilo\CoreBundle\Entity\ExtraField;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, ExtraField. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
7
use Chamilo\CoreBundle\Entity\ExtraFieldValues;
8
use Chamilo\CoreBundle\Framework\Container;
9
use ChamiloSession as Session;
10
use Symfony\Component\HttpFoundation\Response;
11
12
/**
13
 * Class Display
14
 * Contains several public functions dealing with the display of
15
 * table data, messages, help topics, ...
16
 *
17
 * Include/require it in your code to use its public functionality.
18
 * There are also several display public functions in the main api library.
19
 *
20
 * All public functions static public functions inside a class called Display,
21
 * so you use them like this: e.g.
22
 * Display::return_message($message)
23
 */
24
class Display
25
{
26
    /** @var Template */
27
    public static $global_template;
28
    public static $preview_style = null;
29
    public static $legacyTemplate;
30
31
    /**
32
     * Constructor.
33
     */
34
    public function __construct()
35
    {
36
    }
37
38
    /**
39
     * @return array
40
     */
41
    public static function toolList()
42
    {
43
        return [
44
            'group',
45
            'work',
46
            'glossary',
47
            'forum',
48
            'course_description',
49
            'gradebook',
50
            'attendance',
51
            'course_progress',
52
            'notebook',
53
        ];
54
    }
55
56
    /**
57
     * Displays the page header.
58
     *
59
     * @param string The name of the page (will be showed in the page title)
60
     * @param string Optional help file name
61
     * @param string $page_header
62
     */
63
    public static function display_header(
64
        $tool_name = '',
65
        $help = null,
66
        $page_header = null
67
    ) {
68
        global $interbreadcrumb;
69
        $interbreadcrumb[] = ['url' => '#', 'name' => $tool_name];
70
71
        ob_start();
72
73
        return true;
74
    }
75
76
    /**
77
     * Displays the reduced page header (without banner).
78
     */
79
    public static function display_reduced_header()
80
    {
81
        ob_start();
82
        self::$legacyTemplate = '@ChamiloCore/Layout/no_layout.html.twig';
83
84
        return true;
85
86
        global $show_learnpath, $tool_name;
0 ignored issues
show
Unused Code introduced by
GlobalNode is not reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
87
        self::$global_template = new Template(
88
            $tool_name,
89
            false,
90
            false,
91
            $show_learnpath
92
        );
93
    }
94
95
    /**
96
     * Display no header.
97
     */
98
    public static function display_no_header()
99
    {
100
        global $tool_name, $show_learnpath;
101
        self::$global_template = new Template(
102
            $tool_name,
103
            false,
104
            false,
105
            $show_learnpath
106
        );
107
    }
108
109
    /**
110
     * Display the page footer.
111
     */
112
    public static function display_footer()
113
    {
114
        $contents = ob_get_contents();
115
        if (ob_get_length()) {
116
            ob_end_clean();
117
        }
118
        $tpl = '@ChamiloCore/Layout/layout_one_col.html.twig';
119
        if (!empty(self::$legacyTemplate)) {
120
            $tpl = self::$legacyTemplate;
121
        }
122
        $response = new Response();
123
        $params['content'] = $contents;
0 ignored issues
show
Comprehensibility Best Practice introduced by
$params was never initialized. Although not strictly required by PHP, it is generally a good practice to add $params = array(); before regardless.
Loading history...
124
        global $interbreadcrumb, $htmlHeadXtra;
125
126
        $courseInfo = api_get_course_info();
127
        if (!empty($courseInfo)) {
128
            $url = $courseInfo['course_public_url'];
129
            $sessionId = api_get_session_id();
130
            if (!empty($sessionId)) {
131
                $url .= '?sid='.$sessionId;
132
            }
133
134
            array_unshift(
135
                $interbreadcrumb,
136
                ['name' => $courseInfo['title'], 'url' => $url]
137
            );
138
        }
139
140
        $params['legacy_javascript'] = $htmlHeadXtra;
141
        $params['legacy_breadcrumb'] = $interbreadcrumb;
142
143
        Template::setVueParams($params);
144
        $content = Container::getTwig()->render($tpl, $params);
145
        $response->setContent($content);
146
        $response->send();
147
        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...
148
    }
149
150
    /**
151
     * Display the page footer.
152
     */
153
    public static function display_reduced_footer()
154
    {
155
        $contents = ob_get_contents();
156
        if (ob_get_length()) {
157
            ob_end_clean();
158
        }
159
        $tpl = '@ChamiloCore/Layout/no_layout.html.twig';
160
        if (!empty(self::$legacyTemplate)) {
161
            $tpl = self::$legacyTemplate;
162
        }
163
        $response = new Response();
164
        $params['content'] = $contents;
0 ignored issues
show
Comprehensibility Best Practice introduced by
$params was never initialized. Although not strictly required by PHP, it is generally a good practice to add $params = array(); before regardless.
Loading history...
165
        global $interbreadcrumb, $htmlHeadXtra;
166
        $params['legacy_javascript'] = $htmlHeadXtra;
167
        $params['legacy_breadcrumb'] = $interbreadcrumb;
168
169
        $content = Container::getTwig()->render($tpl, $params);
170
        $response->setContent($content);
171
        $response->send();
172
        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...
173
    }
174
175
    /**
176
     * Displays the tool introduction of a tool.
177
     *
178
     * @author Patrick Cool <[email protected]>, Ghent University
179
     *
180
     * @param string $tool          these are the constants that are used for indicating the tools
181
     * @param array  $editor_config Optional configuration settings for the online editor.
182
     *                              return: $tool return a string array list with the "define" in main_api.lib
183
     *
184
     * @return string html code for adding an introduction
185
     */
186
    public static function display_introduction_section(
187
        $tool,
188
        $editor_config = null
189
    ) {
190
        echo self::return_introduction_section($tool, $editor_config);
0 ignored issues
show
Bug introduced by
Are you sure the usage of self::return_introductio...($tool, $editor_config) targeting Display::return_introduction_section() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
191
    }
192
193
    /**
194
     * @param string $tool
195
     * @param array  $editor_config
196
     */
197
    public static function return_introduction_section(
198
        $tool,
199
        $editor_config = null
200
    ) {
201
        $moduleId = $tool;
202
        if ('true' === api_get_setting('enable_tool_introduction') || TOOL_COURSE_HOMEPAGE == $tool) {
203
            $introduction_section = null;
204
            require api_get_path(SYS_CODE_PATH).'inc/introductionSection.inc.php';
205
206
            return $introduction_section;
207
        }
208
    }
209
210
    /**
211
     * Displays a table.
212
     *
213
     * @param array  $header          Titles for the table header
214
     *                                each item in this array can contain 3 values
215
     *                                - 1st element: the column title
216
     *                                - 2nd element: true or false (column sortable?)
217
     *                                - 3th element: additional attributes for
218
     *                                th-tag (eg for column-width)
219
     *                                - 4the element: additional attributes for the td-tags
220
     * @param array  $content         2D-array with the tables content
221
     * @param array  $sorting_options Keys are:
222
     *                                'column' = The column to use as sort-key
223
     *                                'direction' = SORT_ASC or SORT_DESC
224
     * @param array  $paging_options  Keys are:
225
     *                                'per_page_default' = items per page when switching from
226
     *                                full-    list to per-page-view
227
     *                                'per_page' = number of items to show per page
228
     *                                'page_nr' = The page to display
229
     * @param array  $query_vars      Additional variables to add in the query-string
230
     * @param array  $form_actions
231
     * @param string $style           The style that the table will show. You can set 'table' or 'grid'
232
     * @param string $tableName
233
     * @param string $tableId
234
     *
235
     * @author [email protected]
236
     */
237
    public static function display_sortable_table(
238
        $header,
239
        $content,
240
        $sorting_options = [],
241
        $paging_options = [],
242
        $query_vars = null,
243
        $form_actions = [],
244
        $style = 'table',
245
        $tableName = 'tablename',
246
        $tableId = ''
247
    ) {
248
        $column = isset($sorting_options['column']) ? $sorting_options['column'] : 0;
249
        $default_items_per_page = isset($paging_options['per_page']) ? $paging_options['per_page'] : 20;
250
        $table = new SortableTableFromArray($content, $column, $default_items_per_page, $tableName, null, $tableId);
251
        if (is_array($query_vars)) {
252
            $table->set_additional_parameters($query_vars);
253
        }
254
        if ('table' == $style) {
255
            if (is_array($header) && count($header) > 0) {
256
                foreach ($header as $index => $header_item) {
257
                    $table->set_header(
258
                        $index,
259
                        isset($header_item[0]) ? $header_item[0] : null,
260
                        isset($header_item[1]) ? $header_item[1] : null,
261
                        isset($header_item[2]) ? $header_item[2] : null,
262
                        isset($header_item[3]) ? $header_item[3] : null
263
                    );
264
                }
265
            }
266
            $table->set_form_actions($form_actions);
267
            $table->display();
268
        } else {
269
            $table->display_grid();
270
        }
271
    }
272
273
    /**
274
     * Returns an HTML table with sortable column (through complete page refresh).
275
     *
276
     * @param array  $header
277
     * @param array  $content         Array of row arrays
278
     * @param array  $sorting_options
279
     * @param array  $paging_options
280
     * @param array  $query_vars
281
     * @param array  $form_actions
282
     * @param string $style
283
     *
284
     * @return string HTML string for array
285
     */
286
    public static function return_sortable_table(
287
        $header,
288
        $content,
289
        $sorting_options = [],
290
        $paging_options = [],
291
        $query_vars = null,
292
        $form_actions = [],
293
        $style = 'table'
294
    ) {
295
        ob_start();
296
        self::display_sortable_table(
297
            $header,
298
            $content,
299
            $sorting_options,
300
            $paging_options,
301
            $query_vars,
302
            $form_actions,
303
            $style
304
        );
305
        $content = ob_get_contents();
306
        ob_end_clean();
307
308
        return $content;
309
    }
310
311
    /**
312
     * Shows a nice grid.
313
     *
314
     * @param string grid name (important to create css)
315
     * @param array header content
316
     * @param array array with the information to show
317
     * @param array $paging_options Keys are:
318
     *                              'per_page_default' = items per page when switching from
319
     *                              full-    list to per-page-view
320
     *                              'per_page' = number of items to show per page
321
     *                              'page_nr' = The page to display
322
     *                              'hide_navigation' =  true to hide the navigation
323
     * @param array $query_vars     Additional variables to add in the query-string
324
     * @param mixed An array with bool values to know which columns show.
325
     * i.e: $visibility_options= array(true, false) we will only show the first column
326
     *                Can be also only a bool value. TRUE: show all columns, FALSE: show nothing
327
     */
328
    public static function display_sortable_grid(
329
        $name,
330
        $header,
331
        $content,
332
        $paging_options = [],
333
        $query_vars = null,
334
        $form_actions = [],
335
        $visibility_options = true,
336
        $sort_data = true,
337
        $grid_class = []
338
    ) {
339
        echo self::return_sortable_grid(
340
            $name,
341
            $header,
342
            $content,
343
            $paging_options,
344
            $query_vars,
345
            $form_actions,
346
            $visibility_options,
347
            $sort_data,
348
            $grid_class
349
        );
350
    }
351
352
    /**
353
     * Gets a nice grid in html string.
354
     *
355
     * @param string grid name (important to create css)
356
     * @param array header content
357
     * @param array array with the information to show
358
     * @param array $paging_options Keys are:
359
     *                              'per_page_default' = items per page when switching from
360
     *                              full-    list to per-page-view
361
     *                              'per_page' = number of items to show per page
362
     *                              'page_nr' = The page to display
363
     *                              'hide_navigation' =  true to hide the navigation
364
     * @param array $query_vars     Additional variables to add in the query-string
365
     * @param mixed An array with bool values to know which columns show. i.e:
366
     *  $visibility_options= array(true, false) we will only show the first column
367
     *    Can be also only a bool value. TRUE: show all columns, FALSE: show nothing
368
     * @param bool  true for sorting data or false otherwise
369
     * @param array grid classes
370
     *
371
     * @return string html grid
372
     */
373
    public static function return_sortable_grid(
374
        $name,
375
        $header,
376
        $content,
377
        $paging_options = [],
378
        $query_vars = null,
379
        $form_actions = [],
380
        $visibility_options = true,
381
        $sort_data = true,
382
        $grid_class = [],
383
        $elementCount = 0
384
    ) {
385
        $column = 0;
386
        $default_items_per_page = isset($paging_options['per_page']) ? $paging_options['per_page'] : 20;
387
        $table = new SortableTableFromArray($content, $column, $default_items_per_page, $name);
388
        $table->total_number_of_items = intval($elementCount);
389
        if (is_array($query_vars)) {
390
            $table->set_additional_parameters($query_vars);
391
        }
392
393
        return $table->display_simple_grid(
394
            $visibility_options,
395
            $paging_options['hide_navigation'],
396
            $default_items_per_page,
397
            $sort_data,
398
            $grid_class
399
        );
400
    }
401
402
    /**
403
     * Displays a table with a special configuration.
404
     *
405
     * @param array $header          Titles for the table header
406
     *                               each item in this array can contain 3 values
407
     *                               - 1st element: the column title
408
     *                               - 2nd element: true or false (column sortable?)
409
     *                               - 3th element: additional attributes for th-tag (eg for column-width)
410
     *                               - 4the element: additional attributes for the td-tags
411
     * @param array $content         2D-array with the tables content
412
     * @param array $sorting_options Keys are:
413
     *                               'column' = The column to use as sort-key
414
     *                               'direction' = SORT_ASC or SORT_DESC
415
     * @param array $paging_options  Keys are:
416
     *                               'per_page_default' = items per page when switching from full list to per-page-view
417
     *                               'per_page' = number of items to show per page
418
     *                               'page_nr' = The page to display
419
     * @param array $query_vars      Additional variables to add in the query-string
420
     * @param array $column_show     Array of binaries 1= show columns 0. hide a column
421
     * @param array $column_order    An array of integers that let us decide how the columns are going to be sort.
422
     *                               i.e:  $column_order=array('1''4','3','4'); The 2nd column will be order like the 4th column
423
     * @param array $form_actions    Set optional forms actions
424
     *
425
     * @author Julio Montoya
426
     */
427
    public static function display_sortable_config_table(
428
        $table_name,
429
        $header,
430
        $content,
431
        $sorting_options = [],
432
        $paging_options = [],
433
        $query_vars = null,
434
        $column_show = [],
435
        $column_order = [],
436
        $form_actions = []
437
    ) {
438
        $column = isset($sorting_options['column']) ? $sorting_options['column'] : 0;
439
        $default_items_per_page = isset($paging_options['per_page']) ? $paging_options['per_page'] : 20;
440
441
        $table = new SortableTableFromArrayConfig(
442
            $content,
443
            $column,
444
            $default_items_per_page,
445
            $table_name,
446
            $column_show,
447
            $column_order
448
        );
449
450
        if (is_array($query_vars)) {
451
            $table->set_additional_parameters($query_vars);
452
        }
453
        // Show or hide the columns header
454
        if (is_array($column_show)) {
455
            for ($i = 0; $i < count($column_show); $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...
456
                if (!empty($column_show[$i])) {
457
                    $val0 = isset($header[$i][0]) ? $header[$i][0] : null;
458
                    $val1 = isset($header[$i][1]) ? $header[$i][1] : null;
459
                    $val2 = isset($header[$i][2]) ? $header[$i][2] : null;
460
                    $val3 = isset($header[$i][3]) ? $header[$i][3] : null;
461
                    $table->set_header($i, $val0, $val1, $val2, $val3);
462
                }
463
            }
464
        }
465
        $table->set_form_actions($form_actions);
466
        $table->display();
467
    }
468
469
    /**
470
     * Returns a div html string with.
471
     *
472
     * @param string $message
473
     * @param string $type    Example: confirm, normal, warning, error
474
     * @param bool   $filter  Whether to XSS-filter or not
475
     *
476
     * @return string Message wrapped into an HTML div
477
     */
478
    public static function return_message($message, $type = 'normal', $filter = true)
479
    {
480
        if (empty($message)) {
481
            return '';
482
        }
483
484
        if ($filter) {
485
            $message = api_htmlentities(
486
                $message,
487
                ENT_QUOTES,
488
                api_is_xml_http_request() ? 'UTF-8' : api_get_system_encoding()
489
            );
490
        }
491
492
        $class = '';
493
        switch ($type) {
494
            case 'warning':
495
                $class .= 'alert alert-warning';
496
                break;
497
            case 'error':
498
                $class .= 'alert alert-danger';
499
                break;
500
            case 'confirmation':
501
            case 'confirm':
502
            case 'success':
503
                $class .= 'alert alert-success';
504
                break;
505
            case 'normal':
506
            case 'info':
507
            default:
508
                $class .= 'alert alert-info';
509
        }
510
511
        return self::div($message, ['class' => $class]);
512
    }
513
514
    /**
515
     * Returns an encrypted mailto hyperlink.
516
     *
517
     * @param string  e-mail
0 ignored issues
show
Documentation Bug introduced by
The doc comment e-mail at position 0 could not be parsed: Unknown type name 'e-mail' at position 0 in e-mail.
Loading history...
518
     * @param string  clickable text
519
     * @param string  optional, class from stylesheet
520
     * @param bool $addExtraContent
521
     *
522
     * @return string encrypted mailto hyperlink
523
     */
524
    public static function encrypted_mailto_link(
525
        $email,
526
        $clickable_text = null,
527
        $style_class = '',
528
        $addExtraContent = false
529
    ) {
530
        if (is_null($clickable_text)) {
531
            $clickable_text = $email;
532
        }
533
534
        // "mailto:" already present?
535
        if ('mailto:' !== substr($email, 0, 7)) {
536
            $email = 'mailto:'.$email;
537
        }
538
539
        // Class (stylesheet) defined?
540
        if ('' !== $style_class) {
541
            $style_class = ' class="'.$style_class.'"';
542
        }
543
544
        // Encrypt email
545
        $hmail = '';
546
        for ($i = 0; $i < strlen($email); $i++) {
547
            $hmail .= '&#'.ord($email[$i]).';';
548
        }
549
550
        $value = api_get_configuration_value('add_user_course_information_in_mailto');
551
552
        if ($value) {
553
            if ('false' === api_get_setting('allow_email_editor')) {
554
                $hmail .= '?';
555
            }
556
557
            if (!api_is_anonymous()) {
558
                $hmail .= '&subject='.Security::remove_XSS(api_get_setting('siteName'));
559
            }
560
            if ($addExtraContent) {
561
                $content = '';
562
                if (!api_is_anonymous()) {
563
                    $userInfo = api_get_user_info();
564
                    $content .= get_lang('User').': '.$userInfo['complete_name']."\n";
565
566
                    $courseInfo = api_get_course_info();
567
                    if (!empty($courseInfo)) {
568
                        $content .= get_lang('Course').': ';
569
                        $content .= $courseInfo['name'];
570
                        $sessionInfo = api_get_session_info(api_get_session_id());
571
                        if (!empty($sessionInfo)) {
572
                            $content .= ' '.$sessionInfo['name'].' <br />';
573
                        }
574
                    }
575
                }
576
                $hmail .= '&body='.rawurlencode($content);
577
            }
578
        }
579
580
        $hclickable_text = '';
581
        // Encrypt clickable text if @ is present
582
        if (strpos($clickable_text, '@')) {
583
            for ($i = 0; $i < strlen($clickable_text); $i++) {
584
                $hclickable_text .= '&#'.ord($clickable_text[$i]).';';
585
            }
586
        } else {
587
            $hclickable_text = @htmlspecialchars(
588
                $clickable_text,
589
                ENT_QUOTES,
590
                api_get_system_encoding()
591
            );
592
        }
593
        // Return encrypted mailto hyperlink
594
        return '<a href="'.$hmail.'"'.$style_class.' class="clickable_email_link">'.$hclickable_text.'</a>';
595
    }
596
597
    /**
598
     * Returns an mailto icon hyperlink.
599
     *
600
     * @param string  e-mail
0 ignored issues
show
Documentation Bug introduced by
The doc comment e-mail at position 0 could not be parsed: Unknown type name 'e-mail' at position 0 in e-mail.
Loading history...
601
     * @param string  icon source file from the icon lib
602
     * @param int  icon size from icon lib
603
     * @param string  optional, class from stylesheet
604
     *
605
     * @return string encrypted mailto hyperlink
606
     */
607
    public static function icon_mailto_link(
608
        $email,
609
        $icon_file = "mail.png",
610
        $icon_size = 22,
611
        $style_class = ''
612
    ) {
613
        // "mailto:" already present?
614
        if ('mailto:' != substr($email, 0, 7)) {
615
            $email = 'mailto:'.$email;
616
        }
617
        // Class (stylesheet) defined?
618
        if ('' != $style_class) {
619
            $style_class = ' class="'.$style_class.'"';
620
        }
621
        // Encrypt email
622
        $hmail = '';
623
        for ($i = 0; $i < strlen($email); $i++) {
624
            $hmail .= '&#'.ord($email[
625
            $i]).';';
626
        }
627
        // icon html code
628
        $icon_html_source = self::return_icon(
629
            $icon_file,
630
            $hmail,
631
            '',
632
            $icon_size
633
        );
634
        // Return encrypted mailto hyperlink
635
636
        return '<a href="'.$hmail.'"'.$style_class.' class="clickable_email_link">'.$icon_html_source.'</a>';
637
    }
638
639
    /**
640
     * Prints an <option>-list with all letters (A-Z).
641
     *
642
     * @todo This is English language specific implementation.
643
     * It should be adapted for the other languages.
644
     *
645
     * @return string
646
     */
647
    public static function get_alphabet_options($selectedLetter = '')
648
    {
649
        $result = '';
650
        for ($i = 65; $i <= 90; $i++) {
651
            $letter = chr($i);
652
            $result .= '<option value="'.$letter.'"';
653
            if ($selectedLetter == $letter) {
654
                $result .= ' selected="selected"';
655
            }
656
            $result .= '>'.$letter.'</option>';
657
        }
658
659
        return $result;
660
    }
661
662
    /**
663
     * Get the options withing a select box within the given values.
664
     *
665
     * @param int   Min value
666
     * @param int   Max value
667
     * @param int   Default value
668
     *
669
     * @return string HTML select options
670
     */
671
    public static function get_numeric_options($min, $max, $selected_num = 0)
672
    {
673
        $result = '';
674
        for ($i = $min; $i <= $max; $i++) {
675
            $result .= '<option value="'.$i.'"';
676
            if (is_int($selected_num)) {
677
                if ($selected_num == $i) {
678
                    $result .= ' selected="selected"';
679
                }
680
            }
681
            $result .= '>'.$i.'</option>';
682
        }
683
684
        return $result;
685
    }
686
687
    /**
688
     * This public function displays an icon.
689
     *
690
     * @param string   The filename of the file (in the main/img/ folder
691
     * @param string   The alt text (probably a language variable)
692
     * @param array    additional attributes (for instance height, width, onclick, ...)
693
     * @param int  The wanted width of the icon (to be looked for in the corresponding img/icons/ folder)
694
     */
695
    public static function display_icon(
696
        $image,
697
        $alt_text = '',
698
        $additional_attributes = [],
699
        $size = null
700
    ) {
701
        echo self::return_icon($image, $alt_text, $additional_attributes, $size);
702
    }
703
704
    /**
705
     * Gets the path of an icon.
706
     *
707
     * @param string $icon
708
     * @param int    $size
709
     *
710
     * @return string
711
     */
712
    public static function returnIconPath($icon, $size = ICON_SIZE_SMALL)
713
    {
714
        return self::return_icon($icon, null, null, $size, null, true, false);
715
    }
716
717
    /**
718
     * This public function returns the htmlcode for an icon.
719
     *
720
     * @param string   The filename of the file (in the main/img/ folder
721
     * @param string   The alt text (probably a language variable)
722
     * @param array    Additional attributes (for instance height, width, onclick, ...)
723
     * @param int  The wanted width of the icon (to be looked for in the corresponding img/icons/ folder)
724
     *
725
     * @return string An HTML string of the right <img> tag
726
     *
727
     * @author Patrick Cool <[email protected]>, Ghent University 2006
728
     * @author Julio Montoya 2010 Function improved, adding image constants
729
     * @author Yannick Warnier 2011 Added size handler
730
     *
731
     * @version Feb 2011
732
     */
733
    public static function return_icon(
734
        $image,
735
        $alt_text = '',
736
        $additional_attributes = [],
737
        $size = ICON_SIZE_SMALL,
738
        $show_text = true,
739
        $return_only_path = false,
740
        $loadThemeIcon = true
741
    ) {
742
        $code_path = api_get_path(SYS_PUBLIC_PATH);
743
        $w_code_path = api_get_path(WEB_PUBLIC_PATH);
744
        // The following path is checked to see if the file exist. It's
745
        // important to use the public path (i.e. web/css/) rather than the
746
        // internal path (/app/Resource/public/css/) because the path used
747
        // in the end must be the public path
748
        $alternateCssPath = api_get_path(SYS_PUBLIC_PATH).'css/';
749
        $alternateWebCssPath = api_get_path(WEB_PUBLIC_PATH).'css/';
750
751
        // Avoid issues with illegal string offset for legacy calls to this
752
        // method with an empty string rather than null or an empty array
753
        if (empty($additional_attributes)) {
754
            $additional_attributes = [];
755
        }
756
757
        $image = trim($image);
758
759
        if (isset($size)) {
760
            $size = (int) $size;
761
        } else {
762
            $size = ICON_SIZE_SMALL;
763
        }
764
765
        $size_extra = $size.'/';
766
        $icon = $w_code_path.'img/'.$image;
767
        $theme = 'themes/chamilo/icons/';
768
769
        if ($loadThemeIcon) {
770
            // @todo with chamilo 2 code
771
            $theme = 'themes/'.api_get_visual_theme().'/icons/';
772
            if (is_file($alternateCssPath.$theme.$image)) {
773
                $icon = $alternateWebCssPath.$theme.$image;
774
            }
775
            // Checking the theme icons folder example: app/Resources/public/css/themes/chamilo/icons/XXX
776
            if (is_file($alternateCssPath.$theme.$size_extra.$image)) {
777
                $icon = $alternateWebCssPath.$theme.$size_extra.$image;
778
            } elseif (is_file($code_path.'img/icons/'.$size_extra.$image)) {
779
                //Checking the main/img/icons/XXX/ folder
780
                $icon = $w_code_path.'img/icons/'.$size_extra.$image;
781
            }
782
        } else {
783
            if (is_file($code_path.'img/icons/'.$size_extra.$image)) {
784
                // Checking the main/img/icons/XXX/ folder
785
                $icon = $w_code_path.'img/icons/'.$size_extra.$image;
786
            }
787
        }
788
789
        // Special code to enable SVG - refs #7359 - Needs more work
790
        // The code below does something else to "test out" SVG: for each icon,
791
        // it checks if there is an SVG version. If so, it uses it.
792
        // When moving this to production, the return_icon() calls should
793
        // ask for the SVG version directly
794
        $svgIcons = api_get_setting('icons_mode_svg');
795
        if ('true' == $svgIcons && false == $return_only_path) {
796
            $svgImage = substr($image, 0, -3).'svg';
797
            if (is_file($code_path.$theme.'svg/'.$svgImage)) {
798
                $icon = $w_code_path.$theme.'svg/'.$svgImage;
799
            } elseif (is_file($code_path.'img/icons/svg/'.$svgImage)) {
800
                $icon = $w_code_path.'img/icons/svg/'.$svgImage;
801
            }
802
803
            if (empty($additional_attributes['height'])) {
804
                $additional_attributes['height'] = $size;
805
            }
806
            if (empty($additional_attributes['width'])) {
807
                $additional_attributes['width'] = $size;
808
            }
809
        }
810
811
        if ($return_only_path) {
812
            return $icon;
813
        }
814
815
        $img = self::img($icon, $alt_text, $additional_attributes);
816
        if (SHOW_TEXT_NEAR_ICONS == true && !empty($alt_text)) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
817
            if ($show_text) {
818
                $img = "$img $alt_text";
819
            }
820
        }
821
822
        return $img;
823
    }
824
825
    /**
826
     * Returns the htmlcode for an image.
827
     *
828
     * @param string $image_path            the filename of the file (in the main/img/ folder
829
     * @param string $alt_text              the alt text (probably a language variable)
830
     * @param array  $additional_attributes (for instance height, width, onclick, ...)
831
     * @param bool   $filterPath            Optional. Whether filter the image path. Default is true
832
     *
833
     * @return string
834
     *
835
     * @author Julio Montoya 2010
836
     */
837
    public static function img(
838
        $image_path,
839
        $alt_text = '',
840
        $additional_attributes = null,
841
        $filterPath = true
842
    ) {
843
        if (empty($image_path)) {
844
            return '';
845
        }
846
        // Sanitizing the parameter $image_path
847
        if ($filterPath) {
848
            $image_path = Security::filter_img_path($image_path);
849
        }
850
851
        // alt text = the image name if there is none provided (for XHTML compliance)
852
        if ('' == $alt_text) {
853
            $alt_text = basename($image_path);
854
        }
855
856
        if (empty($additional_attributes)) {
857
            $additional_attributes = [];
858
        }
859
860
        $additional_attributes['src'] = $image_path;
861
862
        if (empty($additional_attributes['alt'])) {
863
            $additional_attributes['alt'] = $alt_text;
864
        }
865
        if (empty($additional_attributes['title'])) {
866
            $additional_attributes['title'] = $alt_text;
867
        }
868
869
        return self::tag('img', '', $additional_attributes);
870
    }
871
872
    /**
873
     * Returns the htmlcode for a tag (h3, h1, div, a, button), etc.
874
     *
875
     * @param string $tag                   the tag name
876
     * @param string $content               the tag's content
877
     * @param array  $additional_attributes (for instance height, width, onclick, ...)
878
     *
879
     * @return string
880
     *
881
     * @author Julio Montoya 2010
882
     */
883
    public static function tag($tag, $content, $additional_attributes = [])
884
    {
885
        $attribute_list = '';
886
        // Managing the additional attributes
887
        if (!empty($additional_attributes) && is_array($additional_attributes)) {
888
            $attribute_list = '';
889
            foreach ($additional_attributes as $key => &$value) {
890
                $attribute_list .= $key.'="'.$value.'" ';
891
            }
892
        }
893
        //some tags don't have this </XXX>
894
        if (in_array($tag, ['img', 'input', 'br'])) {
895
            $return_value = '<'.$tag.' '.$attribute_list.' />';
896
        } else {
897
            $return_value = '<'.$tag.' '.$attribute_list.' >'.$content.'</'.$tag.'>';
898
        }
899
900
        return $return_value;
901
    }
902
903
    /**
904
     * Creates a URL anchor.
905
     *
906
     * @param string $name
907
     * @param string $url
908
     * @param array  $attributes
909
     *
910
     * @return string
911
     */
912
    public static function url($name, $url, $attributes = [])
913
    {
914
        if (!empty($url)) {
915
            $url = preg_replace('#&amp;#', '&', $url);
916
            $url = htmlspecialchars($url, ENT_QUOTES, 'UTF-8');
917
            $attributes['href'] = $url;
918
        }
919
920
        return self::tag('a', $name, $attributes);
921
    }
922
923
    /**
924
     * Creates a div tag.
925
     *
926
     * @param string $content
927
     * @param array  $attributes
928
     *
929
     * @return string
930
     */
931
    public static function div($content, $attributes = [])
932
    {
933
        return self::tag('div', $content, $attributes);
934
    }
935
936
    /**
937
     * Creates a span tag.
938
     */
939
    public static function span($content, $attributes = [])
940
    {
941
        return self::tag('span', $content, $attributes);
942
    }
943
944
    /**
945
     * Displays an HTML input tag.
946
     */
947
    public static function input($type, $name, $value, $attributes = [])
948
    {
949
        if (isset($type)) {
950
            $attributes['type'] = $type;
951
        }
952
        if (isset($name)) {
953
            $attributes['name'] = $name;
954
        }
955
        if (isset($value)) {
956
            $attributes['value'] = $value;
957
        }
958
959
        return self::tag('input', '', $attributes);
960
    }
961
962
    /**
963
     * @param $name
964
     * @param $value
965
     * @param array $attributes
966
     *
967
     * @return string
968
     */
969
    public static function button($name, $value, $attributes = [])
970
    {
971
        if (!empty($name)) {
972
            $attributes['name'] = $name;
973
        }
974
975
        return self::tag('button', $value, $attributes);
976
    }
977
978
    /**
979
     * Displays an HTML select tag.
980
     *
981
     * @param string $name
982
     * @param array  $values
983
     * @param int    $default
984
     * @param array  $extra_attributes
985
     * @param bool   $show_blank_item
986
     * @param string $blank_item_text
987
     *
988
     * @return string
989
     */
990
    public static function select(
991
        $name,
992
        $values,
993
        $default = -1,
994
        $extra_attributes = [],
995
        $show_blank_item = true,
996
        $blank_item_text = ''
997
    ) {
998
        $html = '';
999
        $extra = '';
1000
        $default_id = 'id="'.$name.'" ';
1001
        $extra_attributes = array_merge(['class' => 'form-control'], $extra_attributes);
1002
        foreach ($extra_attributes as $key => $parameter) {
1003
            if ('id' == $key) {
1004
                $default_id = '';
1005
            }
1006
            $extra .= $key.'="'.$parameter.'" ';
1007
        }
1008
        $html .= '<select name="'.$name.'" '.$default_id.' '.$extra.'>';
1009
1010
        if ($show_blank_item) {
1011
            if (empty($blank_item_text)) {
1012
                $blank_item_text = get_lang('Select');
1013
            } else {
1014
                $blank_item_text = Security::remove_XSS($blank_item_text);
1015
            }
1016
            $html .= self::tag(
1017
                'option',
1018
                '-- '.$blank_item_text.' --',
1019
                ['value' => '-1']
1020
            );
1021
        }
1022
        if ($values) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $values of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
1023
            foreach ($values as $key => $value) {
1024
                if (is_array($value) && isset($value['name'])) {
1025
                    $value = $value['name'];
1026
                }
1027
                $html .= '<option value="'.$key.'"';
1028
1029
                if (is_array($default)) {
1030
                    foreach ($default as $item) {
1031
                        if ($item == $key) {
1032
                            $html .= ' selected="selected"';
1033
                            break;
1034
                        }
1035
                    }
1036
                } else {
1037
                    if ($default == $key) {
1038
                        $html .= ' selected="selected"';
1039
                    }
1040
                }
1041
1042
                $html .= '>'.$value.'</option>';
1043
            }
1044
        }
1045
        $html .= '</select>';
1046
1047
        return $html;
1048
    }
1049
1050
    /**
1051
     * Creates a tab menu
1052
     * Requirements: declare the jquery, jquery-ui libraries + the jquery-ui.css
1053
     * in the $htmlHeadXtra variable before the display_header
1054
     * Add this script.
1055
     *
1056
     * @example
1057
     * <script>
1058
                </script>
1059
     * @param array  $headers       list of the tab titles
1060
     * @param array  $items
1061
     * @param string $id            id of the container of the tab in the example "tabs"
1062
     * @param array  $attributes    for the ul
1063
     * @param array  $ul_attributes
1064
     * @param string $selected
1065
     *
1066
     * @return string
1067
     */
1068
    public static function tabs(
1069
        $headers,
1070
        $items,
1071
        $id = 'tabs',
1072
        $attributes = [],
1073
        $ul_attributes = [],
1074
        $selected = ''
1075
    ) {
1076
        if (empty($headers) || 0 == count($headers)) {
1077
            return '';
1078
        }
1079
1080
        $lis = '';
1081
        $i = 1;
1082
        foreach ($headers as $item) {
1083
            $active = '';
1084
            if (1 == $i) {
1085
                $active = ' active';
1086
            }
1087
1088
            if (!empty($selected)) {
1089
                $active = '';
1090
                if ($selected == $i) {
1091
                    $active = ' active';
1092
                }
1093
            }
1094
1095
            $item = self::tag(
1096
                'a',
1097
                $item,
1098
                [
1099
                    'href' => '#'.$id.'-'.$i,
1100
                    'class' => 'nav-item nav-link '.$active,
1101
                    'id' => $id.$i.'-tab',
1102
                    'data-toggle' => 'tab',
1103
                    'role' => 'tab',
1104
                    'aria-controls' => $id.'-'.$i,
1105
                    'aria-selected' => $selected,
1106
                ]
1107
            );
1108
            $lis .= $item;
1109
            $i++;
1110
        }
1111
1112
        $ul = self::tag(
1113
            'nav',
1114
            $lis,
1115
            [
1116
                'id' => 'ul_'.$id,
1117
                'class' => 'nav nav-tabs',
1118
                'role' => 'tablist',
1119
            ]
1120
        );
1121
1122
        $i = 1;
1123
        $divs = '';
1124
        foreach ($items as $content) {
1125
            $active = '';
1126
            if (1 == $i) {
1127
                $active = ' show active';
1128
            }
1129
1130
            if (!empty($selected)) {
1131
                $active = '';
1132
                if ($selected == $i) {
1133
                    $active = ' show active';
1134
                }
1135
            }
1136
1137
            $divs .= self::tag(
1138
                'div',
1139
                $content,
1140
                [
1141
                    'id' => $id.'-'.$i,
1142
                    'class' => 'tab-pane fade '.$active,
1143
                    'role' => 'tabpanel',
1144
                    'aria-labelledby' => $id.$i.'-tab',
1145
                ]
1146
            );
1147
            $i++;
1148
        }
1149
1150
        $attributes['id'] = $id;
1151
        $attributes['class'] = 'tab_wrapper';
1152
1153
        $html = self::tag(
1154
            'div',
1155
            $ul.
1156
            self::tag('div', $divs, ['class' => 'tab-content']),
1157
            $attributes
1158
        );
1159
1160
        return $html;
1161
    }
1162
1163
    /**
1164
     * @param $headers
1165
     * @param null $selected
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $selected is correct as it would always require null to be passed?
Loading history...
1166
     *
1167
     * @return string
1168
     */
1169
    public static function tabsOnlyLink($headers, $selected = null)
1170
    {
1171
        $id = uniqid('tabs_');
1172
        $i = 1;
1173
        $lis = null;
1174
        foreach ($headers as $item) {
1175
            $class = null;
1176
            if ($i == $selected) {
1177
                $class = 'active';
1178
            }
1179
            $item = self::tag(
1180
                'a',
1181
                $item['content'],
1182
                [
1183
                    'id' => $id.'-'.$i,
1184
                    'href' => $item['url'],
1185
                    'class' => 'nav-link '.$class,
1186
                ]
1187
            );
1188
            $lis .= self::tag('li', $item, ['class' => 'nav-item']);
1189
            $i++;
1190
        }
1191
1192
        return self::tag(
1193
            'ul',
1194
            $lis,
1195
            ['class' => 'nav nav-tabs']
1196
        );
1197
    }
1198
1199
    /**
1200
     * In order to display a grid using jqgrid you have to:.
1201
     *
1202
     * @example
1203
     * After your Display::display_header function you have to add the nex javascript code:
1204
     * <script>
1205
     *   echo Display::grid_js('my_grid_name', $url,$columns, $column_model, $extra_params,[]);
1206
     *   // for more information of this function check the grid_js() function
1207
     * </script>
1208
     * //Then you have to call the grid_html
1209
     * echo Display::grid_html('my_grid_name');
1210
     * As you can see both function use the same "my_grid_name" this is very important otherwise nothing will work
1211
     *
1212
     * @param   string  the div id, this value must be the same with the first parameter of Display::grid_js()
1213
     *
1214
     * @return string html
1215
     */
1216
    public static function grid_html($div_id)
1217
    {
1218
        $table = self::tag('table', '', ['id' => $div_id]);
1219
        $table .= self::tag('div', '', ['id' => $div_id.'_pager']);
1220
1221
        return $table;
1222
    }
1223
1224
    /**
1225
     * @param string $label
1226
     * @param string $form_item
1227
     *
1228
     * @return string
1229
     */
1230
    public static function form_row($label, $form_item)
1231
    {
1232
        $label = self::tag('label', $label, ['class' => 'col-sm-2 control-label']);
1233
        $form_item = self::div($form_item, ['class' => 'col-sm-10']);
1234
1235
        return self::div($label.$form_item, ['class' => 'form-group']);
1236
    }
1237
1238
    /**
1239
     * This is a wrapper to use the jqgrid in Chamilo.
1240
     * For the other jqgrid options visit http://www.trirand.com/jqgridwiki/doku.php?id=wiki:options
1241
     * This function need to be in the ready jquery function
1242
     * example --> $(function() { <?php echo Display::grid_js('grid' ...); ?> }
1243
     * In order to work this function needs the Display::grid_html function with the same div id.
1244
     *
1245
     * @param string $div_id       div id
1246
     * @param string $url          url where the jqgrid will ask for data (if datatype = json)
1247
     * @param array  $column_names Visible columns (you should use get_lang).
1248
     *                             An array in which we place the names of the columns.
1249
     *                             This is the text that appears in the head of the grid (Header layer).
1250
     *                             Example: colname   {name:'date',     index:'date',   width:120, align:'right'},
1251
     * @param array  $column_model the column model :  Array which describes the parameters of the columns.
1252
     *                             This is the most important part of the grid.
1253
     *                             For a full description of all valid values see colModel API. See the url above.
1254
     * @param array  $extra_params extra parameters
1255
     * @param array  $data         data that will be loaded
1256
     * @param string $formatter    A string that will be appended to the JSON returned
1257
     * @param bool   $fixed_width  not implemented yet
1258
     *
1259
     * @return string the js code
1260
     */
1261
    public static function grid_js(
1262
        $div_id,
1263
        $url,
1264
        $column_names,
1265
        $column_model,
1266
        $extra_params,
1267
        $data = [],
1268
        $formatter = '',
1269
        $fixed_width = false
1270
    ) {
1271
        $obj = new stdClass();
1272
        $obj->first = 'first';
1273
1274
        if (!empty($url)) {
1275
            $obj->url = $url;
1276
        }
1277
1278
        // Needed it in order to render the links/html in the grid
1279
        foreach ($column_model as &$columnModel) {
1280
            if (!isset($columnModel['formatter'])) {
1281
                $columnModel['formatter'] = '';
1282
            }
1283
        }
1284
1285
        //This line should only be used/modified in case of having characters
1286
        // encoding problems - see #6159
1287
        //$column_names = array_map("utf8_encode", $column_names);
1288
        $obj->colNames = $column_names;
1289
        $obj->colModel = $column_model;
1290
        $obj->pager = '#'.$div_id.'_pager';
1291
        $obj->datatype = 'json';
1292
        $obj->viewrecords = 'true';
1293
        $obj->guiStyle = 'bootstrap4';
1294
        $obj->iconSet = 'fontAwesomeSolid';
1295
        $all_value = 10000000;
1296
1297
        // Sets how many records we want to view in the grid
1298
        $obj->rowNum = 20;
1299
1300
        // Default row quantity
1301
        if (!isset($extra_params['rowList'])) {
1302
            $extra_params['rowList'] = [20, 50, 100, 500, 1000, $all_value];
1303
            $rowList = api_get_configuration_value('table_row_list');
1304
            if (!empty($rowList) && isset($rowList['options'])) {
1305
                $rowList = $rowList['options'];
1306
                $rowList[] = $all_value;
1307
            }
1308
            $extra_params['rowList'] = $rowList;
1309
        }
1310
1311
        $defaultRow = api_get_configuration_value('table_default_row');
1312
        if (!empty($defaultRow)) {
1313
            $obj->rowNum = (int) $defaultRow;
1314
        }
1315
1316
        $json = '';
1317
        if (!empty($extra_params['datatype'])) {
1318
            $obj->datatype = $extra_params['datatype'];
1319
        }
1320
1321
        // Row even odd style.
1322
        $obj->altRows = true;
1323
        if (!empty($extra_params['altRows'])) {
1324
            $obj->altRows = $extra_params['altRows'];
1325
        }
1326
1327
        if (!empty($extra_params['sortname'])) {
1328
            $obj->sortname = $extra_params['sortname'];
1329
        }
1330
1331
        if (!empty($extra_params['sortorder'])) {
1332
            $obj->sortorder = $extra_params['sortorder'];
1333
        }
1334
1335
        if (!empty($extra_params['rowList'])) {
1336
            $obj->rowList = $extra_params['rowList'];
1337
        }
1338
1339
        if (!empty($extra_params['rowNum'])) {
1340
            $obj->rowNum = $extra_params['rowNum'];
1341
        } else {
1342
            // Try to load max rows from Session
1343
            $urlInfo = parse_url($url);
1344
            if (isset($urlInfo['query'])) {
1345
                parse_str($urlInfo['query'], $query);
1346
                if (isset($query['a'])) {
1347
                    $action = $query['a'];
1348
                    // This value is set in model.ajax.php
1349
                    $savedRows = Session::read('max_rows_'.$action);
1350
                    if (!empty($savedRows)) {
1351
                        $obj->rowNum = $savedRows;
1352
                    }
1353
                }
1354
            }
1355
        }
1356
1357
        if (!empty($extra_params['viewrecords'])) {
1358
            $obj->viewrecords = $extra_params['viewrecords'];
1359
        }
1360
1361
        $beforeSelectRow = null;
1362
        if (isset($extra_params['beforeSelectRow'])) {
1363
            $beforeSelectRow = 'beforeSelectRow: '.$extra_params['beforeSelectRow'].', ';
1364
            unset($extra_params['beforeSelectRow']);
1365
        }
1366
1367
        $beforeProcessing = '';
1368
        if (isset($extra_params['beforeProcessing'])) {
1369
            $beforeProcessing = 'beforeProcessing : function() { '.$extra_params['beforeProcessing'].' },';
1370
            unset($extra_params['beforeProcessing']);
1371
        }
1372
1373
        $beforeRequest = '';
1374
        if (isset($extra_params['beforeRequest'])) {
1375
            $beforeRequest = 'beforeRequest : function() { '.$extra_params['beforeRequest'].' },';
1376
            unset($extra_params['beforeRequest']);
1377
        }
1378
1379
        $gridComplete = '';
1380
        if (isset($extra_params['gridComplete'])) {
1381
            $gridComplete = 'gridComplete : function() { '.$extra_params['gridComplete'].' },';
1382
            unset($extra_params['gridComplete']);
1383
        }
1384
1385
        // Adding extra params
1386
        if (!empty($extra_params)) {
1387
            foreach ($extra_params as $key => $element) {
1388
                // the groupHeaders key gets a special treatment
1389
                if ('groupHeaders' != $key) {
1390
                    $obj->$key = $element;
1391
                }
1392
            }
1393
        }
1394
1395
        // Adding static data.
1396
        if (!empty($data)) {
1397
            $data_var = $div_id.'_data';
1398
            $json .= ' var '.$data_var.' = '.json_encode($data).';';
1399
            $obj->data = $data_var;
1400
            $obj->datatype = 'local';
1401
            $json .= "\n";
1402
        }
1403
1404
        $obj->end = 'end';
1405
1406
        $json_encode = json_encode($obj);
1407
1408
        if (!empty($data)) {
1409
            //Converts the "data":"js_variable" to "data":js_variable,
1410
            // otherwise it will not work
1411
            $json_encode = str_replace('"data":"'.$data_var.'"', '"data":'.$data_var.'', $json_encode);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $data_var does not seem to be defined for all execution paths leading up to this point.
Loading history...
1412
        }
1413
1414
        // Fixing true/false js values that doesn't need the ""
1415
        $json_encode = str_replace(':"true"', ':true', $json_encode);
1416
        // wrap_cell is not a valid jqgrid attributes is a hack to wrap a text
1417
        $json_encode = str_replace('"wrap_cell":true', 'cellattr : function(rowId, value, rowObject, colModel, arrData) { return \'class = "jqgrid_whitespace"\'; }', $json_encode);
1418
        $json_encode = str_replace(':"false"', ':false', $json_encode);
1419
        $json_encode = str_replace('"formatter":"action_formatter"', 'formatter:action_formatter', $json_encode);
1420
        $json_encode = str_replace('"formatter":"extra_formatter"', 'formatter:extra_formatter', $json_encode);
1421
        $json_encode = str_replace(['{"first":"first",', '"end":"end"}'], '', $json_encode);
1422
1423
        if (api_get_configuration_value('allow_compilatio_tool') &&
1424
            (false !== strpos($_SERVER['REQUEST_URI'], 'work/work.php') ||
1425
             false != strpos($_SERVER['REQUEST_URI'], 'work/work_list_all.php')
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing strpos($_SERVER['REQUEST...ork/work_list_all.php') of type integer to the boolean false. If you are specifically checking for non-zero, consider using something more explicit like > 0 or !== 0 instead.
Loading history...
1426
            )
1427
        ) {
1428
            $json_encode = str_replace('"function () { compilatioInit() }"',
1429
                'function () { compilatioInit() }',
1430
                $json_encode
1431
            );
1432
        }
1433
        // Creating the jqgrid element.
1434
        $json .= '$("#'.$div_id.'").jqGrid({';
1435
        //$json .= $beforeSelectRow;
1436
        $json .= $gridComplete;
1437
        $json .= $beforeProcessing;
1438
        $json .= $beforeRequest;
1439
        $json .= $json_encode;
1440
        $json .= '});';
1441
1442
        // Grouping headers option
1443
        if (isset($extra_params['groupHeaders'])) {
1444
            $groups = '';
1445
            foreach ($extra_params['groupHeaders'] as $group) {
1446
                //{ "startColumnName" : "courses", "numberOfColumns" : 1, "titleText" : "Order Info" },
1447
                $groups .= '{ "startColumnName" : "'.$group['startColumnName'].'", "numberOfColumns" : '.$group['numberOfColumns'].', "titleText" : "'.$group['titleText'].'" },';
1448
            }
1449
            $json .= '$("#'.$div_id.'").jqGrid("setGroupHeaders", {
1450
                "useColSpanStyle" : false,
1451
                "groupHeaders"    : [
1452
                    '.$groups.'
1453
                ]
1454
            });';
1455
        }
1456
1457
        $all_text = addslashes(get_lang('All'));
1458
        $json .= '$("'.$obj->pager.' option[value='.$all_value.']").text("'.$all_text.'");';
1459
        $json .= "\n";
1460
        // Adding edit/delete icons.
1461
        $json .= $formatter;
1462
1463
        return $json;
1464
    }
1465
1466
    /**
1467
     * @param array $headers
1468
     * @param array $rows
1469
     * @param array $attributes
1470
     *
1471
     * @return string
1472
     */
1473
    public static function table($headers, $rows, $attributes = [])
1474
    {
1475
        if (empty($attributes)) {
1476
            $attributes['class'] = 'data_table';
1477
        }
1478
        $table = new HTML_Table($attributes);
1479
        $row = 0;
1480
        $column = 0;
1481
1482
        // Course headers
1483
        if (!empty($headers)) {
1484
            foreach ($headers as $item) {
1485
                $table->setHeaderContents($row, $column, $item);
1486
                $column++;
1487
            }
1488
            $row = 1;
1489
            $column = 0;
1490
        }
1491
1492
        if (!empty($rows)) {
1493
            foreach ($rows as $content) {
1494
                $table->setCellContents($row, $column, $content);
1495
                $row++;
1496
            }
1497
        }
1498
1499
        return $table->toHtml();
1500
    }
1501
1502
    /**
1503
     * Returns the "what's new" icon notifications.
1504
     *
1505
     * The general logic of this function is to track the last time the user
1506
     * entered the course and compare to what has changed inside this course
1507
     * since then, based on the item_property table inside this course. Note that,
1508
     * if the user never entered the course before, he will not see notification
1509
     * icons. This function takes session ID into account (if any) and only shows
1510
     * the corresponding notifications.
1511
     *
1512
     * @param array $courseInfo Course information array, containing at least elements 'db' and 'k'
1513
     * @param bool  $loadAjax
1514
     *
1515
     * @return string The HTML link to be shown next to the course
1516
     */
1517
    public static function show_notification($courseInfo, $loadAjax = true)
1518
    {
1519
        if (empty($courseInfo)) {
1520
            return '';
1521
        }
1522
1523
        return '';
1524
1525
        $t_track_e_access = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LASTACCESS);
0 ignored issues
show
Unused Code introduced by
$t_track_e_access = Data...TIC_TRACK_E_LASTACCESS) is not reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
1526
        $course_tool_table = Database::get_course_table(TABLE_TOOL_LIST);
1527
        $tool_edit_table = Database::get_course_table(TABLE_ITEM_PROPERTY);
1528
        $course_code = Database::escape_string($courseInfo['code']);
1529
1530
        $user_id = api_get_user_id();
1531
        $course_id = (int) $courseInfo['real_id'];
1532
        $sessionId = (int) $courseInfo['id_session'];
1533
        $status = (int) $courseInfo['status'];
1534
1535
        $loadNotificationsByAjax = api_get_configuration_value('user_portal_load_notification_by_ajax');
1536
1537
        if ($loadNotificationsByAjax) {
1538
            if ($loadAjax) {
1539
                $id = 'notification_'.$course_id.'_'.$sessionId.'_'.$status;
1540
                Session::write($id, true);
1541
1542
                return '<span id ="'.$id.'" class="course_notification"></span>';
1543
            }
1544
        }
1545
1546
        // Get the user's last access dates to all tools of this course
1547
        $sql = "SELECT *
1548
                FROM $t_track_e_access
1549
                WHERE
1550
                    c_id = $course_id AND
1551
                    access_user_id = '$user_id' AND
1552
                    access_session_id ='".$sessionId."'
1553
                ORDER BY access_date DESC
1554
                LIMIT 1
1555
                ";
1556
        $result = Database::query($sql);
1557
1558
        // latest date by default is the creation date
1559
        $latestDate = $courseInfo['creation_date'];
1560
        if (Database::num_rows($result)) {
1561
            $row = Database::fetch_array($result, 'ASSOC');
1562
            $latestDate = $row['access_date'];
1563
        }
1564
1565
        $sessionCondition = api_get_session_condition(
1566
            $sessionId,
1567
            true,
1568
            false,
1569
            'session_id'
1570
        );
1571
1572
        $hideTools = [TOOL_NOTEBOOK, TOOL_CHAT];
1573
        // Get current tools in course
1574
        $sql = "SELECT name
1575
                FROM $course_tool_table
1576
                WHERE
1577
                    c_id = $course_id AND
1578
                    visibility = '1' AND
1579
                    name NOT IN ('".implode("','", $hideTools)." ')
1580
                ";
1581
        $result = Database::query($sql);
1582
        $tools = Database::store_result($result);
1583
1584
        $group_ids = GroupManager::get_group_ids($courseInfo['real_id'], $user_id);
1585
        $group_ids[] = 0; //add group 'everyone'
1586
        $notifications = [];
1587
        if ($tools) {
1588
            foreach ($tools as $tool) {
1589
                $toolName = $tool['name'];
1590
                $toolName = Database::escape_string($toolName);
1591
                // Fix to get student publications
1592
                $toolCondition = " tool = '$toolName' AND ";
1593
                if ('student_publication' == $toolName || 'work' == $toolName) {
1594
                    $toolCondition = " (tool = 'work' OR tool = 'student_publication') AND ";
1595
                }
1596
1597
                $toolName = addslashes($toolName);
1598
1599
                $sql = "SELECT * FROM $tool_edit_table
1600
                        WHERE
1601
                            c_id = $course_id AND
1602
                            $toolCondition
1603
                            lastedit_type NOT LIKE '%Deleted%' AND
1604
                            lastedit_type NOT LIKE '%deleted%' AND
1605
                            lastedit_type NOT LIKE '%DocumentInvisible%' AND
1606
                            lastedit_date > '$latestDate' AND
1607
                            lastedit_user_id != $user_id $sessionCondition AND
1608
                            visibility != 2 AND
1609
                            (to_user_id IN ('$user_id', '0') OR to_user_id IS NULL) AND
1610
                            (to_group_id IN ('".implode("','", $group_ids)."') OR to_group_id IS NULL)
1611
                        ORDER BY lastedit_date DESC
1612
                        LIMIT 1";
1613
                $result = Database::query($sql);
1614
1615
                $latestChange = Database::fetch_array($result, 'ASSOC');
1616
1617
                if ($latestChange) {
1618
                    $latestChange['link'] = $tool['link'];
1619
                    $latestChange['image'] = $tool['image'];
1620
                    $latestChange['tool'] = $tool['name'];
1621
                    $notifications[$toolName] = $latestChange;
1622
                }
1623
            }
1624
        }
1625
1626
        // Show all tool icons where there is something new.
1627
        $return = '';
1628
        foreach ($notifications as $notification) {
1629
            $toolName = $notification['tool'];
1630
            if (!(
1631
                    '1' == $notification['visibility'] ||
1632
                    ('1' == $status && '0' == $notification['visibility']) ||
1633
                    !isset($notification['visibility'])
1634
                )
1635
            ) {
1636
                continue;
1637
            }
1638
1639
            if (TOOL_SURVEY == $toolName) {
1640
                $survey_info = SurveyManager::get_survey($notification['ref'], 0, $course_code);
1641
                if (!empty($survey_info)) {
1642
                    /*$invited_users = SurveyUtil::get_invited_users(
1643
                        $survey_info['code'],
1644
                        $course_code
1645
                    );
1646
                    if (!in_array($user_id, $invited_users['course_users'])) {
1647
                        continue;
1648
                    }*/
1649
                }
1650
            }
1651
1652
            if (TOOL_LEARNPATH == $notification['tool']) {
1653
                if (!learnpath::is_lp_visible_for_student($notification['ref'], $user_id, $courseInfo)) {
1654
                    continue;
1655
                }
1656
            }
1657
1658
            if (TOOL_DROPBOX == $notification['tool']) {
1659
                $notification['link'] = 'dropbox/dropbox_download.php?id='.$notification['ref'];
1660
            }
1661
1662
            if ('work' == $notification['tool'] &&
1663
                'DirectoryCreated' == $notification['lastedit_type']
1664
            ) {
1665
                $notification['lastedit_type'] = 'WorkAdded';
1666
            }
1667
1668
            $lastDate = api_get_local_time($notification['lastedit_date']);
1669
            $type = $notification['lastedit_type'];
1670
            if ('CalendareventVisible' == $type) {
1671
                $type = 'Visible';
1672
            }
1673
            $label = get_lang('Since your latest visit').": ".get_lang($type)." ($lastDate)";
1674
1675
            if (false === strpos($notification['link'], '?')) {
1676
                $notification['link'] = $notification['link'].'?notification=1';
1677
            } else {
1678
                $notification['link'] = $notification['link'].'&notification=1';
1679
            }
1680
1681
            $image = substr($notification['image'], 0, -4).'.png';
1682
1683
            $return .= self::url(
1684
                self::return_icon($image, $label),
1685
                api_get_path(WEB_CODE_PATH).
1686
                $notification['link'].'&cidReq='.$course_code.
1687
                '&ref='.$notification['ref'].
1688
                '&gid='.$notification['to_group_id'].
1689
                '&sid='.$sessionId
1690
            ).PHP_EOL;
1691
        }
1692
1693
        return $return;
1694
    }
1695
1696
    /**
1697
     * Get the session box details as an array.
1698
     *
1699
     * @todo check session visibility.
1700
     *
1701
     * @param int $session_id
1702
     *
1703
     * @return array Empty array or session array
1704
     *               ['title'=>'...','category'=>'','dates'=>'...','coach'=>'...','active'=>true/false,'session_category_id'=>int]
1705
     */
1706
    public static function getSessionTitleBox($session_id)
1707
    {
1708
        $session_info = api_get_session_info($session_id);
1709
        $coachInfo = [];
1710
        if (!empty($session_info['id_coach'])) {
1711
            $coachInfo = api_get_user_info($session_info['id_coach']);
1712
        }
1713
1714
        $session = [];
1715
        $session['category_id'] = $session_info['session_category_id'];
1716
        $session['title'] = $session_info['name'];
1717
        $session['coach_id'] = $session['id_coach'] = $session_info['id_coach'];
1718
        $session['dates'] = '';
1719
        $session['coach'] = '';
1720
        if ('true' === api_get_setting('show_session_coach') && isset($coachInfo['complete_name'])) {
1721
            $session['coach'] = get_lang('General coach').': '.$coachInfo['complete_name'];
1722
        }
1723
        $active = false;
1724
        if (('0000-00-00 00:00:00' == $session_info['access_end_date'] &&
1725
            '0000-00-00 00:00:00' == $session_info['access_start_date']) ||
1726
            (empty($session_info['access_end_date']) && empty($session_info['access_start_date']))
1727
        ) {
1728
            if (isset($session_info['duration']) && !empty($session_info['duration'])) {
1729
                $daysLeft = SessionManager::getDayLeftInSession($session_info, api_get_user_id());
1730
                $session['duration'] = $daysLeft >= 0
1731
                    ? sprintf(get_lang('This session has a maximum duration. Only %s days to go.'), $daysLeft)
1732
                    : get_lang('You are already registered but your allowed access time has expired.');
1733
            }
1734
            $active = true;
1735
        } else {
1736
            $dates = SessionManager::parseSessionDates($session_info, true);
1737
            $session['dates'] = $dates['access'];
1738
            if ('true' === api_get_setting('show_session_coach') && isset($coachInfo['complete_name'])) {
1739
                $session['coach'] = $coachInfo['complete_name'];
1740
            }
1741
            //$active = $date_start <= $now && $date_end >= $now;
1742
        }
1743
        $session['active'] = $active;
1744
        $session['session_category_id'] = $session_info['session_category_id'];
1745
        $session['visibility'] = $session_info['visibility'];
1746
        $session['num_users'] = $session_info['nbr_users'];
1747
        $session['num_courses'] = $session_info['nbr_courses'];
1748
        $session['description'] = $session_info['description'];
1749
        $session['show_description'] = $session_info['show_description'];
1750
        //$session['image'] = SessionManager::getSessionImage($session_info['id']);
1751
        $session['url'] = api_get_path(WEB_CODE_PATH).'session/index.php?session_id='.$session_info['id'];
1752
1753
        $entityManager = Database::getManager();
1754
        $fieldValuesRepo = $entityManager->getRepository(ExtraFieldValues::class);
1755
        $extraFieldValues = $fieldValuesRepo->getVisibleValues(
1756
            ExtraField::SESSION_FIELD_TYPE,
1757
            $session_id
1758
        );
1759
1760
        $session['extra_fields'] = [];
1761
        /** @var ExtraFieldValues $value */
1762
        foreach ($extraFieldValues as $value) {
1763
            if (empty($value)) {
1764
                continue;
1765
            }
1766
            $session['extra_fields'][] = [
1767
                'field' => [
1768
                    'variable' => $value->getField()->getVariable(),
1769
                    'display_text' => $value->getField()->getDisplayText(),
1770
                ],
1771
                'value' => $value->getValue(),
1772
            ];
1773
        }
1774
1775
        return $session;
1776
    }
1777
1778
    /**
1779
     * Return the five star HTML.
1780
     *
1781
     * @param string $id              of the rating ul element
1782
     * @param string $url             that will be added (for jquery see hot_courses.tpl)
1783
     * @param array  $point_info      point info array see function CourseManager::get_course_ranking()
1784
     * @param bool   $add_div_wrapper add a div wrapper
1785
     *
1786
     * @return string
1787
     */
1788
    public static function return_rating_system(
1789
        $id,
1790
        $url,
1791
        $point_info = [],
1792
        $add_div_wrapper = true
1793
    ) {
1794
        $number_of_users_who_voted = isset($point_info['users_who_voted']) ? $point_info['users_who_voted'] : null;
1795
        $percentage = isset($point_info['point_average']) ? $point_info['point_average'] : 0;
1796
1797
        if (!empty($percentage)) {
1798
            $percentage = $percentage * 125 / 100;
1799
        }
1800
        $accesses = isset($point_info['accesses']) ? $point_info['accesses'] : 0;
1801
        $star_label = sprintf(get_lang('%s stars out of 5'), $point_info['point_average_star']);
1802
1803
        $html = '<section class="rating-widget">';
1804
        $html .= '<div class="rating-stars"><ul id="stars">';
1805
        $html .= '<li class="star" data-link="'.$url.'&amp;star=1" title="Poor" data-value="1"><i class="fa fa-star fa-fw"></i></li>
1806
                 <li class="star" data-link="'.$url.'&amp;star=2" title="Fair" data-value="2"><i class="fa fa-star fa-fw"></i></li>
1807
                 <li class="star" data-link="'.$url.'&amp;star=3" title="Good" data-value="3"><i class="fa fa-star fa-fw"></i></li>
1808
                 <li class="star" data-link="'.$url.'&amp;star=4" title="Excellent" data-value="4"><i class="fa fa-star fa-fw"></i></li>
1809
                 <li class="star" data-link="'.$url.'&amp;star=5" title="WOW!!!" data-value="5"><i class="fa fa-star fa-fw"></i></li>
1810
        ';
1811
        $html .= '</ul></div>';
1812
        $html .= '</section>';
1813
        $labels = [];
1814
1815
        $labels[] = 1 == $number_of_users_who_voted ? $number_of_users_who_voted.' '.get_lang('Vote') : $number_of_users_who_voted.' '.get_lang('Votes');
1816
        $labels[] = 1 == $accesses ? $accesses.' '.get_lang('Visit') : $accesses.' '.get_lang('Visits');
1817
        $labels[] = $point_info['user_vote'] ? get_lang('Your vote').' ['.$point_info['user_vote'].']' : get_lang('Your vote').' [?] ';
1818
1819
        if (!$add_div_wrapper && api_is_anonymous()) {
1820
            $labels[] = self::tag('span', get_lang('Login to vote'), ['class' => 'error']);
1821
        }
1822
1823
        $html .= self::div(implode(' | ', $labels), ['id' => 'vote_label_'.$id, 'class' => 'vote_label_info']);
1824
        $html .= ' '.self::span(' ', ['id' => 'vote_label2_'.$id]);
1825
1826
        if ($add_div_wrapper) {
1827
            $html = self::div($html, ['id' => 'rating_wrapper_'.$id]);
1828
        }
1829
1830
        return $html;
1831
    }
1832
1833
    /**
1834
     * @param string $title
1835
     * @param string $second_title
1836
     * @param string $size
1837
     * @param bool   $filter
1838
     *
1839
     * @return string
1840
     */
1841
    public static function page_header($title, $second_title = null, $size = 'h2', $filter = true)
1842
    {
1843
        if ($filter) {
1844
            $title = Security::remove_XSS($title);
1845
        }
1846
1847
        if (!empty($second_title)) {
1848
            if ($filter) {
1849
                $second_title = Security::remove_XSS($second_title);
1850
            }
1851
            $title .= "<small> $second_title</small>";
1852
        }
1853
1854
        return '<'.$size.' class="page-header">'.$title.'</'.$size.'>';
1855
    }
1856
1857
    public static function page_header_and_translate($title, $second_title = null)
1858
    {
1859
        $title = get_lang($title);
1860
1861
        return self::page_header($title, $second_title);
1862
    }
1863
1864
    public static function page_subheader_and_translate($title, $second_title = null)
1865
    {
1866
        $title = get_lang($title);
1867
1868
        return self::page_subheader($title, $second_title);
1869
    }
1870
1871
    public static function page_subheader($title, $second_title = null, $size = 'h3', $attributes = [])
1872
    {
1873
        if (!empty($second_title)) {
1874
            $second_title = Security::remove_XSS($second_title);
1875
            $title .= "<small> $second_title<small>";
1876
        }
1877
        $subTitle = self::tag($size, Security::remove_XSS($title), $attributes);
1878
1879
        return $subTitle;
1880
    }
1881
1882
    public static function page_subheader2($title, $second_title = null)
1883
    {
1884
        return self::page_header($title, $second_title, 'h4');
1885
    }
1886
1887
    public static function page_subheader3($title, $second_title = null)
1888
    {
1889
        return self::page_header($title, $second_title, 'h5');
1890
    }
1891
1892
    /**
1893
     * @param array $list
1894
     *
1895
     * @return string|null
1896
     */
1897
    public static function description($list)
1898
    {
1899
        $html = null;
1900
        if (!empty($list)) {
1901
            $html = '<dl class="dl-horizontal">';
1902
            foreach ($list as $item) {
1903
                $html .= '<dt>'.$item['title'].'</dt>';
1904
                $html .= '<dd>'.$item['content'].'</dd>';
1905
            }
1906
            $html .= '</dl>';
1907
        }
1908
1909
        return $html;
1910
    }
1911
1912
    /**
1913
     * @param int    $percentage      int value between 0 and 100
1914
     * @param bool   $show_percentage
1915
     * @param string $extra_info
1916
     * @param string $class           danger/success/infowarning
1917
     *
1918
     * @return string
1919
     */
1920
    public static function bar_progress($percentage, $show_percentage = true, $extra_info = '', $class = '')
1921
    {
1922
        $percentage = (int) $percentage;
1923
        $class = empty($class) ? '' : "progress-bar-$class";
1924
1925
        $div = '<div class="progress">
1926
                <div
1927
                    class="progress-bar progress-bar-striped '.$class.'"
1928
                    role="progressbar"
1929
                    aria-valuenow="'.$percentage.'"
1930
                    aria-valuemin="0"
1931
                    aria-valuemax="100"
1932
                    style="width: '.$percentage.'%;"
1933
                >';
1934
        if ($show_percentage) {
1935
            $div .= $percentage.'%';
1936
        } else {
1937
            if (!empty($extra_info)) {
1938
                $div .= $extra_info;
1939
            }
1940
        }
1941
        $div .= '</div></div>';
1942
1943
        return $div;
1944
    }
1945
1946
    /**
1947
     * @param string $count
1948
     * @param string $type
1949
     *
1950
     * @return string|null
1951
     */
1952
    public static function badge($count, $type = 'warning')
1953
    {
1954
        $class = '';
1955
1956
        switch ($type) {
1957
            case 'success':
1958
                $class = 'bg-success';
1959
                break;
1960
            case 'warning':
1961
                $class = 'bg-warning text-dark';
1962
                break;
1963
            case 'important':
1964
                $class = 'bg-important';
1965
                break;
1966
            case 'info':
1967
                $class = 'bg-info';
1968
                break;
1969
            case 'inverse':
1970
                $class = 'bg-inverse';
1971
                break;
1972
        }
1973
1974
        if (!empty($count)) {
1975
            return ' <span class="badge '.$class.'">'.$count.'</span>';
1976
        }
1977
1978
        return null;
1979
    }
1980
1981
    /**
1982
     * @param array $badge_list
1983
     *
1984
     * @return string
1985
     */
1986
    public static function badge_group($badge_list)
1987
    {
1988
        $html = '<div class="badge-group">';
1989
        foreach ($badge_list as $badge) {
1990
            $html .= $badge;
1991
        }
1992
        $html .= '</div>';
1993
1994
        return $html;
1995
    }
1996
1997
    /**
1998
     * @param string $content
1999
     * @param string $type
2000
     *
2001
     * @return string
2002
     */
2003
    public static function label($content, $type = 'default')
2004
    {
2005
        switch ($type) {
2006
            case 'success':
2007
                $class = 'success';
2008
                break;
2009
            case 'warning':
2010
                $class = 'warning text-dark';
2011
                break;
2012
            case 'important':
2013
            case 'danger':
2014
                $class = 'danger';
2015
                break;
2016
            case 'info':
2017
                $class = 'info';
2018
                break;
2019
            case 'primary':
2020
                $class = 'primary';
2021
                break;
2022
            default:
2023
                $class = 'secondary';
2024
                break;
2025
        }
2026
2027
        $html = '';
2028
        if (!empty($content)) {
2029
            $html = '<span class="badge bg-'.$class.'">';
2030
            $html .= $content;
2031
            $html .= '</span>';
2032
        }
2033
2034
        return $html;
2035
    }
2036
2037
    /**
2038
     * @param array  $items
2039
     * @param string $class
2040
     *
2041
     * @return string|null
2042
     */
2043
    public static function actions($items, $class = 'new_actions')
2044
    {
2045
        $html = null;
2046
        if (!empty($items)) {
2047
            $html = '<div class="'.$class.'"><ul class="nav nav-pills">';
2048
            foreach ($items as $value) {
2049
                $class = null;
2050
                if (isset($value['active']) && $value['active']) {
2051
                    $class = 'class ="active"';
2052
                }
2053
2054
                if (basename($_SERVER['REQUEST_URI']) == basename($value['url'])) {
2055
                    $class = 'class ="active"';
2056
                }
2057
                $html .= "<li $class >";
2058
                $attributes = isset($value['url_attributes']) ? $value['url_attributes'] : [];
2059
                $html .= self::url($value['content'], $value['url'], $attributes);
2060
                $html .= '</li>';
2061
            }
2062
            $html .= '</ul></div>';
2063
            $html .= '<br />';
2064
        }
2065
2066
        return $html;
2067
    }
2068
2069
    /**
2070
     * Prints a tooltip.
2071
     *
2072
     * @param string $text
2073
     * @param string $tip
2074
     *
2075
     * @return string
2076
     */
2077
    public static function tip($text, $tip)
2078
    {
2079
        if (empty($tip)) {
2080
            return $text;
2081
        }
2082
2083
        return self::span(
2084
            $text,
2085
            ['class' => 'boot-tooltip', 'title' => strip_tags($tip)]
2086
        );
2087
    }
2088
2089
    /**
2090
     * @param array  $items
2091
     * @param string $type
2092
     * @param null   $id
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $id is correct as it would always require null to be passed?
Loading history...
2093
     *
2094
     * @return string|null
2095
     */
2096
    public static function generate_accordion($items, $type = 'jquery', $id = null)
2097
    {
2098
        $html = null;
2099
        if (!empty($items)) {
2100
            if (empty($id)) {
2101
                $id = api_get_unique_id();
2102
            }
2103
            if ('jquery' == $type) {
2104
                $html = '<div class="accordion_jquery" id="'.$id.'">'; //using jquery
2105
            } else {
2106
                $html = '<div class="accordion" id="'.$id.'">'; //using bootstrap
2107
            }
2108
2109
            $count = 1;
2110
            foreach ($items as $item) {
2111
                $html .= '<div class="accordion-my-group">';
2112
                $html .= '<div class="accordion-heading">
2113
                            <a class="accordion-toggle" data-toggle="collapse" data-parent="#'.$id.'" href="#collapse'.$count.'">
2114
                            '.$item['title'].'
2115
                            </a>
2116
                          </div>';
2117
2118
                $html .= '<div id="collapse'.$count.'" class="accordion-body">';
2119
                $html .= '<div class="accordion-my-inner">
2120
                            '.$item['content'].'
2121
                            </div>
2122
                          </div>';
2123
            }
2124
            $html .= '</div>';
2125
        }
2126
2127
        return $html;
2128
    }
2129
2130
    /**
2131
     * @param array $buttons
2132
     *
2133
     * @return string
2134
     */
2135
    public static function groupButton($buttons)
2136
    {
2137
        $html = '<div class="btn-group" role="group">';
2138
        foreach ($buttons as $button) {
2139
            $html .= $button;
2140
        }
2141
        $html .= '</div>';
2142
2143
        return $html;
2144
    }
2145
2146
    /**
2147
     * @todo use twig
2148
     *
2149
     * @param string $title
2150
     * @param array  $elements
2151
     * @param bool   $alignToRight
2152
     *
2153
     * @return string
2154
     */
2155
    public static function groupButtonWithDropDown($title, $elements, $alignToRight = false)
2156
    {
2157
        $id = uniqid('dropdown', true);
2158
        $html = '<div class="btn-group" role="group">
2159
                <button
2160
                    id="'.$id.'"
2161
                    class="btn btn-secondary dropdown-toggle"
2162
                    data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
2163
                '.$title.'
2164
                </button>
2165
                <div class="dropdown-menu aria-labelledby="'.$id.'" '.($alignToRight ? 'dropdown-menu-right' : '').'">';
2166
        foreach ($elements as $item) {
2167
            $html .= self::tag(
2168
                'li',
2169
                self::url($item['title'], $item['href'], ['class' => 'dropdown-item'])
2170
            );
2171
        }
2172
        $html .= '</div>
2173
            </div>';
2174
2175
        return $html;
2176
    }
2177
2178
    /**
2179
     * @param string $file
2180
     * @param array  $params
2181
     *
2182
     * @return string|null
2183
     */
2184
    public static function getMediaPlayer($file, $params = [])
2185
    {
2186
        $fileInfo = pathinfo($file);
2187
2188
        $autoplay = isset($params['autoplay']) && 'true' === $params['autoplay'] ? 'autoplay' : '';
2189
        $id = isset($params['id']) ? $params['id'] : $fileInfo['basename'];
2190
        $width = isset($params['width']) ? 'width="'.$params['width'].'"' : null;
2191
        $class = isset($params['class']) ? ' class="'.$params['class'].'"' : null;
2192
2193
        switch ($fileInfo['extension']) {
2194
            case 'mp3':
2195
            case 'webm':
2196
                $html = '<audio id="'.$id.'" '.$class.' controls '.$autoplay.' '.$width.' src="'.$params['url'].'" >';
2197
                $html .= '<object width="'.$width.'" height="50" type="application/x-shockwave-flash" data="'.api_get_path(WEB_LIBRARY_PATH).'javascript/mediaelement/flashmediaelement.swf">
2198
                            <param name="movie" value="'.api_get_path(WEB_LIBRARY_PATH).'javascript/mediaelement/flashmediaelement.swf" />
2199
                            <param name="flashvars" value="controls=true&file='.$params['url'].'" />
2200
                          </object>';
2201
                $html .= '</audio>';
2202
2203
                return $html;
2204
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
2205
            case 'wav':
2206
            case 'ogg':
2207
                $html = '<audio width="300px" controls id="'.$id.'" '.$autoplay.' src="'.$params['url'].'" >';
2208
2209
                return $html;
2210
                break;
2211
        }
2212
2213
        return null;
2214
    }
2215
2216
    /**
2217
     * @param int    $nextValue
2218
     * @param array  $list
2219
     * @param int    $current
2220
     * @param int    $fixedValue
2221
     * @param array  $conditions
2222
     * @param string $link
2223
     * @param bool   $isMedia
2224
     * @param bool   $addHeaders
2225
     * @param array  $linkAttributes
2226
     *
2227
     * @return string
2228
     */
2229
    public static function progressPaginationBar(
2230
        $nextValue,
2231
        $list,
2232
        $current,
2233
        $fixedValue = null,
2234
        $conditions = [],
2235
        $link = null,
2236
        $isMedia = false,
2237
        $addHeaders = true,
2238
        $linkAttributes = []
2239
    ) {
2240
        if ($addHeaders) {
2241
            $pagination_size = 'pagination-mini';
2242
            $html = '<div class="exercise_pagination pagination '.$pagination_size.'"><ul>';
2243
        } else {
2244
            $html = null;
2245
        }
2246
        $affectAllItems = false;
2247
        if ($isMedia && isset($fixedValue) && ($nextValue + 1 == $current)) {
2248
            $affectAllItems = true;
2249
        }
2250
        $localCounter = 0;
2251
        foreach ($list as $itemId) {
2252
            $isCurrent = false;
2253
            if ($affectAllItems) {
2254
                $isCurrent = true;
2255
            } else {
2256
                if (!$isMedia) {
2257
                    $isCurrent = $current == ($localCounter + $nextValue + 1) ? true : false;
2258
                }
2259
            }
2260
            $html .= self::parsePaginationItem(
2261
                $itemId,
2262
                $isCurrent,
2263
                $conditions,
2264
                $link,
2265
                $nextValue,
2266
                $isMedia,
2267
                $localCounter,
2268
                $fixedValue,
2269
                $linkAttributes
2270
            );
2271
            $localCounter++;
2272
        }
2273
        if ($addHeaders) {
2274
            $html .= '</ul></div>';
2275
        }
2276
2277
        return $html;
2278
    }
2279
2280
    /**
2281
     * @param int    $itemId
2282
     * @param bool   $isCurrent
2283
     * @param array  $conditions
2284
     * @param string $link
2285
     * @param int    $nextValue
2286
     * @param bool   $isMedia
2287
     * @param int    $localCounter
2288
     * @param int    $fixedValue
2289
     * @param array  $linkAttributes
2290
     *
2291
     * @return string
2292
     */
2293
    public static function parsePaginationItem(
2294
        $itemId,
2295
        $isCurrent,
2296
        $conditions,
2297
        $link,
2298
        $nextValue = 0,
2299
        $isMedia = false,
2300
        $localCounter = null,
2301
        $fixedValue = null,
2302
        $linkAttributes = []
2303
    ) {
2304
        $defaultClass = 'before';
2305
        $class = $defaultClass;
2306
        foreach ($conditions as $condition) {
2307
            $array = isset($condition['items']) ? $condition['items'] : [];
2308
            $class_to_applied = $condition['class'];
2309
            $type = isset($condition['type']) ? $condition['type'] : 'positive';
2310
            $mode = isset($condition['mode']) ? $condition['mode'] : 'add';
2311
            switch ($type) {
2312
                case 'positive':
2313
                    if (in_array($itemId, $array)) {
2314
                        if ('overwrite' == $mode) {
2315
                            $class = " $defaultClass $class_to_applied";
2316
                        } else {
2317
                            $class .= " $class_to_applied";
2318
                        }
2319
                    }
2320
                    break;
2321
                case 'negative':
2322
                    if (!in_array($itemId, $array)) {
2323
                        if ('overwrite' == $mode) {
2324
                            $class = " $defaultClass $class_to_applied";
2325
                        } else {
2326
                            $class .= " $class_to_applied";
2327
                        }
2328
                    }
2329
                    break;
2330
            }
2331
        }
2332
        if ($isCurrent) {
2333
            $class = 'before current';
2334
        }
2335
        if ($isMedia && $isCurrent) {
2336
            $class = 'before current';
2337
        }
2338
        if (empty($link)) {
2339
            $link_to_show = '#';
2340
        } else {
2341
            $link_to_show = $link.($nextValue + $localCounter);
2342
        }
2343
        $label = $nextValue + $localCounter + 1;
2344
        if ($isMedia) {
2345
            $label = ($fixedValue + 1).' '.chr(97 + $localCounter);
2346
            $link_to_show = $link.$fixedValue.'#questionanchor'.$itemId;
2347
        }
2348
        $link = self::url($label.' ', $link_to_show, $linkAttributes);
2349
2350
        return '<li class = "'.$class.'">'.$link.'</li>';
2351
    }
2352
2353
    /**
2354
     * @param int $current
2355
     * @param int $total
2356
     *
2357
     * @return string
2358
     */
2359
    public static function paginationIndicator($current, $total)
2360
    {
2361
        $html = null;
2362
        if (!empty($current) && !empty($total)) {
2363
            $label = sprintf(get_lang('%s of %s'), $current, $total);
2364
            $html = self::url($label, '#', ['class' => 'btn disabled']);
2365
        }
2366
2367
        return $html;
2368
    }
2369
2370
    /**
2371
     * @param $url
2372
     * @param $currentPage
2373
     * @param $pagesCount
2374
     * @param $totalItems
2375
     *
2376
     * @return string
2377
     */
2378
    public static function getPagination($url, $currentPage, $pagesCount, $totalItems)
2379
    {
2380
        $pagination = '';
2381
        if ($totalItems > 1 && $pagesCount > 1) {
2382
            $pagination .= '<ul class="pagination">';
2383
            for ($i = 0; $i < $pagesCount; $i++) {
2384
                $newPage = $i + 1;
2385
                if ($currentPage == $newPage) {
2386
                    $pagination .= '<li class="active"><a href="'.$url.'&page='.$newPage.'">'.$newPage.'</a></li>';
2387
                } else {
2388
                    $pagination .= '<li><a href="'.$url.'&page='.$newPage.'">'.$newPage.'</a></li>';
2389
                }
2390
            }
2391
            $pagination .= '</ul>';
2392
        }
2393
2394
        return $pagination;
2395
    }
2396
2397
    /**
2398
     * Adds a legacy message in the queue.
2399
     *
2400
     * @param string $message
2401
     */
2402
    public static function addFlash($message)
2403
    {
2404
        // Detect type of message.
2405
        $parts = preg_match('/alert-([a-z]*)/', $message, $matches);
2406
        $type = 'primary';
2407
        if ($parts && isset($matches[1]) && $matches[1]) {
2408
            $type = $matches[1];
2409
        }
2410
        // Detect legacy content of message.
2411
        $result = preg_match('/<div(.*?)\>(.*?)\<\/div>/s', $message, $matches);
2412
        if ($result && isset($matches[2])) {
2413
            Container::getSession()->getFlashBag()->add($type, $matches[2]);
2414
        }
2415
    }
2416
2417
    /**
2418
     * Get the profile edition link for a user.
2419
     *
2420
     * @param int  $userId  The user id
2421
     * @param bool $asAdmin Optional. Whether get the URL for the platform admin
2422
     *
2423
     * @return string The link
2424
     */
2425
    public static function getProfileEditionLink($userId, $asAdmin = false)
2426
    {
2427
        $editProfileUrl = api_get_path(WEB_CODE_PATH).'auth/profile.php';
2428
        if ($asAdmin) {
2429
            $editProfileUrl = api_get_path(WEB_CODE_PATH)."admin/user_edit.php?user_id=".intval($userId);
2430
        }
2431
2432
        return $editProfileUrl;
2433
    }
2434
2435
    /**
2436
     * Get the vCard for a user.
2437
     *
2438
     * @param int $userId The user id
2439
     *
2440
     * @return string *.*vcf file
2441
     */
2442
    public static function getVCardUserLink($userId)
2443
    {
2444
        $vCardUrl = api_get_path(WEB_PATH).'main/social/vcard_export.php?userId='.intval($userId);
2445
2446
        return $vCardUrl;
2447
    }
2448
2449
    /**
2450
     * @param string $content
2451
     * @param string $title
2452
     * @param string $footer
2453
     * @param string $type        primary|success|info|warning|danger
2454
     * @param string $extra
2455
     * @param string $id
2456
     * @param string $customColor
2457
     * @param string $rightAction
2458
     *
2459
     * @return string
2460
     */
2461
    public static function panel(
2462
        $content,
2463
        $title = '',
2464
        $footer = '',
2465
        $type = 'default',
2466
        $extra = '',
2467
        $id = '',
2468
        $customColor = '',
2469
        $rightAction = ''
2470
    ) {
2471
        $headerStyle = '';
2472
        if (!empty($customColor)) {
2473
            $headerStyle = 'style = "color: white; background-color: '.$customColor.'" ';
2474
        }
2475
2476
        if (!empty($rightAction)) {
2477
            $rightAction = '<span class="float-right">'.$rightAction.'</span>';
2478
        }
2479
2480
        $title = !empty($title) ? '<h5 class="card-title">'.$title.' '.$rightAction.'</h5>'.$extra : '';
2481
        $footer = !empty($footer) ? '<p class="card-text"><small class="text-muted">'.$footer.'</small></p>' : '';
2482
        $typeList = ['primary', 'success', 'info', 'warning', 'danger'];
2483
        $style = !in_array($type, $typeList) ? 'default' : $type;
2484
2485
        if (!empty($id)) {
2486
            $id = " id='$id'";
2487
        }
2488
        $cardBody = $title.' '.self::contentPanel($content).' '.$footer;
2489
2490
        $panel = Display::tag('div', $cardBody, ['id' => 'card-'.$id, 'class' => 'card-body']);
2491
2492
        return '
2493
            <div '.$id.' class="card">
2494
                '.$panel.'
2495
            </div>'
2496
        ;
2497
    }
2498
2499
    /**
2500
     * @param string $content
2501
     */
2502
    public static function contentPanel($content): string
2503
    {
2504
        if (empty($content)) {
2505
            return '';
2506
        }
2507
2508
        return '<div class="card-text">'.$content.'</div>';
2509
    }
2510
2511
    /**
2512
     * Get the button HTML with an Awesome Font icon.
2513
     *
2514
     * @param string $text        The button content
2515
     * @param string $url         The url to button
2516
     * @param string $icon        The Awesome Font class for icon
2517
     * @param string $type        Optional. The button Bootstrap class. Default 'default' class
2518
     * @param array  $attributes  The additional attributes
2519
     * @param bool   $includeText
2520
     *
2521
     * @return string The button HTML
2522
     */
2523
    public static function toolbarButton(
2524
        $text,
2525
        $url,
2526
        $icon = 'check',
2527
        $type = null,
2528
        array $attributes = [],
2529
        $includeText = true
2530
    ) {
2531
        $buttonClass = "btn btn-outline-secondary";
2532
        if (!empty($type)) {
2533
            $buttonClass = "btn btn-$type";
2534
        }
2535
        $icon = self::tag('i', null, ['class' => "fa fa-$icon fa-fw", 'aria-hidden' => 'true']);
2536
        $attributes['class'] = isset($attributes['class']) ? "$buttonClass {$attributes['class']}" : $buttonClass;
2537
        $attributes['title'] = isset($attributes['title']) ? $attributes['title'] : $text;
2538
2539
        if (!$includeText) {
2540
            $text = '<span class="sr-only">'.$text.'</span>';
2541
        }
2542
2543
        return self::url("$icon $text", $url, $attributes);
2544
    }
2545
2546
    public static function toolbarAction(string $id, array $contentList): string
2547
    {
2548
        $col = count($contentList);
2549
        $html = ' <div id="'.$id.'" class="q-card">';
2550
        $html .= ' <div class="flex justify-between mb-3 '.$col.'">';
2551
        foreach ($contentList as $item) {
2552
            $html .= '<div class=" flex p-3 gap-2 ">'.$item.'</div>';
2553
        }
2554
        $html .= '</div>';
2555
        $html .= '</div>';
2556
2557
        return $html;
2558
    }
2559
2560
    /**
2561
     * Get a HTML code for a icon by Font Awesome.
2562
     *
2563
     * @param string     $name            The icon name. Example: "mail-reply"
2564
     * @param int|string $size            Optional. The size for the icon. (Example: lg, 2, 3, 4, 5)
2565
     * @param bool       $fixWidth        Optional. Whether add the fw class
2566
     * @param string     $additionalClass Optional. Additional class
2567
     *
2568
     * @return string
2569
     */
2570
    public static function returnFontAwesomeIcon(
2571
        $name,
2572
        $size = '',
2573
        $fixWidth = false,
2574
        $additionalClass = ''
2575
    ) {
2576
        $className = "fa fa-$name";
2577
2578
        if ($fixWidth) {
2579
            $className .= ' fa-fw';
2580
        }
2581
2582
        switch ($size) {
2583
            case 'xs':
2584
            case 'sm':
2585
            case 'lg':
2586
                $className .= " fa-{$size}";
2587
                break;
2588
            case 2:
2589
            case 3:
2590
            case 4:
2591
            case 5:
2592
                $className .= " fa-{$size}x";
2593
                break;
2594
        }
2595
2596
        if (!empty($additionalClass)) {
2597
            $className .= " $additionalClass";
2598
        }
2599
2600
        $icon = self::tag('em', null, ['class' => $className]);
2601
2602
        return "$icon ";
2603
    }
2604
2605
    /**
2606
     * @param string     $title
2607
     * @param string     $content
2608
     * @param null       $id
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $id is correct as it would always require null to be passed?
Loading history...
2609
     * @param array      $params
2610
     * @param null       $idAccordion
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $idAccordion is correct as it would always require null to be passed?
Loading history...
2611
     * @param null       $idCollapse
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $idCollapse is correct as it would always require null to be passed?
Loading history...
2612
     * @param bool|true  $open
2613
     * @param bool|false $fullClickable
2614
     *
2615
     * @return string
2616
     *
2617
     * @todo rework function to easy use
2618
     */
2619
    public static function panelCollapse(
2620
        $title,
2621
        $content,
2622
        $id = null,
2623
        $params = [],
2624
        $idAccordion = null,
2625
        $idCollapse = null,
2626
        $open = true,
2627
        $fullClickable = false
2628
    ) {
2629
        if (!empty($idAccordion)) {
2630
            $headerClass = '';
2631
            $headerClass .= $fullClickable ? 'center-block ' : '';
2632
            $headerClass .= $open ? '' : 'collapsed';
2633
            $contentClass = 'panel-collapse collapse ';
2634
            $contentClass .= $open ? 'in' : '';
2635
            $ariaExpanded = $open ? 'true' : 'false';
2636
2637
            $html = <<<HTML
2638
                <div class="card" id="$id">
2639
                    <div class="card-header">
2640
                        $title
2641
                    </div>
2642
                    <div class="card-body">$content</div>
2643
                </div>
2644
HTML;
2645
        } else {
2646
            if (!empty($id)) {
2647
                $params['id'] = $id;
2648
            }
2649
            $params['class'] = 'card';
2650
            $html = '';
2651
            if (!empty($title)) {
2652
                $html .= '<div class="card-header">'.$title.'</div>'.PHP_EOL;
2653
            }
2654
            $html .= '<div class="card-body">'.$content.'</div>'.PHP_EOL;
2655
            $html = self::div($html, $params);
2656
        }
2657
2658
        return $html;
2659
    }
2660
2661
    /**
2662
     * Returns the string "1 day ago" with a link showing the exact date time.
2663
     *
2664
     * @param string $dateTime in UTC or a DateTime in UTC
2665
     *
2666
     * @return string
2667
     */
2668
    public static function dateToStringAgoAndLongDate($dateTime)
2669
    {
2670
        if (empty($dateTime) || '0000-00-00 00:00:00' === $dateTime) {
2671
            return '';
2672
        }
2673
2674
        if ($dateTime instanceof \DateTime) {
0 ignored issues
show
introduced by
$dateTime is never a sub-type of DateTime.
Loading history...
2675
            $dateTime = $dateTime->format('Y-m-d H:i:s');
2676
        }
2677
2678
        return self::tip(
2679
            date_to_str_ago($dateTime),
2680
            api_convert_and_format_date($dateTime, DATE_TIME_FORMAT_LONG)
2681
            //api_get_local_time($dateTime)
2682
        );
2683
    }
2684
2685
    /**
2686
     * @param array  $userInfo
2687
     * @param string $status
2688
     * @param string $toolbar
2689
     *
2690
     * @return string
2691
     */
2692
    public static function getUserCard($userInfo, $status = '', $toolbar = '')
2693
    {
2694
        if (empty($userInfo)) {
2695
            return '';
2696
        }
2697
2698
        if (!empty($status)) {
2699
            $status = '<div class="items-user-status">'.$status.'</div>';
2700
        }
2701
2702
        if (!empty($toolbar)) {
2703
            $toolbar = '<div class="btn-group pull-right">'.$toolbar.'</div>';
2704
        }
2705
2706
        return '<div id="user_card_'.$userInfo['id'].'" class="card d-flex flex-row">
2707
                    <img src="'.$userInfo['avatar'].'" class="rounded" />
2708
                    <h3 class="card-title">'.$userInfo['complete_name'].'</h3>
2709
                    <div class="card-body">
2710
                       <div class="card-title">
2711
                       '.$status.'
2712
                       '.$toolbar.'
2713
                       </div>
2714
                    </div>
2715
                    <hr />
2716
              </div>';
2717
    }
2718
2719
    /**
2720
     * @param string $fileName
2721
     * @param string $fileUrl
2722
     *
2723
     * @return string
2724
     */
2725
    public static function fileHtmlGuesser($fileName, $fileUrl)
2726
    {
2727
        $data = pathinfo($fileName);
2728
2729
        //$content = self::url($data['basename'], $fileUrl);
2730
        $content = '';
2731
        switch ($data['extension']) {
2732
            case 'webm':
2733
            case 'mp4':
2734
            case 'ogg':
2735
                $content = '<video style="width: 400px; height:100%;" src="'.$fileUrl.'"></video>';
2736
                // Allows video to play when loading during an ajax call
2737
                $content .= "<script>jQuery('video:not(.skip), audio:not(.skip)').mediaelementplayer();</script>";
2738
                break;
2739
            case 'jpg':
2740
            case 'jpeg':
2741
            case 'gif':
2742
            case 'png':
2743
                $content = '<img class="img-responsive" src="'.$fileUrl.'" />';
2744
                break;
2745
            default:
2746
                //$html = self::url($data['basename'], $fileUrl);
2747
                break;
2748
        }
2749
        //$html = self::url($content, $fileUrl, ['ajax']);
2750
2751
        return $content;
2752
    }
2753
2754
    /**
2755
     * @param string $frameName
2756
     *
2757
     * @return string
2758
     */
2759
    public static function getFrameReadyBlock($frameName)
2760
    {
2761
        $webPublicPath = api_get_path(WEB_PUBLIC_PATH);
2762
        $videoFeatures = [
2763
            'playpause',
2764
            'current',
2765
            'progress',
2766
            'duration',
2767
            'tracks',
2768
            'volume',
2769
            'fullscreen',
2770
            'vrview',
2771
            'markersrolls',
2772
        ];
2773
        $features = api_get_configuration_value('video_features');
2774
        $videoPluginsJS = [];
2775
        $videoPluginCSS = [];
2776
        if (!empty($features) && isset($features['features'])) {
2777
            foreach ($features['features'] as $feature) {
2778
                if ('vrview' === $feature) {
2779
                    continue;
2780
                }
2781
                $defaultFeatures[] = $feature;
2782
                $videoPluginsJS[] = "mediaelement/plugins/$feature/$feature.js";
2783
                $videoPluginCSS[] = "mediaelement/plugins/$feature/$feature.css";
2784
            }
2785
        }
2786
2787
        $videoPluginFiles = '';
2788
        foreach ($videoPluginsJS as $file) {
2789
            $videoPluginFiles .= '{type: "script", src: "'.$webPublicPath.'assets/'.$file.'"},';
2790
        }
2791
2792
        $videoPluginCssFiles = '';
2793
        foreach ($videoPluginCSS as $file) {
2794
            $videoPluginCssFiles .= '{type: "stylesheet", src: "'.$webPublicPath.'assets/'.$file.'"},';
2795
        }
2796
2797
        $translateHtml = '';
2798
        $translate = api_get_configuration_value('translate_html');
2799
        if ($translate) {
2800
            $translateHtml = '{type:"script", src:"'.api_get_path(WEB_AJAX_PATH).'lang.ajax.php?a=translate_html&'.api_get_cidreq().'"},';
2801
        }
2802
2803
        $lpJs = api_get_path(WEB_PUBLIC_PATH).'build/lp.js';
2804
        // {type:"script", src:"'.api_get_jquery_ui_js_web_path().'"},
2805
        // {type:"script", src: "'.$webPublicPath.'build/libs/mediaelement/plugins/markersrolls/markersrolls.js"},
2806
        // {type:"script", src:"'.$webPublicPath.'build/libs/mathjax/MathJax.js?config=AM_HTMLorMML"},
2807
        $videoFeatures = implode("','", $videoFeatures);
2808
        $frameReady = '
2809
        $.frameReady(function() {
2810
             $(function () {
2811
                $("video:not(.skip), audio:not(.skip)").mediaelementplayer({
2812
                    pluginPath: "'.$webPublicPath.'assets/mediaelement/plugins/",
2813
                    features: [\''.$videoFeatures.'\'],
2814
                    success: function(mediaElement, originalNode, instance) {
2815
                        '.ChamiloApi::getQuizMarkersRollsJS().'
2816
                    },
2817
                    vrPath: "'.$webPublicPath.'assets/vrview/build/vrview.js"
2818
                });
2819
            });
2820
        },
2821
        "'.$frameName.'",
2822
        [
2823
            {type:"script", src:"'.$lpJs.'", deps: [
2824
2825
            {type:"script", src:"'.api_get_path(WEB_CODE_PATH).'glossary/glossary.js.php?'.api_get_cidreq().'"},
2826
2827
            {type:"script", src: "'.$webPublicPath.'build/libs/mediaelement/mediaelement-and-player.min.js",
2828
                deps: [
2829
                {type:"script", src: "'.$webPublicPath.'build/libs/mediaelement/plugins/vrview/vrview.js"},
2830
                '.$videoPluginFiles.'
2831
            ]},
2832
            '.$translateHtml.'
2833
            ]},
2834
            '.$videoPluginCssFiles.'
2835
        ]);';
2836
2837
        return $frameReady;
2838
    }
2839
2840
    /**
2841
     * @param string $image
2842
     * @param int    $size
2843
     *
2844
     * @return string
2845
     */
2846
    public static function get_icon_path($image, $size = ICON_SIZE_SMALL)
2847
    {
2848
        return self::return_icon($image, '', [], $size, false, true);
2849
    }
2850
2851
    /**
2852
     * @param string $image
2853
     * @param int    $size
2854
     * @param string $name
2855
     *
2856
     * @return string
2857
     */
2858
    public static function get_image($image, $size = ICON_SIZE_SMALL, $name = '')
2859
    {
2860
        return self::return_icon($image, $name, [], $size);
2861
    }
2862
2863
    public static function dropdownMenu($items = [], array $attr = [])
2864
    {
2865
        $links = null;
2866
        $url = null;
2867
        foreach ($items as $row) {
2868
            $url = self::url($row['icon'].$row['item'], $row['url'], ['class' => 'dropdown-item']);
2869
            $links .= self::tag('li', $url);
2870
        }
2871
        $html = self::tag('ul', $links, $attr);
2872
2873
        return $html;
2874
    }
2875
2876
    /**
2877
     * @param $id
2878
     *
2879
     * @return array|mixed
2880
     */
2881
    public static function randomColor($id)
2882
    {
2883
        static $colors = [];
2884
2885
        if (!empty($colors[$id])) {
2886
            return $colors[$id];
2887
        } else {
2888
            $color = substr(md5(time() * $id), 0, 6);
2889
            $c1 = hexdec(substr($color, 0, 2));
2890
            $c2 = hexdec(substr($color, 2, 2));
2891
            $c3 = hexdec(substr($color, 4, 2));
2892
            $luminosity = $c1 + $c2 + $c3;
2893
2894
            $type = '#000000';
2895
            if ($luminosity < (255 + 255 + 255) / 2) {
2896
                $type = '#FFFFFF';
2897
            }
2898
2899
            $result = [
2900
                'color' => '#'.$color,
2901
                'luminosity' => $type,
2902
            ];
2903
            $colors[$id] = $result;
2904
2905
            return $result; // example: #fc443a
2906
        }
2907
    }
2908
}
2909